Search

How Cookies, LocalStorage, and Sessions Differ

The short answer

Quick answer: Cookies are small pieces of data the browser stores and sends automatically to the server with every request to that site. localStorage and sessionStorage are key-value stores that only JavaScript in the browser can read; they are never sent anywhere automatically. localStorage lasts until cleared, and sessionStorage lasts until the tab closes. A session is different in kind: it is data kept on the server about a logged-in user, found using an ID that is usually stored in a cookie. Use cookies for authentication, web storage for non-sensitive interface preferences, and server sessions for anything the server must trust.

Side by side

CookieslocalStoragesessionStorage
CapacityAbout 4 KB eachAbout 5 to 10 MB per originAbout 5 MB per origin
LifetimeUntil an expiry date, or the end of the browser sessionUntil deletedUntil the tab closes
Sent with requestsYes, automaticallyNoNo
Readable by JavaScriptYes, unless HttpOnlyYesYes
Can be set by the serverYes, with Set-CookieNoNo
Shared between tabsYesYes, same originNo; each tab has its own
ScopeDomain and pathOrigin (scheme + host + port)Origin and tab

Cookies

Cookies were invented in the 1990s to give the stateless HTTP protocol a memory. They are specified in RFC 6265 and explained in MDN's guide to HTTP cookies.

The server sets one in a response:

Set-Cookie: sid=a3f9c1e7; Path=/; Max-Age=86400; Secure; HttpOnly; SameSite=Lax

The browser then returns it on every matching request:

Cookie: sid=a3f9c1e7

The attributes that matter

AttributeEffect
Expires / Max-AgeWhen the cookie is deleted. Without one, it is a session cookie, removed when the browser closes
DomainWhich hosts receive it. Setting a parent domain includes subdomains
PathWhich URL paths receive it
SecureSent only over HTTPS
HttpOnlyHidden from JavaScript; document.cookie cannot see it
SameSiteWhether it is sent on requests that come from other sites

SameSite has three values:

ValueSent on cross-site requests?
StrictNever
LaxOnly when the user navigates to the site by a top-level link. The default in modern browsers
NoneAlways; requires Secure

Strengths: the server can set and read them, they travel automatically, and HttpOnly keeps them away from scripts.

Weaknesses: small, added to every request (including images and other assets on the same domain), and their automatic sending creates the risk of forged requests.

A note on third-party cookies, those set by a domain other than the one in the address bar: browsers have been restricting or partitioning them for privacy reasons, so do not design anything new that depends on them.

localStorage and sessionStorage

The Web Storage API is a simple key-value store.

localStorage.setItem("theme", "dark");
const theme = localStorage.getItem("theme");
localStorage.removeItem("theme");

// Values are strings, so objects need converting
localStorage.setItem("prefs", JSON.stringify({ fontSize: 16 }));
const prefs = JSON.parse(localStorage.getItem("prefs") ?? "{}");
  • localStorage persists across restarts and is shared by all tabs of the same origin.
  • sessionStorage is separate for each tab and is cleared when the tab closes.

Strengths: far more space than cookies, a simple API, and no effect on request size.

Weaknesses:

  • Strings only.
  • Synchronous. Reads and writes block the main thread, so it is unsuitable for large data.
  • Any script on the page can read it. That includes third-party scripts and any injected through cross-site scripting.
  • The server cannot see it. JavaScript must send it explicitly.
  • Not available in web workers.
  • Can be cleared by the browser under storage pressure, or by the user.

For larger data

StorageUse
IndexedDBA real asynchronous database in the browser: large, structured data, offline apps
Cache APIStoring network responses, used by service workers for offline support
Origin Private File SystemFile-like storage for applications that need it

Sessions

"Session" is used in two ways.

  • A session cookie is simply a cookie with no expiry date.
  • A server-side session is a record on the server, in memory, a database or Redis, holding data about a logged-in user.

A server-side session works like this:

  1. You log in. The server creates a session record and a long random session ID.
  2. It sends the ID in an HttpOnly cookie.
  3. Each request carries the cookie. The server looks up the ID to find out who you are.
  4. Logging out deletes the record.

The browser holds only a meaningless ID. The real data stays on the server, where the user cannot read or alter it, and the server can end the session at any time. See JWT vs sessions for the comparison with token-based authentication.

The security question: where should a login token go?

There are two attacks to weigh.

XSS (cross-site scripting). An attacker's script runs on your page. It can read anything JavaScript can read: all of localStorage, all of sessionStorage, and any cookie that is not HttpOnly.

CSRF (cross-site request forgery). Another site causes the user's browser to send a request to your site. Because cookies are sent automatically, the request arrives authenticated.

StorageXSS can steal itCSRF applies
localStorage / sessionStorageYesNo
Cookie without HttpOnlyYesYes
HttpOnly cookieNoYes, but mitigated by SameSite and CSRF tokens

The general recommendation for web applications is an HttpOnly, Secure, SameSite cookie:

  • Scripts cannot read it, so an XSS flaw cannot copy the token out.
  • SameSite=Lax or Strict blocks most forged cross-site requests, and an anti-CSRF token covers the rest for state-changing actions.
  • Secure keeps it off unencrypted connections. See how HTTPS works.

A caveat: HttpOnly does not make XSS harmless. A script running in the page can still make requests as the user while the page is open. It prevents the token being taken away and used elsewhere, which is a meaningful reduction, not a cure.

Storing tokens in localStorage is common in single-page applications and is not automatically wrong, but it means any XSS flaw exposes the token directly. If you do it, keep tokens short-lived and invest heavily in XSS prevention.

What to store where

DataWhere
Session ID or authentication tokenHttpOnly cookie
Shopping basket for a logged-in user, permissions, anything trustedServer-side session or database
Theme, language, layout preferenceslocalStorage, or a cookie if the server needs it to render the page
A form in progress, a wizard's current stepsessionStorage
Large offline dataIndexedDB
Cached API responses for offline useCache API
Passwords, card numbers, secretsNowhere in the browser

Cross-origin API calls add another consideration: cookies are only sent if both the request and the server's CORS headers allow credentials. See how CORS works.

Privacy and consent

Privacy laws such as the GDPR and the ePrivacy rules in Europe generally require consent before storing or reading information on a user's device that is not strictly necessary for the service they asked for. Despite the name "cookie banner", these rules apply to any client-side storage, including localStorage. Cookies needed for login or a shopping basket are typically exempt; analytics and advertising identifiers typically are not. Check the rules that apply to you.

Frequently asked questions

What is the difference between cookies and localStorage?

Cookies are sent to the server automatically with every request and can be hidden from JavaScript. localStorage is larger, stays in the browser, and is always readable by scripts on the page.

What is the difference between localStorage and sessionStorage?

localStorage persists until cleared and is shared across tabs. sessionStorage is separate for each tab and is erased when the tab closes.

What is the difference between a cookie and a session?

A cookie is data stored in the browser. A session is data stored on the server, usually located by an ID kept in a cookie.

Is it safe to store a JWT in localStorage?

It is readable by any script on the page, so an XSS vulnerability exposes it. An HttpOnly cookie is generally the safer place.

Conclusion

The three browser stores differ on one key question: who can read the data, and does it travel to the server? Cookies travel and can be hidden from scripts, which makes them right for authentication. Web storage stays local and is visible to scripts, which makes it right for harmless preferences. And anything the server must rely on should live on the server, with the browser holding only a reference to it.

Related articles

Sources and further reading

Usama Muneer

Usama Muneer

Coder, Blogger, Tech Speaker & Web Technologies Enthusiast. Passionate about working on open-source Programming languages & Tools while utilizing my Product Development skills.

Your experience on this site will be improved by allowing cookies Cookie Policy