Frontend System Design · Lesson 12 of 86 · 4 min
Browser Storage: Cookies, Web Storage, IndexedDB
This is a classic system design question. Your answer reveals if you know the trade-offs between size, persistence, performance, and security.
When an interviewer asks "How would you store X on the client?", they're not looking for a definition of localStorage. They are testing your ability to choose the right tool by weighing the trade-offs. Your goal is to justify your choice based on four factors: how much data, how long it needs to live, who needs it (client or server), and how it needs to be accessed.
How to Choose the Right Storage
Start your answer by asking clarifying questions based on this decision tree. "Does the server need this data on every request?" is a great first question. It immediately splits the problem in half.
Cookies: For Server Communication
Cookies are the only option that works automatically with the server. The browser attaches them to every HTTP request to the same domain.
This is both their primary feature and their biggest flaw. It's great for managing server-side sessions, because the server gets the session ID with zero client-side code. It's bad for performance if you store anything large, as it adds overhead to every single request, including requests for images and CSS.
The size limit is tiny, around 4KB. They are for small identifiers, not data.
Interview angle: Storing auth tokens. This is the core debate.
HttpOnlycookies are inaccessible to JavaScript, which protects them from Cross-Site Scripting (XSS) attacks. This makes them a common choice for auth tokens. However, they are vulnerable to Cross-Site Request Forgery (CSRF) unless you useSameSiteattributes and anti-CSRF tokens. Storing tokens inlocalStorageis immune to CSRF but vulnerable to XSS. You must be able to explain this trade-off.
Web Storage: Simple Key-Value Pairs
Web Storage (localStorage and sessionStorage) provides a simple, synchronous key-value API. It's a massive improvement over the clunky document.cookie API for client-only data. Both have a generous size limit, typically 5-10MB per origin.
localStorage persists data until it's explicitly cleared. It's scoped to the origin (protocol, host, and port). Data saved on example.com is not available on sub.example.com.
sessionStorage is identical to localStorage in every way but one: its data is cleared when the page session ends (i.e., the tab is closed). Data is not shared between tabs, even if they are for the same origin.
The trap: Web Storage only stores strings. If you try to store an object, you'll get the unhelpful string "[object Object]". Always use JSON.stringify() when writing and JSON.parse() when reading complex data.
const userPreferences = {
theme: 'dark',
notifications: { enabled: true, sound: 'default' }
};
// Storing the object
localStorage.setItem('userPrefs', JSON.stringify(userPreferences));
// Retrieving and parsing the object
const savedPrefsString = localStorage.getItem('userPrefs');
const savedPrefs = savedPrefsString ? JSON.parse(savedPrefsString) : {};
console.log(savedPrefs.theme); // 'dark'
The security risk: Data in Web Storage is accessible to any JavaScript running on the page. This makes it a prime target for XSS attacks. Never store sensitive information like session tokens, personal details, or financial data here. It's for non-sensitive application state and user preferences.
IndexedDB: The Client-Side Database
When you need to store large amounts of structured data, need to query it, or need offline support, IndexedDB is the only serious option. It is a transactional, asynchronous, non-relational database in the browser.
Key features:
- Large storage: The limit is often based on a percentage of available disk space, easily reaching hundreds of megabytes or more.
- Asynchronous API: All operations are non-blocking, so it won't freeze your UI. This also makes the API complex, relying on events and requests.
- Transactional: Operations are grouped into transactions, ensuring data integrity.
- Indexes: You can create indexes on object properties to enable fast searching and querying.
- Stores anything: It can store complex JavaScript objects, files, and blobs directly without serialization.
The trap: The native IndexedDB API is verbose and event-driven, which is why most developers use a lightweight wrapper library like idb by Jake Archibald. These libraries wrap the API in Promises, making it usable with async/await. You should mention this in an interview to show practical experience.
This example shows how to open a database, define a schema, and add/retrieve data. Notice the onupgradeneeded event; this is the only place you can alter the database schema (create object stores and indexes).
// A lightweight wrapper around IndexedDB using async/await
const DB_NAME = 'MyWebAppDB';
const STORE_NAME = 'users';
const DB_VERSION = 1;
async function openDatabase() {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onerror = () => reject(request.error);
request.onsuccess = () => resolve(request.result);
// This event runs only when the DB is created or version is upgraded.
// It's the only place to define the database schema.
request.onupgradeneeded = (event) => {
const db = (event.target).result;
if (!db.objectStoreNames.contains(STORE_NAME)) {
const store = db.createObjectStore(STORE_NAME, { keyPath: 'id', autoIncrement: true });
store.createIndex('email', 'email', { unique: true });
}
};
});
}
async function addUser(user) {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readwrite');
const store = transaction.objectStore(STORE_NAME);
await store.add(user);
return transaction.done; // Promise that resolves when transaction completes
}
async function getUserByEmail(email) {
const db = await openDatabase();
const transaction = db.transaction(STORE_NAME, 'readonly');
const store = transaction.objectStore(STORE_NAME);
const index = store.index('email');
return index.get(email);
}
// Example usage
(async () => {
try {
await addUser({ name: 'Alice', email: 'alice@example.com' });
const user = await getUserByEmail('alice@example.com');
console.log('Found user:', user);
} catch (error) {
console.error('IndexedDB operation failed:', error);
}
})();
Try it
Design a "save for later" feature for an e-commerce product page for a logged-out user. Write down which storage mechanism you'd use and a one-paragraph justification covering persistence requirements, data complexity, and potential security concerns.
Next: We'll cover the hard numbers and security risks in Client-Side Storage: Limits and Security Risks.
Lock it in — apply this lesson under interview conditions.