Tutorials Books Videos Forums

Change the theme! Search!
Rambo ftw!

Customize Theme




Table of Contents

Cookies vs. localStorage vs. sessionStorage

by Dillion Megida   |   filed under JavaScript 101

Data! That is the magic sauce that makes our web sites and apps interesting and useful. While a lot of the data we interact with comes from the server, an equally large part of the data we rely on is stored locally (aka client-side) by our browser. There are many reasons why our favorites web sites and apps store some data locally. The biggest reason has to do with performance. Data we store locally is available nearly instantaneously to our browser, whereas the data stored remotely takes time to make its way from a server to your computer.

This means if our pages rely on any data for displaying frequently accessed information or page state, this data is typically stored locally. This information could be: 

There are a bunch of ways we can tell our browsers to store data locally. Three popular ways are cookies, local storage and session storage. In this article, we'll learn more about these three approaches, how they work, how they differ, and when to use one over the other.



One of the oldest and most common ways to store some data is by using cookies, introduced by Mosaic Netscape around 1994:

The idea behind cookies was simple. When navigating between pages, we needed a way to persist some information that would normally be lost when one page exits and another page loads. This was necessary because the relationship between our browser and a server is stateless. Each time you visit the same server, it will treat you as if it is the first time it has ever met you.

The Problem

Let's say you are logging-in to access parts of a web site that requires authentication. The interaction between your browser and the server may look as follows:

After you logged-in, when you navigate deeper into the site, your expectation might be to see the secure content. With our server being stateless and having no way to remember who you are, what will actually happen is this:

The server will have no idea that you were the authenticated browser from just a few moments ago. A server is a bit like a goldfish in the remembering department! Without a way to help our server remember us, any activity that actually requires the server to remember us won't work. Extending our authentication dilemma further, our entire browsing experience might be a series of log-in screens that get thrown at us with every navigation:

This is the stuff that nightmares are made of, right? 

Cookies FTW!

Cookies solve this remembering problem our servers have quite nicely. A cookie is just some text-based information. A cookie is set typically by the server itself, and it will contain the right level of details to help the server identify us:

With each navigation, our browser and server send this cookie (or cookies in some cases) along with whatever web request they are making. While the connection between our browser and the server is still stateless, the cookie information that is passed around acts like a log of our communication and helps our server recognize us:

There are a bunch of other details that we're glossing over here, but this is a high-level overview of how cookies can help our servers remember us…and make surfing the web a more fun and seamless experience.

What exactly is a cookie?

As we saw earlier, a cookie is just some text-based information. This information has a structure made up of a series of key and value pairs. The following really long string is an example of what a cookie looks like:

"locale=en; _ga=GA1.2.1665695300.1566934440; cto_lwid=409ae255-69e8-4436-8956-08bf4b3d539e; last_active_role=personal; utag_main=v_id:016cd49217f900031bcd8acf3e2e03077003506f00fb8$_sn:3$_se:12$_ss:0$_st:1580768158108$ses_id:1580765219002%3Bexp-session$_pn:6%3Bexp-session; paper_theme_override=light; SnapABugHistory=11#; xsrf=9qh9HHD4tEqayfG0U05F9M; SnapABugUserAlias=%23; SnapABugVisit=2#1595374028"

Notice that the content stored by the cookie is a combination of human-readable information and a gibberish-looking mess of letters and numbers. That is totally normal. Some parts of the cookie will only make sense to our server and whatever unique identifier-like approach it uses to represent state. Other parts of the cookie, typically the more human-readable part, will be used by some client-side JavaScript to set or read some values.

The last detail to note is that not all cookies persist data the same. Session Cookies are ones that only exist for a particular browsing session and disappear when you close that tab. We then have Permanent Cookies that don't disappear when the browsing session is ended. These cookies can exist for a period of time specified in the cookie itself. They can exist for a few days, a few years, or more!

Web Storage (aka localStorage and sessionStorage)

Time to shift gears. While cookies were introduced a lifetime ago, the Web Storage API was introduced more recently. The idea behind web storage is to make storing and retrieving values very simple on the client-side (not server) using JavaScript and a common key/value arrangement.

Below is an example of how we can add and removing some values using it:

// Add items
localStorage.setItem("artist", "Tycho");
localStorage.setItem("album", "Awake");
localStorage.setItem("track", "Apogee");
localStorage.setItem("year", "2014");
localStorage.setItem("type", "vinyl");

// Remove an item

That doesn't seem too complex, right? If we had to visualize the keys and values stored, this is what we would see:

There are a few additional details to call out:

  1. Web Storage is all about client-side code. None of this data is read by a server. Think of this as your own personal database that you can use for your own needs.
  2. All of the operations we perform with the Web Storage APIs is tied to whatever domain our code is being run on. This level of isolation ensures that we don't accidentally (or deliberately!) modify any data that 3rd party sites may have already set in our storage. In other words, any data stored on foo.com is inaccessible to code that may be running on bar.com...and vice versa.

    If you were hoping to use Web Storage to persist or access some data across multiple sites on different domains, you are out of luck! That's probably a good thing from a privacy and security point of view ™

Digging one level deeper, what we call Web Storage is actually an umbrella term for two very similar objects: localStorage and sessionStorage. What sets them apart is for how long they persist the data we store. The localStorage API persists data indefinitely until a user chooses to delete all of their cached data via the browser. The sessionStorage API stores data for the current session of the browser. The current session here is the current tab. This means the next tab (even if it has the same page) does not know of the data stored in sessionStorage for the current tab. It works similarly for a different window.

To go into more detail on the Web Storage API, check out this article on the site.

Comparison and Use cases

Now that we've seen more about cookies and Web Storage (aka localStorage and sessionStorage), let's summarize their interesting details and look at the use cases.

For Cookies

For Web Storage (localStorage and sessionStorage)

Which should you use?

This decision depends strongly on what you want to achieve. But there are few tips to help you decide:

Wrap up

To tie everything we've talked about so far, cookies, localStorage, and sessionStorage are used to save temporal data to the browser. The browser makes a request to the server to fetch required assets, but some times, you need some data saved locally. In cases like sessions and cookies, the local data interacts with the server and in cases like local storage, it helps the browser get data faster.

You made it to the end! And now I believe you now know how these concepts work and how they differ. If you have any questions, feel free to post on the forums.

Hi, I'm Dillion! I am a frontend engineer passionate about learning, teaching and building web applications. Check out my blog and follow me on Twitter!

The KIRUPA Newsletter

Thought provoking content that lives at the intersection of design 🎨, development 🤖, and business 💰 - delivered weekly to over a bazillion subscribers!


Creating engaging and entertaining content for designers and developers since 1998.



Loose Ends

:: Copyright KIRUPA 2024 //--