Programming
We provide developers and engineers the guides and tutorials they...
Search
We provide developers and engineers the guides and tutorials they...
Content is king. It's not just about how you're going to write, b...
Looking for an engaging connection with thousands of other people...
Cookies vs localStorage vs sessionStorage vs server sessions: capacity, lifetime, what is sent to the server, XSS and CSRF security, and when to use each.
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.
| Cookies | localStorage | sessionStorage | |
|---|---|---|---|
| Capacity | About 4 KB each | About 5 to 10 MB per origin | About 5 MB per origin |
| Lifetime | Until an expiry date, or the end of the browser session | Until deleted | Until the tab closes |
| Sent with requests | Yes, automatically | No | No |
| Readable by JavaScript | Yes, unless HttpOnly | Yes | Yes |
| Can be set by the server | Yes, with Set-Cookie | No | No |
| Shared between tabs | Yes | Yes, same origin | No; each tab has its own |
| Scope | Domain and path | Origin (scheme + host + port) | Origin and tab |
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
| Attribute | Effect |
|---|---|
Expires / Max-Age | When the cookie is deleted. Without one, it is a session cookie, removed when the browser closes |
Domain | Which hosts receive it. Setting a parent domain includes subdomains |
Path | Which URL paths receive it |
Secure | Sent only over HTTPS |
HttpOnly | Hidden from JavaScript; document.cookie cannot see it |
SameSite | Whether it is sent on requests that come from other sites |
SameSite has three values:
| Value | Sent on cross-site requests? |
|---|---|
Strict | Never |
Lax | Only when the user navigates to the site by a top-level link. The default in modern browsers |
None | Always; 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.
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") ?? "{}");
Strengths: far more space than cookies, a simple API, and no effect on request size.
Weaknesses:
| Storage | Use |
|---|---|
| IndexedDB | A real asynchronous database in the browser: large, structured data, offline apps |
| Cache API | Storing network responses, used by service workers for offline support |
| Origin Private File System | File-like storage for applications that need it |
"Session" is used in two ways.
A server-side session works like this:
HttpOnly cookie.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.
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.
| Storage | XSS can steal it | CSRF applies |
|---|---|---|
| localStorage / sessionStorage | Yes | No |
Cookie without HttpOnly | Yes | Yes |
HttpOnly cookie | No | Yes, but mitigated by SameSite and CSRF tokens |
The general recommendation for web applications is an HttpOnly, Secure, SameSite cookie:
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.
| Data | Where |
|---|---|
| Session ID or authentication token | HttpOnly cookie |
| Shopping basket for a logged-in user, permissions, anything trusted | Server-side session or database |
| Theme, language, layout preferences | localStorage, or a cookie if the server needs it to render the page |
| A form in progress, a wizard's current step | sessionStorage |
| Large offline data | IndexedDB |
| Cached API responses for offline use | Cache API |
| Passwords, card numbers, secrets | Nowhere 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 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.
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.
localStorage persists until cleared and is shared across tabs. sessionStorage is separate for each tab and is erased when the tab closes.
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.
It is readable by any script on the page, so an XSS vulnerability exposes it. An HttpOnly cookie is generally the safer place.
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.