Understanding sessionStorage and localStorage in JavaScript

For training and consulting, write to us at info@xrmforyou.com

Before the advent of HTML 5, all our data in client side used to be stored in cookies. As that was the only option then. The problem with cookies was it was included in every server request. And also the more the cookies you store, you tend to slow down your browser performance.
Then came HTML 5 which swept the tech community by storm. Tons and tons of feature with OOB support for so many things which needed plugins or extra code to accomplish!
Html5 you beauty!

With HTML5, we got the concept of webstorage in the form of sessionStorage and localStorage and guess what! Information is never transferred to the server.
So what’s the difference between them.

  • window.localStorage – This stores data in the browser with no expiration date. Which basically means that data stored using localStorage are not deleted when you close the browser session. So if you open up the browser again, it will still persist. But wait I haven’t revealed all my cards yet. Even though the value persist across sessions, it is specific to browser and the domain where you initially set the value.

So for example – I am in website – https://xrm20206.crm.dynamics.com and I set a local storage value using localStorage.setItem(“key1”, “Let’ Test you persistence here”);
Now I close my browser and again open the same browser and this time I browse my blog – Dynamics and PowerApps Blog. If I try to get the value of localStorage using localStorage.getItem(“key1”), I would get the value as undefined. Understandably so. Otherwise it imposes huge security risk.

  • window.sessionStorage – stores the data for only one session and the value is lost when the browser tab is closed. This is very useful when you try to pass the session specific data across pages. But if you close the browser and open the same website again, you won’t get the value of sessionStorage you set earlier.

And finally before I end my blog, sample code to get and set values using sessionStorage and localStorage.

// session storage.
window.sessionStorage.setItem(“key1”, “Value1”);
window.sessionStorage.getItem(“key1”);
// local storage
window.localStorage.setItem(“key1”, “Value1”);
window.localStorage.getItem(“key1”);

Hope this helps!
Debajit Dutta
(Microsoft Business Solutions MVP)