Lesson 90 of 296
Cookies vs localStorage vs sessionStorage
What you will learn
- The ways a browser can store data
- How each one works and its limits
- Cookie attributes and what they protect
- Security: where to store login tokens
- IndexedDB for larger data
On this page
The options
| Cookies | localStorage | sessionStorage | IndexedDB | |
|---|---|---|---|---|
| Size limit (approx.) | About 4 KB per cookie | About 5 MB per origin (varies by browser) | About 5 MB per origin | Much larger, based on disk space |
| Lasts until | The expiry date, or the browser session ends | Deleted by code or the user | The tab is closed | Deleted by code or the user |
| Shared between tabs | Yes | Yes (same origin) | No, one tab only | Yes |
| Sent to the server automatically | Yes, with every matching request | No | No | No |
| Readable by JavaScript | Yes, unless HttpOnly | Yes | Yes | Yes |
| API | document.cookie (awkward), or set by the server | Simple, synchronous | Simple, synchronous | Asynchronous, more complex |
| Data type | Strings | Strings | Strings | Structured data, files |
localStorage
localStorage.setItem("theme", "dark");
localStorage.getItem("theme"); "dark"
localStorage.getItem("missing"); null
localStorage.removeItem("theme");
localStorage.clear();It only stores strings. Store objects as JSON:
const prefs = { theme: "dark", fontSize: 16 };
localStorage.setItem("prefs", JSON.stringify(prefs));
const saved = JSON.parse(localStorage.getItem("prefs") ?? "{}");Without JSON.stringify, an object is saved as the useless string "[object Object]".
Wrap it in try...catch: it can throw when storage is full, disabled, or in some private browsing modes, and JSON.parse throws on corrupted data.
function loadPrefs() {
try {
return JSON.parse(localStorage.getItem("prefs")) ?? {};
} catch {
return {};
}
}It is synchronous: it blocks the main thread while reading and writing. Keep the data small.
Good uses: theme, language, dismissed banners, unsaved drafts, small UI preferences.
sessionStorage
Same methods as localStorage, but the data belongs to one tab and is deleted when that tab closes. Each new tab starts empty.
Good uses: a multi-step form in progress, a scroll position to restore within that tab.
The storage event
When localStorage changes in another tab of the same site, the other tabs receive a storage event. Use it to keep tabs in sync, for example logging out everywhere:
window.addEventListener("storage", (e) => {
if (e.key === "loggedOut") showLoginScreen();
});Cookies
A cookie is a small piece of data the browser stores and sends back to the server with every request to that domain. Cookies are mainly for the server: sessions, login state, tracking.
A server sets a cookie with a response header:
Set-Cookie: sessionId=abc123; Max-Age=86400; Path=/; Secure; HttpOnly; SameSite=LaxCookie attributes
| Attribute | Meaning |
|---|---|
Expires / Max-Age | When it expires. Without them, it is a session cookie, removed when the browser closes. |
Domain / Path | Which URLs it is sent to |
Secure | Only sent over HTTPS |
HttpOnly | JavaScript cannot read it (document.cookie will not show it). Protects against XSS stealing it. |
SameSite=Strict | Never sent with requests that come from other sites |
SameSite=Lax | Sent when the user navigates to your site from a link, but not with most cross-site requests. The default in modern browsers. |
SameSite=None | Sent with cross-site requests; must also be Secure |
SameSite helps protect against CSRF (Cross-Site Request Forgery), where another site tricks the user's browser into sending a request to your site (Part 20).
Cookies from JavaScript
document.cookie = "banner=hidden; Max-Age=2592000; Path=/; SameSite=Lax";
document.cookie; "banner=hidden; other=value"The API is awkward: setting adds or updates one cookie; reading returns all cookies (except HttpOnly ones) as one string. Most code uses a small library or lets the server manage cookies.
Every cookie costs bandwidth
Cookies are sent with every request to their domain, including images and scripts. Large or many cookies slow down every request. Do not store data in cookies that the server does not need.
Where to store login tokens: the security question
This is one of the most common front end security questions.
| Place | Risk |
|---|---|
| localStorage / sessionStorage | Any JavaScript on the page can read it. If an attacker achieves XSS (Lesson 87), they can steal the token and use it anywhere. |
| HttpOnly, Secure, SameSite cookie | JavaScript cannot read it, so XSS cannot steal it directly. Needs CSRF protection, which SameSite and CSRF tokens provide. |
| Memory (a JavaScript variable) | Lost on page refresh; often combined with a refresh token in an HttpOnly cookie |
The usual recommendation: keep session identifiers and refresh tokens in HttpOnly, Secure, SameSite cookies, and never put long-lived secrets in localStorage. Part 15 covers sessions, JWTs and refresh tokens in detail.
Even with HttpOnly cookies, XSS is still dangerous: the attacker's script can make requests as the user while the page is open. Preventing XSS is always the first defence.
IndexedDB
IndexedDB is a real database inside the browser: asynchronous, large capacity, stores objects, files and indexes. Used for offline apps, caching large data and storing files. Its API is complicated, so most people use a small wrapper library (such as idb).
The Cache Storage API (used with Service Workers) stores whole HTTP responses for offline support.
Privacy and the law
In the UK and EU, cookies and similar storage that are not strictly necessary (analytics, advertising) need the user's consent (UK PECR and GDPR rules). Cookies needed for the site to work, like login sessions and shopping baskets, do not need consent. This affects how you build cookie banners.
Common mistakes
- Storing objects in localStorage without JSON.
- Storing access tokens or other secrets in localStorage.
- Not handling
nullfromgetItem, or invalid JSON. - Large cookies sent with every request.
- Forgetting
SecureandHttpOnlyon session cookies. - Expecting sessionStorage to be shared between tabs.
How to say it in an interview
"Cookies are small, sent automatically with every request to their domain, and can be HttpOnly so JavaScript cannot read them, plus Secure and SameSite for HTTPS-only and CSRF protection. localStorage holds about 5 megabytes of strings per origin, persists until cleared and is shared across tabs; sessionStorage is the same but per tab and cleared when the tab closes. Both are synchronous and readable by any script, so an XSS attack can steal anything there. I keep session and refresh tokens in HttpOnly Secure SameSite cookies, use localStorage only for non-sensitive preferences, and IndexedDB for large or offline data."
Key words
| Word | Meaning |
|---|---|
| Cookie | Small data sent to the server with every request |
| localStorage | Persistent key-value storage in the browser |
| sessionStorage | Key-value storage for one tab |
| IndexedDB | An asynchronous database in the browser |
| HttpOnly | A cookie flag that hides it from JavaScript |
| Secure | A cookie flag: HTTPS only |
| SameSite | A cookie setting that controls cross-site sending |
| CSRF | Tricking a browser into sending an unwanted request to another site |
| Origin | Protocol + domain + port |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.