How to use localStorage?

Ashiq
Updated 1 Jun 2021
HIGHLIGHTS
  • Usage of localStoarge and sessionStorage
  • When we should use this storage
  • Security concern
  • Secure alternative storage

Almost every day I stumble across a new website storing sensitive user information in local storage and it bothers me to know that so many developers are opening themselves up to catastrophic security issues by doing so. Are you one among them? Local Storage were added in browser to make it easy for developer to cache basis adat which changes very often or never. But some developers are making wrong use of it by storing sensitive data in it.

By the way what is localStorage?

Local storage is a new feature of HTML5 that allows developer to store any information within the clients system through key value pairs. Unlike cookie it doesn't have any expiry and can't be set from server side. Only client side code can set and get the values of localStorage.


Saving data in localStorage is pretty straignht forward

localStorage.setItem('name', 'Jhon doe');
//or, simply
localStorage.name = 'Jhon doe;

Similarly to retrieve data from localStorage

localStorage.getItem('name');
//or, simply
localStorage.name;

To remove or clear localStorage data

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

//or, to remove all data from localStorage at once
localStorage.clear();

When to use localStorage

We can use LocalStorage to store user preferences, like settings, UI theme, incomplete form data, track user progress in large forms etc. Without a web server and database to save a user preference, localStorage allows user to continue using website with their customization.

Going serverless

You might develop a server application or game that relies on MQTT, Socket for data transmission and probably you dont have backend to manage the game, So how can you save data on browser's cookie, how can you track user's progress? Here localStorage comes into rescue, as you dont need help of server (Cookie can only be generated from server). Twist! If yor game is session bases i.e stores data on each session of game then also go for sessionStorage

Data types?

Oh no, localStorage stores only string. So how about storing bolean, array, object? Thers's a hack, stringify the data type (JSON.stringify())

Storage limit?

localStorage capacity varies browser to browser, with 2.5MB, 5MB and unlimited being the most common values. Browser implementations vary, but the amount of storage available is usually based on the amount of storage available on the device.


So, now we know localStorage doesn't have any expiry so how will data get deleted when we no longer needed? Luckily we have sessionStorage which stores data till the user keeps the tabs open, Unlike localStorage, sessionStorage will not keep data lifelong but once the tab is closed the data will be gone. One more difference is, sessionStorage are tab independent, one tab will not be able to read or write to another tab's sessionStorage data. So if you need to store data for a particualr session go to sessionStorage instead of localStorage

sessionStorage.setItem('name', 'Jhon doe');
//or, simply
sessionStorage.name = 'Jhon doe;

Storing array, object in localStorage

let data = {
	name : 'Dave',
	score : 34,
	history : [3,2,3,3],
	host : true
}
localStorage.userdata = JSON.stringify(data);
//retrieve the data
if(localStorage.userdata){
	let data = JSON.parse(localStorage.userdata);
	console.log(data);
}

So whats the major issue?

Both localStorage and sessionStorage are synchronous and will block the main thread, thus if you are using those in loops, very frequently, to store or retrived large block of data, we ⚠️warn you not to do so. It will give significant perfomance loss in such case.

Can localStorage be accessed by web workers?

Unfortunately no, web workers or service works wont be able to access localStorage/sessionStorage


📝 Tip : Cookies should not be used for storage of large data, or normal user prefence data as they are sent with every HTTP request, So storing KBs of data will increase the size of every web request.


Why should we worried about using localStorage?

<script src="https://compromised.com/script.js"></script>

What if you included a third party script and the script is compromised 😱? They can read all your localStorage and SesionStoarge data and send to their server. Think before you store sensitive data.

Neve store JSON Web Tokens in Local Storage. If an attacker get the JWT token, they can make request to your website. JWT as essentially the same as username and password. So avoid storing them in localStorage. In other words, any authentication your application requires can be bypassed by a user with local privileges to the machine on which the data is stored. Therefore, it's recommended not to store any sensitive information in local storage. 🕵🏼


🤷🏻‍ So what's the alternate?

Many a times we are required to store Session ID, JWT, API Keys etc. So whats the best storage for such scenerio? Cryptographically signed cookie could be a better choice, Yes it shouldn't be a lame token as attackers might be able to recreate weak tokens. Also make sure to use ✅httpOnly and ✅secure. Using httpOnly makes your cookie non-readable from client site, it can be only read by server if sent with the request. And secure ensures that cookies can only be set over an encrypted connection. One more point, DO NOT store large data on cookie (although limit is 2-4KB) as with every request those bytes of cookie will add to network load.


References

  1. developer.mozilla.org
  2. Secure Browser Storage