Skip to content

Cookies, localStorage and sessionStorage

BasicsConcept

Cookies, localStorage and sessionStorage all keep a string under a name, so they look interchangeable. They are not: here is who can read each one, when the browser sends it, and when it disappears.

01 Three places to keep a value

A shop wants to remember three things: who you are, that you like the dark theme, and what is in your basket. The browser offers three places to put them, and they look alike from the code:

JavaScript
document.cookie = 'theme=dark; Max-Age=31536000; Path=/';
localStorage.setItem('cart', JSON.stringify([3, 7]));
sessionStorage.setItem('checkoutStep', '2');

All three store short strings under a name. They differ in three ways that decide which one is right: who can read the value, when it is sent to a server, and when it disappears.

02 Who can read each one

A cookie belongs to a site and path: Domain and Path decide which requests carry it. Web storage belongs to an origin, the exact scheme, host and port: https://shop.example and http://shop.example get separate localStorage. sessionStorage is narrower still: one origin in one tab.

Who can read a stored value
StorePage scriptsThe serverOther tabs, same origin
CookieYes, via document.cookieYes, in every matching requestYes
Cookie with HttpOnlyNoYes, in every matching requestYes (the server sees it)
localStorageYesOnly if a script sends itYes
sessionStorageYesOnly if a script sends itNo: each tab has its own

“Page scripts” means every script running on that origin: your code, the analytics snippet, the chat widget, and anything an attacker manages to inject. The browser does not tell them apart.

03 When each one travels

The biggest difference is that cookies are sent by the browser, automatically, and web storage is never sent at all. Here is one page visit with all three kinds of value in play.

One page: what is stored, what is sent, what scripts see
Step 1 of 7
cookie jar for shop.example
Empty
localStorage for https://shop.example
Empty
requests the browser sends
Empty
  • just stored or sent
  • attached to a request
  • readable by scripts
  • stored

You open https://shop.example for the first time. The cookie jar and localStorage for this site are empty, and nothing has been sent yet.

This is why a session ID belongs in a cookie: the server needs it on every request, and HttpOnly keeps it away from scripts. It is also why cookies cost something: every matching request, including each image and stylesheet, carries them.

04 When each one disappears

Each store has its own clock. A cookie with no Max-Age or Expires is a session cookie; one with them is persistent.

When each store is cleared
StoreCleared whenSurvives a reload?
Session cookieThe browser session ends (typically when the browser quits, unless it restores the session)Yes
Persistent cookieIts Max-Age or Expires passes; Chrome caps this at 400 daysYes
localStorageCode or the user clears it; it has no expiry dateYes
sessionStorageThe tab closesYes
sessionStorageGoneIt belongs to the tab. Close the tab and the checkout step you saved is gone.
Session cookieKept for nowOther tabs keep the browser session alive, so the cookie lives until the browser quits.
localStorageKeptNothing in the browser expires it. It stays until something deletes it.

“No expiry” is not “forever”. Browsers clear storage when the disk runs low, when the user clears site data, and Safari typically deletes script-written storage for a site you have not interacted with for 7 days of browser use.

05 Try it in the console

Open DevTools on any site you control and paste this into the console. The Application panel (Chrome) or Storage panel (Firefox) lists all three stores, with each cookie’s flags and expiry.

JavaScript
document.cookie = 'theme=dark; Max-Age=31536000; Path=/';
localStorage.setItem('cart', JSON.stringify([3, 7]));
sessionStorage.setItem('checkoutStep', '2');
document.cookie; // 'theme=dark' (an HttpOnly cookie would not be listed)
localStorage.getItem('cart'); // '[3,7]' a string: parse it with JSON.parse
localStorage.setItem('n', 5);
typeof localStorage.getItem('n'); // 'string'

Then open the same site in a new tab and run sessionStorage.getItem("checkoutStep"). It returns null: the new tab has its own sessionStorage. localStorage.getItem("cart") still returns [3,7].

  • Size: a cookie is typically limited to about 4 KB, and localStorage to about 5 MB per origin. Both vary by browser.
  • Only strings: setItem("n", 5) stores "5", and an object without JSON.stringify stores "[object Object]".
  • Blocking: localStorage calls are synchronous, so reading a large value pauses the page while it loads.

06 Which one to pick

Pick by who needs the value and how long
You need to keepUseBecause
A session IDCookie: HttpOnly, Secure, SameSiteThe server needs it on every request; scripts must not read it
A theme the server rendersCookie (not HttpOnly)The server reads it to send the right HTML; scripts can change it
A form draft for this tabsessionStorageSurvives a reload, does not leak into another tab
UI preferences, cached public datalocalStorageLasts across visits, never adds bytes to requests

Anything in localStorage or sessionStorage, and any cookie without HttpOnly, can be read by every script on the page. One cross-site scripting bug is enough to send a token stored there to someone else. Sessions vs tokens goes into where an auth token should live.

07 When storage surprises you

document.cookie = 'theme=dark' // on /account/settingsA cookie that only some pages seeWithout Path, the cookie’s path defaults to the directory of the URL that set it, here /account. Pages under /shop never receive it. Set Path=/.
Set-Cookie: sid=a91f; Domain=shop.exampleDomain makes a cookie wider, not narrowerNaming a Domain sends the cookie to every subdomain too, such as blog.shop.example. Leave Domain out to keep it to the exact host.
localStorage.setItem('user', user)Storing an object without JSONStorage converts the value to a string, so you read back "[object Object]". Store JSON.stringify(user) and parse it on the way out.
Cookie: sid=…; prefs=…; ab=… (on every image)Cookies on every requestEvery matching request carries every matching cookie. Large cookies slow down each image and script request; keep them small.
http://localhost:3000 vs http://localhost:5173Two ports, two localStorages, one cookie jarWeb storage is split by port, cookies are not. A dev server on another port sees the same cookies but empty storage.

08 Check yourself

Question

You save a token with localStorage.setItem("token", t). Does the browser send it with the next fetch("/api/me")?

Question

A user fills half a form, opens a second tab of the same page, and looks for their draft. Where would it be visible in both tabs?

Question

The server sets Set-Cookie: sid=a91f; HttpOnly. What does document.cookie show?

09 Practise this

Was this tutorial useful?Your vote tells us what to improve next.
Spotted a mistake, or something unclear?