LocalStorage and SessionStorage

Last week, we covered the lifecycle of Angular applications and how services can be used as a cache for our data.

I mentioned that Angular apps are independent applications running in a browser tab and that closing such a tab “kills” the application and frees the memory used by our app – thus losing any data stored in our services. Using the browser’s refresh button would also clear everything – similar to a reboot of the application.

If we want a more persistent cache, we can use the localStorage API from Javascript. Learning that API takes five seconds:

The above code stores the string “Tom” in the browser localStorage under the key “myCat”. To read that value, later on, all we need is the following:

And that’s it! Such storage will remain in place if the user closes your app’s tab or even closes the browser and shuts down their computer. Your data stays in the browser storage if the user does not clear the browser’s cache.

Also, such data is stored based on the domain on your web app, so other websites cannot read your storage values, and you can’t access values from other websites either.

One last tip: To store objects or arrays in localStorage, we have to turn them into strings, which means we usually do the following:

And to read that object from localStorage:

Note that sessionStorage has the same API as localStorage, but follows different rules and has a shorter life span:

  • A page session lasts as long as the tab or the browser is open and survives over page reloads and restores.
  • Opening a page in a new tab or window creates a new session with the value of the top-level browsing context.
  • Opening multiple tabs/windows with the same URL creates sessionStorage for each tab/window.
  • Duplicating a tab copies the tab’s sessionStorage into the new tab.
  • Closing a tab/window ends the session and clears objects in sessionStorage.

Alain Chautard

Alain is a Google Developer Expert in Web Technologies, Angular, and Google Maps. His daily mission is to help development teams adopt Angular and build at scale with the framework. He has taught Angular on all six continents! A world traveler and photographer, Alain is also an international conference speaker, and a published author of several video courses.