- Key Takeaways
- Why Store Data on the Client?
- JavaScript Variables (Past, Present and Future)
- Cookies (Past, Present and Future)
- window.name (Past and Present)
- HTML5 Web SQL Database (Past)
- HTML5 Web Storage (Present and Future)
- HTML5 IndexedDB (Future)
- HTML5 File API (Future)
- Summary
- Frequently Asked Questions about HTML5 Browser Storage
Key Takeaways
- HTML5 offers several options for client-side data storage, including JavaScript variables, cookies, window.name, Web SQL Database, Web Storage, IndexedDB, and the File API. Each has its own advantages and disadvantages in terms of speed, simplicity, data persistence, and browser support.
- Cookies are a reliable method for retaining state between client and server, but they have limited storage space and are often seen as a threat to internet privacy. The window.name property is easy to use and retains data between browser refreshes, but it is not secure for storing sensitive information.
- HTML5 Web Storage is currently the most practical method for storing large volumes of client-side-only information. It is easy to use, widely supported across browsers, and provides both session and persistent storage options. However, it can only store string values and may have performance issues with large datasets.
- Future HTML5 storage options, such as IndexedDB and the File API, promise robust client-side data storage and access. However, they are currently not widely supported across browsers and their APIs are subject to change.
Why Store Data on the Client?
The main reason is practicality. JavaScript code running on the browser does not necessarily need to send all information to the server. There are several use cases:- You want to increase performance. You can cache data client-side so it can be retrieved without additional server requests.
- You have a significant quantity of client-side-only data, e.g. HTML strings or widget configuration settings.
- You want you make your application work off-line.
JavaScript Variables (Past, Present and Future)
The simplest choice is JavaScript variables. It may be practical to create a single global variable to store application data, e.g.// global application storage
var appDataStore = {};
// set values
appDataStore.hello = "Hello World!";
appDataStore.info = { a:1, b:2, c:3 };
// retrieve values
console.log(appDataStore.hello);
console.log(appDataStore.info.b);
It’s also possible to store values in the page DOM as node attributes or properties. This can be useful for widget-specific values, but it’s slower and riskier than JavaScript variables; future browsers or other libraries may interpret your data in unexpected ways.
// store data in node
var mywidget = document.getElementById("mywidget");
mywidget.setAttribute("data-myvalue", "Hello World!");
// retrieve values
mywidget.textContent = mywidget.getAttribute("data-myvalue");
The advantages of JavaScript variables:
- the fastest and simplest solution
- no need to serialize or de-serialize data
- ideal for single-page applications
- very fragile — linking elsewhere, refreshing or closing the tab will wipe all data
- global variables can be overwritten and analyzed by third-party scripts.
Cookies (Past, Present and Future)
Cookies are domain-specific chunks of text data. They sound tasty, but cookie handling is awkward in JavaScript since the basicdocument.cookie
string must be parsed, e.g.
// store cookie data
document.cookie = "hello=" + escape("Hello World") + "; path=/";
// retrieve value
cookies =
document.cookie.split(";"),
value = null,
regexp = new RegExp("^\s*hello=(.*)$");
for (var c = 0; c < cookies.length && !value; c++) {
var match = cookies[c].match(regexp);
if (match.length == 2) value = unescape(match[1]);
}
console.log(value);
The advantages of cookies:
- a reliable method of retaining state between the client and server
- by setting an expiry date, cookie data will persist beyond page refreshes and tab closing
- cookies are supported in all modern browsers
- clunky JavaScript implementation — you will need a cookie-handling library
- values are strings only — other data must be serialized using methods such as
JSON.stringify
andJSON.parse
- cookie storage space is limited — do not depend on having more than 20 cookies of 4KB each
- cookies can be deleted or blocked
- cookies were unfairly labeled as a threat to internet privacy; you may need to comply with bizarre regional rules and regulations.
window.name (Past and Present)
Thewindow.name
property is a little odd. You can set a single string value which persists between browser refreshes or linking elsewhere and clicking back, e.g.
window.name = "Hello World!";
console.log(window.name);
The advantages of window.name
:
- simple to use
- data is retained on the client only and never sent to the server
- the property permits several megabytes of information
- wide browser support
- data is lost when the tab or browser is closed
- only a single string value can be stored — serialization will be necessary
- pages in other domains can read or change
window.name
data — never use it for sensitive information
window.name
was never designed for data storage. It’s a hack and vendors could drop support at any time. For that reason, it’s best to use alternative storage options although the technique has been adopted within legacy browser shims and polyfills.
See also: How to Write a Cookie-less Session Library for JavaScript
HTML5 Web SQL Database (Past)
The Web SQL Database was an initial attempt by vendors to bring SQL-based relational databases to the browser. It has been implemented in Chrome, Safari and Opera 15+, but was opposed by Mozilla and Microsoft in favor of IndexedDB. The advantages of Web SQL Database:- designed for robust client-side data storage and access
- it uses SQL like many server side applications
- some support on Webkit/Blink desktop and mobile browsers
- SQL never seemed appropriate for client-side development
- the database schema must be defined up-front
- marginal browser support and the Webkit/Blink teams may eventually drop it
- the W3C specification was abandoned in 2010
HTML5 Web Storage (Present and Future)
Web Storage provides two objects with identical APIs:window.localStorage
to retain persistent data and code.sessionStorage
to retain session-only data which is lost when the tab is closed. Domain-specific strings are stored using name/value pairs. Unlike cookies, the storage limit is far larger (at least 5MB) and information is never transferred to the server.
// is localStorage available?
if (typeof window.localStorage != "undefined") {
// store
localStorage.setItem("hello", "Hello World!");
// retrieve
console.log(localStorage.getItem("hello"));
// delete
localStorage.removeItem("hello");
}
The advantages of Web Storage:
- easy to use with simple name/value pairs
- session and persistent storage options are available
- an event model is available to keep other tabs and windows synchronized
- wide support on desktop and mobile browsers including IE8+
- Web Storage polyfills are available for older browsers which fall-back to cookie and
windows.name
storage methods
- string values only — serialization may be necessary
- unstructured data with no transactions, indexing or searching facilties
- may exhibit poor performance on large datasets
HTML5 IndexedDB (Future)
IndexedDB provides a structured, transactional, high-performance NoSQL-like data store with a synchronous and asynchronous API. There’s too much to document here, but the API permits you to create databases, data stores and indexes, handle revisions, populate data using transactions, run non-blocking queries, and traverse data sets using cursors. The advantages of IndexedDB:- designed for robust client-side data storage and access
- good support in modern desktop browsers: IE10+, Firefox 23+, Chrome 28+ and Opera 16+
- the API is very new and subject to revision
- little support in older and mobile browsers
- a large and complex API — it would be difficult and largely impractical to create a IndexedDB polyfill
- like any NoSQL store, data is unstructured which can lead to integrity issues
HTML5 File API (Future)
The HTML5 File API is being extended to support writing as well as reading sequential data on the local file system. Your domain is provided with a complete sand-boxed hierarchical file system to use as it chooses. The advantages of the HTML5 File API:- large text and binary files can be created and stored
- performance should be good
- a very early specification which is subject to revision
- an obvious security risk unless file writing is restricted
- little support in current browsers and polyfills may be impractical
- unstructured data with no transactions, indexing or searching facilties
Summary
There we have it — no less than seven storage alternatives. My pragmatic recommendations at this point in time:- JavaScript variables will always be necessary but only use them for volatile in-memory data. Avoid DOM attributes/properties when possible.
- Assuming it’s necessary, use cookies for retaining state between the client and server. But keep cookies small; a single token with a few characters should be enough.
- Use HTML5 Web Storage to store data off-line or when large volumes of client-side-only information is required.
- If you have to support older browsers such as IE6 and IE7, use a Web Storage polyfill which implements the API using cookies and
window.name
. - Keep an eye on IndexedDB; it will eventually become a viable storage mechanism when legacy browsers die out.
- Similarly, the File API will become increasingly practical for storing unstructured data. It’s possibly the best solution for generated binary data such as images, audio, video and PDFs.
Frequently Asked Questions about HTML5 Browser Storage
What are the key advantages of using HTML5 for browser storage?
HTML5 offers several advantages for browser storage. Firstly, it provides a more secure and robust platform for storing data on the client-side. It supports both session storage and local storage, allowing developers to store data temporarily or permanently. Secondly, HTML5 storage is more efficient and faster than traditional cookies. It can store larger amounts of data, up to 5MB per domain, compared to cookies’ 4KB limit. Lastly, HTML5 storage is more flexible, as it allows for storing complex data types, not just strings.
Are there any limitations or disadvantages of HTML5 browser storage?
While HTML5 browser storage offers many benefits, it also has some limitations. The most significant limitation is the storage limit, which is typically 5MB per domain. This might not be sufficient for applications that need to store large amounts of data. Additionally, HTML5 storage is not supported by all browsers, especially older versions. Lastly, data stored using HTML5 is not secure and can be easily accessed by anyone who has access to the user’s computer.
How does HTML5 browser storage compare to Flash storage?
HTML5 and Flash storage have some similarities, but they also have significant differences. Both can store data on the client-side, but HTML5 storage is generally considered more secure and reliable. Flash storage requires the user to have the Flash plugin installed, which is not always the case, especially on mobile devices. On the other hand, HTML5 is supported by all modern browsers. Additionally, Flash storage has a larger storage limit of 100KB compared to HTML5’s 5MB.
Can I use HTML5 storage for sensitive data?
It’s not recommended to use HTML5 storage for storing sensitive data. The data stored using HTML5 is not encrypted and can be easily accessed by anyone who has access to the user’s computer. If you need to store sensitive data, it’s better to use secure server-side storage or encrypt the data before storing it using HTML5.
How can I check if a browser supports HTML5 storage?
You can check if a browser supports HTML5 storage by using the ‘localStorage’ in ‘window’ property. If this property exists, then the browser supports HTML5 storage. Here’s a simple code snippet that checks for HTML5 storage support:if ('localStorage' in window) {
console.log('This browser supports HTML5 storage');
} else {
console.log('This browser does not support HTML5 storage');
}
How can I increase the storage limit of HTML5?
The storage limit of HTML5 is set by the browser and cannot be increased by the developer. However, some browsers allow users to increase the storage limit manually through the browser settings. It’s important to note that increasing the storage limit might have security implications.
Can I store complex data types using HTML5 storage?
Yes, you can store complex data types using HTML5 storage. However, the data needs to be serialized before storing and deserialized after retrieving. You can use the JSON.stringify() method to serialize the data and the JSON.parse() method to deserialize the data.
How can I delete data from HTML5 storage?
You can delete data from HTML5 storage using the removeItem() method. Here’s a simple code snippet that deletes data from HTML5 storage:localStorage.removeItem('key');
Can I use HTML5 storage for offline applications?
Yes, HTML5 storage can be used for offline applications. It allows you to store data on the client-side, which can be accessed even when the user is offline. This makes HTML5 storage a great choice for applications that need to work offline.
How does HTML5 storage handle session management?
HTML5 storage provides two objects for storing data: localStorage and sessionStorage. The localStorage object stores data with no expiration date, while the sessionStorage object stores data for one session. The data in sessionStorage is deleted when the user closes the specific browser tab.
Craig is a freelance UK web consultant who built his first page for IE2.0 in 1995. Since that time he's been advocating standards, accessibility, and best-practice HTML5 techniques. He's created enterprise specifications, websites and online applications for companies and organisations including the UK Parliament, the European Parliament, the Department of Energy & Climate Change, Microsoft, and more. He's written more than 1,000 articles for SitePoint and you can find him @craigbuckler.