Frontend System Design · Lesson 14 of 86 · 4 min
Choosing the Right Client-Side Storage
This is a classic frontend interview question that tests your understanding of trade-offs in performance, security, and state management.
After this, you will know exactly which storage to pick for any given scenario and be able to justify your choice. The decision comes down to four factors: persistence, scope, size, and whether the server needs the data.
The Four APIs and Their Trade-offs
You have four tools in the browser for storage. Don't just list them in an interview; frame them by their primary use case.
Cookies are for data the server needs. They are automatically sent with every HTTP request to your domain, which is their main feature and their main performance cost. The size limit is tiny, around 4KB.
Use cookies for session identifiers. A server-set, HttpOnly, Secure, and SameSite=Strict cookie is the standard way to handle authentication tokens.
LocalStorage is for persistent client-only data. It's a simple key-value store (strings only) that persists until cleared by you or the user. The limit is much larger, typically 5-10MB.
Use localStorage for user preferences like theme (dark/light mode) or remembering a user's name.
The trap: Never store sensitive information like session tokens or JWTs in
localStorage. It's accessible via JavaScript, making it vulnerable to Cross-Site Scripting (XSS) attacks. If an attacker injects a script onto your page, they can read everything inlocalStorageand impersonate your user.
SessionStorage is localStorage with a shorter lifespan. It's a key-value store that is cleared when the browser tab is closed. The data is isolated to that specific tab.
Use sessionStorage for temporary data related to a single user task, like persisting form data across refreshes in a multi-step checkout flow.
IndexedDB is a client-side database. It's for large amounts of structured data you need to query, like you would with a NoSQL database. It's asynchronous, transactional, and can store complex objects, files, and blobs. The size limits are generous and often configurable by the user.
Use IndexedDB for building offline-first applications (Progressive Web Apps) or for caching large, complex datasets on the client, like messages in a chat app or documents in an editor.
A Decision Flowchart
When you're asked to choose, walk the interviewer through your logic. This flowchart models that thought process.
How to Store Auth Tokens
This is the most common follow-up question, and getting it right is critical.
The short answer: Use a secure, HttpOnly cookie.
An HttpOnly cookie is inaccessible to JavaScript running on the page. This is your primary defense against a stolen token via an XSS attack. If your authentication token is in localStorage, any injected script can grab it and send it to an attacker's server.
localStorage.setItem('jwt', token); // Don't do this.
The counter-argument is that cookies are vulnerable to Cross-Site Request Forgery (CSRF). This is true, but CSRF can be mitigated effectively by using the SameSite cookie attribute (Strict or Lax) and anti-CSRF tokens. The risk of token theft from XSS is generally considered more severe and harder to prevent than CSRF.
Don't Block the Main Thread
Performance is another key trade-off. localStorage and sessionStorage have synchronous APIs.
// This call blocks rendering until the data is read from disk.
const theme = localStorage.getItem('userTheme');
For small, infrequent reads and writes, this is fine. But if you read or write large amounts of data, you can block the main thread and cause your UI to freeze. Iterating and calling setItem in a loop is a common way to introduce jank.
IndexedDB has an asynchronous API. It uses events (or Promises with a wrapper library) so you can perform database operations without blocking the UI. This makes it the only viable choice for storing and querying large datasets on the client.
Code: Persisting a User Preference
This is the canonical example for localStorage: a dark mode toggle. It's simple, non-sensitive data that should persist across sessions.
const THEME_KEY = 'userTheme';
const LIGHT_THEME = 'light-theme';
const DARK_THEME = 'dark-theme';
function applyTheme(theme) {
document.body.className = theme;
}
function toggleTheme() {
const currentTheme = localStorage.getItem(THEME_KEY) || LIGHT_THEME;
const newTheme = currentTheme === DARK_THEME ? LIGHT_THEME : DARK_THEME;
localStorage.setItem(THEME_KEY, newTheme);
applyTheme(newTheme);
}
// Apply the saved theme on initial load
const savedTheme = localStorage.getItem(THEME_KEY);
if (savedTheme) {
applyTheme(savedTheme);
}
// Example: hook up to a button
// const themeToggleButton = document.getElementById('theme-toggle');
// themeToggleButton.addEventListener('click', toggleTheme);
In an interview, you can quickly write this to demonstrate you know the API and its most appropriate use case.
Try it
Take a simple multi-step form and use sessionStorage to save the input from each step. The data should persist if the user refreshes the page, but be gone if they close and reopen the tab. Be ready to explain why sessionStorage is a better choice here than localStorage.
Next: We'll move from client storage to network-level improvements in HTTP Caching: Cache-Control, ETag, Last-Modified.
Lock it in — apply this lesson under interview conditions.