Track 07 · Lesson 2 of 18Identity and login

Track 07 · Identity and login

Browser storage compared

Lesson 2 of 18· 7 min

You can keep data in a JavaScript variable, sessionStorage, localStorage, IndexedDB or a cookie. They differ in how long data lasts, which tabs see it, who can read it, and whether it travels to the server. These differences decide where a login can safely live.

Five places, six events

Save a value, then make things happen

Then make something happen

RowJS variablelet cart = 3sessionStoragesessionStorage.setItem("cart", "3")localStoragelocalStorage.setItem("cart", "3")IndexedDBstore.put({ id: "cart", items: 3 })Cookie (HttpOnly)Set-Cookie: cart=3; Max-Age=2592000; HttpOnly
Right nowEmpty

Nothing saved yet.

Empty

Nothing saved yet.

Empty

Nothing saved yet.

Empty

Nothing saved yet.

Empty

Nothing saved yet.

SpaceMemory you haveAbout 5 MBAbout 5 MBLarge: a share of free diskAbout 4 KB per cookie
Lasts untilReloadThe tab closesClearedClearedIts expiry, or the browser closes
Shared withThis page onlyThis tab onlyAll tabs, same originAll tabs, same originAll tabs, its domain
Sent to the serverNoNoNoNoYes, automatically
How you use itVariablesSync, strings onlySync, strings onlyAsync, objects and filesSet-Cookie or document.cookie
Save a value first, then pick an event.

Try the real APIs on this page

// Pick an action

Reload and read again: both survive, because a reload keeps the same tab. Close the tab and come back, and only localStorage remains. This site keeps your lesson progress in localStorage too.

How long it lasts#

A reload wipes memory, and only memory. sessionStorage survives reloads but belongs to one tab. localStorage and IndexedDB stay until cleared, though Safari may delete them after seven days without a visit. Cookies last until their Max-Age or Expires, or until the browser closes if they have neither.

Who can read it#

Every kind of storage JavaScript can read, an injected script can read too. That’s the line that matters for auth: an HttpOnly cookie is the only option a script can’t read at all. Other websites can never read your storage, thanks to the same-origin policy, but your cookies can still ride along on their requests to you, depending on SameSite.

What travels to the server#

Only cookies are sent automatically, with every request to their domain, even images. That’s convenient for sessions, and it’s exactly what cross-site request forgery exploits. Everything else is sent only when your code adds it.

Check yourself

Which kind of browser storage can an injected script NOT read?