Secure Storage in the Browser — Security

localStorage and sessionStorage are two places to keep data in the browser. localStorage survives closing the browser, sessionStorage disappears when the tab…

Once a user logs in, where does the token (the sign that you logged in) go? Plenty of tutorials put it in localStorage: one line, done. Yet the place you choose decides what can be stolen if an attacker's script ever runs on your page (XSS).

The browser has three main places to keep data: localStorage, sessionStorage, and cookies. They differ in three ways: who can read them, when the data disappears, and whether the data is sent to the server. Picture an office with three places to leave an access card: an unlocked desk drawer, a whiteboard wiped every time the room empties, and a safe only the security guard can open. An intruder in the room can open the drawer and read the whiteboard, but can't open the safe. The access card is the login token, the drawer is localStorage, the whiteboard is sessionStorage (the room emptying is the tab closing), the safe is an HttpOnly cookie, the guard is the browser, and the intruder is the XSS script.

Three places, three behaviours

This table compares the three. Cookies are split in two: a plain cookie and an HttpOnly cookie.

localStorage sessionStorage Plain cookie HttpOnly cookie
Read by the page's JavaScript yes yes yes, through document.cookie no
Sent to the server no no yes, automatically yes, automatically
Gone when code or the user deletes it the tab closes it expires it expires
Capacity about 5 MB per origin about 5 MB per origin about 4 KB per cookie about 4 KB per cookie

Here is an example that uses all three:

localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); // "dark", still there tomorrow

sessionStorage.setItem("draft", "Hi, about my order...");
// close the tab: the draft is gone

document.cookie; // "theme=dark" (an HttpOnly cookie never shows up here)

What an XSS script reads

In the Lab, Budi logs in on https://myapp.com, and the server returns the JWT eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyfQ.c2lnbmF0dXJl. The app keeps that token in localStorage. Then a comment holding an injected script reaches the page without escaping. That script runs with the same rights as your own code, so it can read the storage right away. The lines that start with > are its commands, and the line under each one is the result:

> localStorage.getItem("token")
'eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyfQ.c2lnbmF0dXJl'
> document.cookie
'theme=dark'

With one more line of code, the token is sent to the attacker's server. With that token, the attacker can log in as Budi from the attacker's own computer, until the token expires. That's why a JWT must not be kept in localStorage: it's open to every piece of JavaScript on the page, XSS scripts included. sessionStorage is just as open, it only disappears sooner.

Cookies: only HttpOnly hides them from scripts

The safest place for a login token is an HttpOnly cookie. The server is the one that sets it, through a response header:

Set-Cookie: token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyfQ.c2lnbmF0dXJl; Max-Age=7200; Path=/; HttpOnly; Secure; SameSite=Lax

So a cookie with Secure and SameSite=Strict, but no HttpOnly, can still be read through document.cookie.

Your code doesn't need to touch the token either. The browser attaches the cookie by itself to every request to myapp.com. In fetch, credentials: "include" asks the browser to include cookies:

fetch("/api/orders", { credentials: "include" });

One more thing: an HttpOnly cookie can only be created by the server. If JavaScript writes document.cookie = "token=abc; HttpOnly", the browser ignores that cookie entirely.

What HttpOnly doesn't prevent

HttpOnly stops the token from being stolen, not from being used. While the page with the XSS is still open, the injected script can call fetch("/api/orders"), and the browser still attaches the cookie. But the difference is big: the attacker can't take the token home, so they can't use it from elsewhere after Budi closes the tab.

So HttpOnly limits the damage, but the real cure is still preventing XSS: output escaping and CSP, which you've already learned.

Where to keep what?

On logout, clean up everything. Remove items from storage with removeItem. The server should also send the token cookie again with Max-Age=0 (an age of zero seconds), so the browser drops it.

💡 What if the token in localStorage is encrypted?

It sounds safe, but it doesn't help against XSS. To decrypt the token, your code needs the key. That key is on the page too: in a variable, in storage, or as a CryptoKey (a key object from Web Crypto) in IndexedDB (a small database in the browser). An injected script runs with the same rights as your code, so it can use the same key to decrypt, or simply use the token directly. Encryption in the browser only helps when someone reads the browser's files on disk, not during XSS.

⚠️ Assumptions that make a token easy to steal

TL;DR: localStorage and sessionStorage are two places to keep data in the browser. localStorage survives closing the browser, sessionStorage disappears when the tab closes, and both can be read by any JavaScript on the page, XSS scripts included. That's why a JWT or login token must not be kept there: it's vulnerable to XSS, because an attacker can simply copy it. The safest place for a token is an HttpOnly cookie with Secure and SameSite, set by the server through Set-Cookie. HttpOnly is the only flag that hides a cookie from document.cookie. Secure and SameSite don't hide it. HttpOnly stops the token from being stolen, but not from being used while the page with the XSS is still open, so you still have to prevent the XSS. Keep preferences in localStorage, drafts in sessionStorage, and sensitive data out of the browser.

⚡ Three places, three behaviours

Write:

localStorage.setItem("theme", "dark");
sessionStorage.setItem("draft", "Hi, about my order...");

Meaning: localStorage and sessionStorage are two places to keep data in the browser. localStorage survives closing the browser, while sessionStorage disappears when the tab closes. Both can be read by any JavaScript on the page, and neither is sent to the server.

⚡ What an XSS script reads

Guess first: why must a JWT not be kept in localStorage?

It's vulnerable to XSS. An injected script only has to call localStorage.getItem("token"), then the token goes to the attacker's server and is used to log in from the attacker's own computer.

Meaning: sessionStorage is just as open to an XSS script as localStorage, it only disappears sooner.

⚡ An HttpOnly cookie

Write:

Set-Cookie: token=eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOjQyfQ.c2lnbmF0dXJl; Max-Age=7200; Path=/; HttpOnly; Secure; SameSite=Lax

Meaning: The server sets this cookie through the Set-Cookie response header. HttpOnly is the only flag (an extra setting on a cookie) that hides a cookie from JavaScript. Secure (the cookie is only sent over HTTPS) and SameSite (a rule for requests from other sites) don't hide it. An HttpOnly cookie can only be created by the server.

⚡ Limit the damage, prevent the XSS

Meaning: HttpOnly stops the token from being stolen, not from being used. While the page with the XSS is still open, the injected script can still send requests, and the browser still attaches the cookie. So the real cure is still escaping and CSP, which prevent XSS. Keep preferences in localStorage, drafts in sessionStorage, and sensitive data out of the browser.

What you will learn