A Complete Guide to Web Storage APIs — Local Storage and Session Storage

Web Storage APIs are used by developers to store data into the browser to improve the user experience and performance of the web apps. The data here refers to the key-value pair of strings. Now storing this data can be done by two mechanisms: either by using the sessionStorage API and the localStorage API.
Session storage
- The data is stored in the browser’s memory for that specific session. The session here means until we close the browser window or tab.
- The storage limit of session storage is very high when compared to cookies. The cookies which can generally store around 4000 bytes of data and session storage can store at least 5 MB of data or even more than that depending on the device and browser.
Note:
1. Data survives a page refresh.
2.While restoring the tab (Ctrl+Shift+T), sessionStorage is maintained in the Chrome, Firefox but not in the Safari browser . It is browser dependent feature while restoring the tab.
Local storage
- It is almost the same as the session storage but the only difference is that it does not have an expiration time. So even if we close the browser window/tabs and restart the system and come back again anytime the data persists till we manually delete it. That makes it unique and very useful.
- localStorage can also store about 5 MB of data.
Note:
Data stored on normal browsing sessions will not be available when you open a browser in private browsing or in Incognito mode. It is also browser dependent feature.
Now let’s discuss common features to both local and session storage:
1) Both are used for storing the data on the client-side. the data is never transferred to the server while making a network request.
2) Both are stored on the window object of the browser — window.localStorage or localStorage and window.sessionStorage or sessionStorage.
3) Both are Object type — typeof localStorage and typeof sessionStorage is “object”
4) Both storage objects provide the same methods and properties:
setItem(key, value)
– store key/value pair.getItem(key)
– get the value by key.removeItem(key)
– remove the key with its value.clear()
– delete everything.key(index)
– get the key on a given position.length
– the number of stored items.
As we can see, it’s like a Map
collection (setItem/getItem/removeItem
), but also allows access by index with key(index)
.
5) Due to security reasons both follow the same-origin policy. Same-Origin refers to the same protocol (HTTP or HTTPS ), same host or domain(abc.com), and the same port(8080 or wherever the app is hosted). Session storage is different even for the document with the same-origin policy open in different tabs, so the same web page open in two different tabs cannot share the same session storage.
Suppose we store localStorage data in https://ayushv.medium.com/. Can we access the data on:
- https://ayushv.medium.com/data.php — Yes, we are of the same origin.
- http://ayushv.medium.com/— No, we are on different protocols.
- https://blog.ayushv.medium.com/— No, we are on a different domain. (subdomain added)
- https://ayushv.medium.com/:8080- No, we are on a different port.
6) Both local and session storage are also scoped by browser vendors. So storage data saved by IE cannot be read by Chrome or FF.
We can see all the local and session storage data for each site under the
Application
tab in chrome developer tools.
Examples and Practical usage:
1. localStorage.setItem(key, value)localStorage.setItem(“name”, “Ayush”)
localStorage.setItem(“name”, “Verma”)
//it will override2. localStorage.getItem(key)localStorage.getItem(“name”) 3. localStorage.removeItem(key)localStorage.removeItem(“name”)4. localStorage.clear()
5. localStorage.key(0)
6. localStorage.length
Generally, Web Storage APIs are used to store objects. JSON.stringify() and JSON.parse() are used to store and get objects.
Web Storage APIs are used a lot by many big companies to store some less relevant user-specific data into their browsers. Some companies even use it to optimize the performance of the web page speed as accessing local storage is faster than making a request to the server and getting the data. Companies like Flipkart and Paytm use localStorage for keeping a lot of data.
- Flipkart — Some information such as browsed products, navigation menu, autosuggest history all this user-specific data are being stored in the local storage.
- Paytm — They store a lot of data such as the recent searches for flights, recent cities we select, and even some session data into localStorage.
Use Storage objects for Browser Caching — We can cache some application data for later usage/run the app offline. For example, imagine you need to load currency data for all the countries. It can be saved in LocalStorage and not make HTTP requests every time you needed the list.
However, If you want it to load per session, you can use SessionStorage.
Use sessionStorage for modal — Suppose we have a modal on the page that displays some long-form to enter details. Many times it happens that, the user enters some data in the form, and by mistake clicks outside the modal and the modal gets closed. Because of which he loses all the entered data.
To avoid the loss of data, we can use sessionStorage so the stored data in modal will only be applicable to the current tab.
Tip — create own generic functions something like setLocalStorageData() and getLocalStorageData()
How Performance gets affected — Large complex applications can be slow due to the synchronous behaviour of storage objects. If you need more storage and performance, you can use IndexedDB or cache API.
Vulnerability to Cross-Site Scripting (XSS) Attacks
XSS attacks can be used to get data from storage objects and add malicious scripts to the data stored. Both are vulnerable to XSS Attacks. Therefore avoid storing sensitive data in browser storage.
It is not recommended to save sensitive data as Username/Password, Credit card info, JWT tokens, API keys, Personal info, and Session ids.
How to Mitigate Security Attacks?
- Do not use the same origin for multiple web applications. Instead, use subdomains since otherwise, the storage will be shared with all.
- Validate, encode and escape data read from browser storage.
- Encrypt data before saving.
Conclusion
You can choose LocalStorage vs. SessionStorage based on your use case. If your application needs data to be shared across multiple browser windows and tabs, use the LocalStorage otherwise, use the SessionStorage.
It’s recommended to use the browser storage when there is,
- No sensitive data
- Payload size up to 5MB
Thanks for reading :)