Cookies have been with us for a long time (Internet Explorer v2 had support for them in October 1995). There’s nothing wrong with them, and they certainly made the web a more pleasant place, but after nearly 25 years a lot has changed.

Local Storage (you’ll find it under Web Storage on W3) is and isn’t a replacement for cookies. That’s what’s most confusing about it. In most cases, you can safely use localStorage instead of cookies and get the (wrong) impression that they are the same, while they are not. Read on to see a no-nonsense breakdown of how and when to use localStorage to replace cookies.

Revolution or evolution?

Local storage, or localStorage, or DOM storage or web storage (I’m not making these names up; all of them are in use, and all reference the same thing) got real-world adoption among popular browsers in 2012 as an “HTML5 feature”. It seemed like a godsend replacement for cookies. A fix for bloated requests carrying unneeded data all the time and size limitations. While it does “solve” those problems, it’s not an apples-for-apples replacement for cookies.

As the name implies, the data is stored locally, on the user’s device. Hence it doesn’t have to be transferred over the network with every HTTP request reducing the footprint and giving us a lot more space to save the data. That “local only” paradigm is the most significant difference between cookies and local storage. Cookies can be read both server-side and client-side, local storage only on client-side. That’s all there is to it. If your app heavily depends on reading cookies server-side and generating content based on it then switching to local storage will mean rewriting the app. If you only use cookies to store settings such as which tab is active in the interface, then local storage is an ideal replacement.

If you only use cookies to store settings such as which tab is active in the interface, then local storage is an ideal replacement for them.

Deceptionaly similar

The table below gives a clear insight into the differences and use cases of cookies, localStorage, and sessionStorage. While you can quickly glance at it to get the answer you need and leave, I’d recommend reading the somewhat lengthy footnotes that go into more details. Yes, I know you’re busy and want to view the next cat video, but things are not black and white so digging a bit deeper will do you good.

 

FeatureCookieslocalStoragesessionStorage
Maximum data size – more info4 kB5 MB5 MB
Blockable by users – more infoyesyesyes
Auto-expire option – more infoyesnoyes
Supported data types – more infostring onlystring onlystring only
Browser support – more infovery highvery highvery high
Accessible server-side – more infoyesnono
Data transferred on every HTTP request – more infoyesnono
Editable by users – more infoyesyesyes
Supported on SSL – more infoyesn/an/a
Can be accessed on – more infoserver-side & client-sideclient-side onlyclient-side only
Clearing / deleting – more infoPHP, JS & automaticJS onlyJS & automatic
Lifetime – more infoas specifiedtill deletedtill tab is closed
Secure data storage – more infononono

 

Digging deeper into web storage & cookies

The maximum amount of data you can store locally depends on the browser. There are no guarantees and if you want a safe bet, go below 5 MB, to about 2 MB. Use this handy tool to test the maximum allowed local storage size in your browser.

It’s a common scenario for users to block 3rd party or all cookies. The same rule applies to local storage. There are no guarantees, and your app has to work (or at least not break) in an environment where local storage is not available.

All cookies expire at some point, but people tend to set lifetime to a few years which seems forever in internet time. Local storage on the other hand never expires and is available till the app or user deletes it. Session storage gets purged when tab or window gets closed – no exceptions.

“What do you mean only strings can be saved? I save objects all the time!” JSON enables you to save objects and other data types in the form of a string. The conversion is done on reading and writing without your knowledge. With a sound library for dealing with cookies and local storage, you won’t have to think about data types. However, that doesn’t change the fact that only strings are natively supported.

There’s not a single client-side feature that all browsers support. It’s a sad fact, but still a fact. You can check for specific numbers on Can I Use but as far as cookies and local storage go I’d ignore all browsers that don’t support them. They are marginal and below 1%.

You can’t access localStorage via server-side processing only. You need JS too. When the user requests a page and PHP kicks in (or whatever server-side language you use) to generate it, you won’t have access to any local data, session or permanent. Once the page loads and JS kicks in you can access the local data and do whatever you need – adjust the user interface or utilize AJAX to send local data back to the server. So yes, you can get the local data back to the server but not in the same manner and the same moment as you’d with a cookie. Depending on your requirements this may be a deal-breaker when it comes to switching from cookies to local storage, so, please – plan ahead!

With local storage, no data is transferred between the client and the server (unless there’s code that explicitly does that). It’s great for reducing payload size. Cookies, on the other hand, are transferred as HTTP header field with every request on the set domain. That can’t be changed or selectively turned off.

Users “shouldn’t” access local data and change it directly (outside your app) but nothing is stopping them in doing so. There are numerous debugging tools available for editing locally stored data. So don’t trust local data or assume the user didn’t touch it. Always assume the worse.

While cookies do have a “secure” attribute that you can set, that does not protect the cookie in transit from the application to the browser. So it’s better than nothing but far from secure. Local storage, being a client-side only technology doesn’t know or care if you use HTTP or HTTPS. Security has to come from the way you handle data. Do not store any sensitive data such as credit card numbers or passwords in any form of local storage! Ever!

Do not store any sensitive data such as credit card numbers or passwords in any form of local storage! Ever!

A bit of code to get you started

This article is not meant to be a JavaScript web storage tutorial but to save you the trouble here’s a Hello World example with local storage;

// store a value
localStorage.setItem( 'name', 'John' );

// retrieve a value
localStorage.getItem( 'name' );

// remove the value
localStorage.removeItem( 'name' );

// only string values can be stored so for objects, use JSON
var post = {
  title: 'Cookies are old',
  author: 'Gordan'
}
localStorage.setItem( 'post', JSON.stringify( post ) );

// and to retrieve
var post = JSON.parse( localStorage.getItem( 'post' ) );

The code above works, and it’s as simple as possible. However, I do not recommend using it. As with cookies, nobody uses document.cookies to interact with them. There are minor cross-browser differences to take into account, and since they only store strings, you have to stringify and parse with JSON on every read and write. That’s why we use small libraries to help us handle cookies such as js-cookie. Same goes for local storage. Putting a small abstraction layer between your code and the API will help in the long run. I recommend store.js. It’s been around for a while, takes care of cross-browser nonsense and fallbacks and even has handy plugins that expand its features. If you’re interested in some coding practice create your own library and convert it into a jQuery plugin.

Cookies are bad, right? We need something new!

Cookies are not bad. They’ve been serving their purpose for decades and will continue to do so as local storage is not an “apples for apples” replacement. Cookies are, however showing signs of aging. Apart from that, some of their design shortcomings are not going away any time soon either. Namely “polluting” every request on the domain with cookie payload and small maximum payload size.

Inadequate and old or not, cookies are here to stay so don’t think local storage will take over completely any time soon. However, in some use-cases, local storage is without a doubt a better choice.

If you have (a lot of) data to store on the client side that rarely gets transferred to the server and that data doesn’t contain anything sensitive – start using local storage! It’s precisely what it was created for. You’ll create a faster app by making all HTTP requests on the domain lighter and get that warm fuzzy feeling of using something new.

Leave a Reply

Your email address will not be published. Required fields are marked *