Learn the key differences between localStorage, sessionStorage, and cookies — a common front-end interview topic. This guide explains practical use cases, storage limits, and security considerations, along with insights into CSRF protection, SameSite attributes, and Content Security Policy (CSP).
Written by: Chia1104 CC BY-NC-SA 4.0
This year, I spent quite a bit of time in interviews, and one of the most frequently asked questions was:
“Can you explain the difference between localStorage, sessionStorage, and cookies?”
Here’s a quick rundown of how I usually answer it—and I’ll also share a rather peculiar interview experience related to it.
localStorage can be thought of as a “long-term locker that sticks with a domain.”
As long as the user or code doesn’t explicitly clear it, the stored data will persist—even after closing or restarting the browser. These values exist entirely on the client side and aren’t sent with every HTTP request. This makes localStorage great for storing data that is not server-dependent but should persist, such as theme preference (dark/light mode), sidebar state, or list sorting options.
In terms of capacity, localStorage usually offers several megabytes of space—far more generous than cookies, which are limited to just a few kilobytes. It has a simple key-value API, such as localStorage.setItem('theme', 'dark').
However, since the data is fully controlled by the front end and doesn’t automatically expire, it’s not suitable for sensitive information like raw access tokens. It can also become a “forgotten closet” full of old data if you don’t manage it properly.
If localStorage is a “long-term locker,” then sessionStorage is more like “a temporary desk for the current tab.”
It also stores key-value data on the browser side and isn’t automatically sent to the server. The key difference lies in its lifecycle: once you close the tab or window, its data disappears. In some browsers, even opening a new tab won’t share the same sessionStorage.
This makes it ideal for short-term, session-bound states, such as multi-step form progress, temporary search filters, or UI states.
The benefit is that you don’t have to worry about cleaning it up—it vanishes automatically when the tab closes. The drawback, of course, is that if the user accidentally closes the tab, there’s no way to recover that data.
Cookies are more like “little notes that get sent with every HTTP request.”
If the domain, path, and security conditions match, the browser automatically attaches the associated cookies to outgoing requests. That’s why cookies have long been the primary tool for things like login sessions, tracking IDs, and A/B testing flags—since the server can recognize the user without extra logic.
Cookies typically hold only a few kilobytes of data, and because they’re sent with every request, overusing them wastes bandwidth and slows things down.
They can have expiration times defined with Expires or Max-Age. If not set, the cookie usually expires once the browser is closed (a “session cookie”).
Modern browsers also support flags like HttpOnly, Secure, and SameSite for enhanced security and stricter cross-site behavior.
When asked this in an interview, I like to summarize along several key axes:
Now for that interview story I mentioned earlier (no company names, just for fun).
During one interview, I answered this exact question and explained the three storage types in detail. When I finished with cookies, the interviewer suddenly asked,
“So can cookies be used to set CSRF?”
At that moment, I misheard it as “CSR” (Client-Side Rendering) while thinking about “CSP” (Content Security Policy)! You can imagine how that interview ended…
Let’s clarify that confusion here.
Strictly speaking, you don’t set CSRF on cookies.
Instead, you use the SameSite attribute of cookies to help defend against CSRF attacks—often alongside a traditional CSRF token mechanism.
CSRF exploits the fact that browsers automatically include cookies in cross-origin requests.
So the server sees a valid session cookie and assumes the request is coming from the legitimate user.
That’s why cookies are part of the problem, but they can also be configured to mitigate it.
By adding a SameSite property to cookies, you can control whether to include them in cross-site requests:
SameSite=Strict: Only same-origin requests send cookies. This blocks most CSRF attempts but can affect UX.SameSite=Lax: Allows cookies for top-level GET navigations but not for things like cross-origin POSTs or image loads—a balanced compromise between security and usability.A more reliable method is to use CSRF tokens embedded in form submissions:
<input type="hidden" name="csrf-token" value="GENERATED_BY_SSR" />The token is generated and tracked by the server.
When the client submits a POST request, it must send the same token. The server verifies it to ensure the request truly originated from the legitimate site.
(And no, CSR has nothing to do with this!)
CSP is a browser-level whitelist-based security mechanism that restricts what external resources a webpage can load or execute. Its main goal is to reduce the risk of XSS (Cross-Site Scripting) and various injection attacks.
The idea behind CSP is: trust nothing by default.
You explicitly allow only specific origins and resource types—for example, JavaScript, CSS, images, fonts, iframes, or AJAX requests.
CSP is typically set via the HTTP response header Content-Security-Policy
(or a <meta> tag). You can also start with Content-Security-Policy-Report-Only,
which runs in report-only mode to gather violations before enforcing strict blocking.
Some widely used directives include:
default-src: Default resource policy, e.g., default-src 'self' allows only same-origin resources.script-src, style-src, img-src: Control allowed sources for JavaScript, CSS, and images (e.g., your domain plus specific CDNs).CSP is particularly effective against XSS. Even if an attacker injects a <script> tag, the browser blocks it because it’s not on the allowlist.
CSP can also restrict outbound data or form submissions (connect-src, form-action), reducing the risk of data leaks or malicious exfiltration.