# Cookies vs. localStorage vs. sessionStorage by [Dillion Megida](https://dillionmegida.com/me) | filed under [JavaScript 101](https://www.kirupa.com/javascript/learn_javascript.htm) 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: - Data from a previous browsing session like your username, the contents of a shopping cart, items in a ToDo list, etc. - Personalization settings that affect how your page renders - settings like color scheme, font size, whether some UI elements are visible or not - Data you want to keep handy if the network connection goes offline - Tracking and analytics data that needs to be updated frequently - …and much MUCH more! 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. Onwards! ## Cookies One of the oldest and most common ways to store some data is by using cookies, introduced by [Mosaic Netscape around 1994](https://en.wikipedia.org/wiki/File:Mosaic_Netscape_0.9_on_Windows_XP.png): ![](https://www.kirupa.com/hodgepodge/images/netscape_original_cookies.png) 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: ![](https://www.kirupa.com/hodgepodge/images/server_comm_200.png) 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: ![](https://www.kirupa.com/hodgepodge/images/server_comm_nope_200.png) 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: ![](https://www.kirupa.com/hodgepodge/images/logging_in.png) 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: ![](https://www.kirupa.com/hodgepodge/images/server_comm_cookie_200.png) 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: ![](https://www.kirupa.com/hodgepodge/images/server_comm_nope_cookie_200.png) 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: ```html "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](https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie) 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: ```js // 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: ![](https://www.kirupa.com/things_to_do_with_data/images/key_values_tycho_144.png) 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. 1. 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. 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](https://www.kirupa.com/things_to_do_with_data/web_storage.htm). ## 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** - They can exist for as long as until the expiration date. If not specified, it exists till the browser is terminated. - They are sent by the browser with the request to the website they were saved for. - They help the server 'remember' the things the browser and server share in common. - Can only take up about 4kb of space on disk, so you are limited in - Use case: **For Web Storage** (localStorage and sessionStorage) - They can be saved for as long as possible - They can only be accessed by pages of the same domain - They can store up to 5mb of data by default - For sessionStorage specifically, the data can be saved only for as long as the current page (tab) is open. Only the current page can have access to this store. The next tab (even though holding the same page) knows nothing about this store. - Use case: Dark theme, light theme To retain the current layout of a website. Say, for example, the user clicks a button that opens a new layout without making a request to the server or changing the URL, sessionStorage can be used to save that layout so that on refresh, the user remains where they are. ## Which should you use? This decision depends strongly on what you want to achieve. But there are few tips to help you decide: - If you want a page to always (in different instances and tabs) know of something, sessionStorage would be a wrong choice. Rather, localStorage is your friend. - If you server doesn't need to know of any local data you want to save, saving in cookies may not be the best choice. - If the server needs to know about a saved data, cookie is your goto! ## 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](https://forum.kirupa.com).