HTML5 Browser Storage: the Past, Present and Future

Share this article

I have slightly selfish reasons for writing this article; I can never remember all the client-side storage mechanisms available to HTML5 developers! I’ve possibly forgotten some now…

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:
  1. You want to increase performance. You can cache data client-side so it can be retrieved without additional server requests.
  2. You have a significant quantity of client-side-only data, e.g. HTML strings or widget configuration settings.
  3. You want you make your application work off-line.
Let’s browse the options.

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
The disadvantages:
  • 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 basic document.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
The disadvantages:
  • 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 and JSON.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.
The flip-side of cookie client/server sharing causes the biggest technical issue. Cookie data is sent in the HTTP header of every request and response. It’s therefore appended to every HTML page, image, CSS file, JavaScript file, Ajax call, etc. If you had 50Kb of cookie data and downloaded ten 1KB images, it would result in one megabyte of additional network traffic.

window.name (Past and Present)

The window.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
The disadvantages:
  • 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
The disadvantages:
  • 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
In summary: don’t use a Web SQL Database! See also: W3C Web SQL Database Specification

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
The disadvantages:
  • string values only — serialization may be necessary
  • unstructured data with no transactions, indexing or searching facilties
  • may exhibit poor performance on large datasets
See also:

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 disadvantages:
  • 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
See also:

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
The disadvantages:
  • 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
See also:

Summary

There we have it — no less than seven storage alternatives. My pragmatic recommendations at this point in time:
  1. JavaScript variables will always be necessary but only use them for volatile in-memory data. Avoid DOM attributes/properties when possible.
  2. 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.
  3. Use HTML5 Web Storage to store data off-line or when large volumes of client-side-only information is required.
  4. 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.
  5. Keep an eye on IndexedDB; it will eventually become a viable storage mechanism when legacy browsers die out.
  6. 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.
Or perhaps you have further thoughts? Comments on this article are closed. Have a question about HTML5? Why not ask it on our forums?

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 BucklerCraig Buckler
View Author

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.

HTML5 Dev CenterHTML5 Tutorials & Articlesweb storage
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week