localStorage vs sessionStorage?

September 12, 2019
Thomas Duffy

Written by Thomas Duffy

localStorage vs sessionStorage

When developing web apps, there can be many reasons to store data on a users device rather than interacting with a database on a remote web server somewhere. For example, you may want to cache an API response or save the state of a form if the user leaves or refreshes the page. Which… by the way, can make someone want to frisbee their computer out the window if your website doesn’t support this behavior on a form longer than two fields! I’m sure anyone thats ever used a bad form on the web can relate to this feeling.

This type of caching experience is pretty common nowadays and can be accomplished in many different ways. In this post we’ll talk about the Web Storage API and its two methods, localStorage and sessionStorage. We’ll also cover the difference between the two and how and when to use them.

An easy quick explanation of localStorage and sessionStorage.

The Web Storage API a newer API that was released with HTML5. The purpose is to give us the ability to easily and securely store key / value pairs in the browser. You may be thinking, “Isn’t that what cookies do?”. Well yes, but the Web Storage API is really just designed to store larger amounts of data and not have to send it back and forth with network requests like cookies.

The two types of storage included in the Web Storage API are localStorage and sessionStorage.

The only main difference between localStorage and sessionStorage is that when using localStorage, the saved data will persist after the users session has ended. So if you close the browser or tab and then come back to the site, the data can still be retrieved. On the other hand when using sessionStorage the data would be removed after the tab or window is closed, hence the word “session” in the name sessionStorage.

Session Storage Local Storage
Amount of storage 5mb 10mb
Accessible From Browser Browser
Expires Closing tab or browser Does Not Expire
Sent with requests No No

The easy way to see what’s in localStorage.

Before we dive into how to use the Web Storage API its important we know how to inspect and debug what is in localStorage, aside from console logging the localStorage object.

The first step is to open your Chrome devtools. Then go to the Application tab.

second step for finding localStorage

Then, you should see localStorage and sessionStorage on the left panel.

third step for finding localStorage

If you click on either one you’ll see the key / values listed out in a table format. You should see something that looks like the image below minus the example values I added in.

forth step for finding localStorage

Just as a side note, you can actually add and delete values in localStorage / sessionStorage from this tool. This can be useful for testing and debugging.

How to add to localStorage / sessionStorage.

Saving data with localStorage and sessionStorage is done by passing two arguments to the setItem method. The first argument is the key or name of the value you are saving. You’ll use this key to access the value later, similar to reading and writing to a regular object. The second argument is the value you want to store.

Technically you can set a value in localStorage and sessionStorage the following ways, but its recommended to stick with the setItem method.

localStorage.setItem(‘key’, ‘value’)
localStorage[‘key'] = ‘value’;
localStorage.key = ‘value’;

sessionStorage.setItem(‘key’, ‘value’)
sessionStorage[‘key'] = ‘value’;
sessionStorage.key = ‘value’;

How to read an entry in localStorage / sessionStorage.

To read from localStorage / sessionStorage we’re gonna use the the getItem method. This method only takes the key of a previously set value. So for example, let’s say we set someone’s first name using

// Writing
localStorage.setItem(‘firstName’, ‘Jimmy’)

we would then access that data with the following.

// Reading
localStorage.getItem(‘firstName’)

which would output ‘Jimmy’. If you passed in a key that wasn’t set or was cleared out, then the method would just return null.

Also, just like setting data you can technically read the data like you would a plain Javascript object, but it’s recommended to use the provided getItem method.

How to edit an entry.

Making updates is identical to the way we set the data, you just have to call the setItem method with the same key that was used to set the data and pass in an updated value. Lets take a look at an example.

Let’s say you set someone’s name with

\\ Writing
localStorage.setItem(‘firstName’, ‘Jimmy’)

and you wanted to update it to ‘Carl’. You would simply just call

\\ Updating
localStorage.setItem(‘firstName’, ‘Carl’)

and that value will now be updated to ‘Carl’.

How to delete an entry.

To delete an entry from localStorage / sessionStorage you would use the removeItem method. You simply would just pass in the key you would like to remove. So if I wanted to delete ‘Carl’ from my previous entry, I would just call

localStorage.removeItem(‘firstName’)

and poof, its gone. If you would like to completely clear out all values in localStorage you can simply call

localStorage.clear();

Browser Support

Browser support is actually really good for the Web Storage API considering HTML5 has been around since 2014. But if you do plan on supporting older browsers you should guard against the API not being available.

The simple check below should suffice.

if (window.localStorage) {
  // your code
}

How secure is the Web Storage API?

Because the data stored in the Web Storage API can easily be accessed and manipulated from the client browser, you shouldn’t use it to store any sensitive information. Some Good use cases include persisting state on forms or storing a users geolocation for location based web apps. With the storage limit being upwards of 10MB’s I’ve even seen API responses being cached for a good perceived performance boost.

Conclusion

To sum everything up, you can see that localStorage and sessionStorage are actually part of the same Web Storage API. They are pretty much identical besides the expiration factor. So it really just boils down to your individual use case for storing the data.

If you need the data to just survive a refresh but not the browser being closed, then use sessionStorage. But, if you want the data to persist no matter if the user session ends or not, then it’s safe to say localStorage is your best bet.


Thomas Duffy

Written by Thomas Duffy