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.
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 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.
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"
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!
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 localStorage.removeItem("type");
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:
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.
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 Web Storage (localStorage and sessionStorage)
This decision depends strongly on what you want to achieve. But there are few tips to help you decide:
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!