Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Frontend System Design Roadmap
  1. 1.HTTP/1.1 vs HTTP/2 vs HTTP/3 (QUIC)
  2. 2.TCP and TLS Handshakes: Connection Setup Costs
  3. 3.Browser Network Stack and Connection Pooling
  4. 4.GET vs POST and Idempotency in HTTP
  5. 5.The Critical Rendering Path (CRP)
  6. 6.DOM, CSSOM and the Render Tree
  7. 7.Layout, Paint and Compositing
  8. 8.Reflows and Repaints Explained
  9. 9.Event Loop: Call Stack, Task and Microtask Queues
  10. 10.Async JavaScript: Promises and async/await
  11. 11.Web Workers: Multi-threading in the Browser
  12. 12.Browser Storage: Cookies, Web Storage, IndexedDB
  13. 13.Client-Side Storage: Limits and Security Risks
  14. 14.Choosing the Right Client-Side Storage
  15. 15.HTTP Caching: Cache-Control, ETag, Last-Modified
  16. 16.Browser-Level Caching Mechanisms
  17. 17.Cache Invalidation for Frontend Apps
  18. 18.Structuring a Large Single-Page App
  19. 19.Component-Based Architecture Principles
  20. 20.Props, State and Component Lifecycle
  21. 21.Module Bundling Basics
  22. 22.Core Web Vitals: LCP, INP and CLS
  23. 23.FCP and Time to Interactive (TTI) Explained
  24. 24.Measuring Performance: Lighthouse and WebPageTest
  25. 25.Asset Compression and Minification Basics
  26. 26.What Is a CDN and How Does It Work?
  27. 27.CDN Benefits: Latency, Availability, Offload
  28. 28.CDN Cache Behavior and Invalidation
  29. 29.Global State vs Local Component State
  30. 30.State Patterns: Redux, Zustand and Context
  31. 31.Data Fetching: React Query and SWR
  32. 32.Immutable Data in Frontend State
  33. 33.SSR vs CSR: Rendering Trade-offs
  34. 34.Hydration and Time to First Byte (TTFB)
  35. 35.Static Site Generation (SSG) for Speed and SEO
  36. 36.Incremental Static Regeneration (ISR)
  37. 37.Micro-Frontends: Core Principles
  38. 38.Micro-Frontend Integration Strategies
  39. 39.Communication Between Micro-Frontends
  40. 40.Micro-Frontends: Pros and Cons for Large Teams
  41. 41.Real-Time: Polling, SSE and WebSockets
  42. 42.Real-Time Use Cases: Chat, Alerts, Live Data
  43. 43.Designing a Real-Time Data Flow
  44. 44.Scaling WebSocket Connections
  45. 45.Responsive Images: srcset, sizes and picture
  46. 46.Modern Image Formats: WebP, AVIF, JPEG XL
  47. 47.Lazy Loading Images and Videos
  48. 48.Video Streaming: HLS, DASH, Adaptive Bitrate
  49. 49.REST and GraphQL for Frontend Engineers
  50. 50.Batching, Throttling and Debouncing API Calls
  51. 51.Handling API Errors in the Frontend
  52. 52.Authentication Flows: OAuth and JWT
  53. 53.Global Error Boundaries in React
  54. 54.Error Reporting: Sentry and LogRocket
  55. 55.Graceful Degradation and Fallback UIs
  56. 56.Real User Monitoring (RUM)
  57. 57.CORS: Cross-Origin Resource Sharing
  58. 58.Preventing XSS (Cross-Site Scripting)
  59. 59.CSRF Protection for Frontend Apps
  60. 60.Content Security Policy (CSP)
  61. 61.Storing Auth Tokens: Cookies vs localStorage
  62. 62.PWA Manifest and Installability
  63. 63.Service Workers: Lifecycle and Caching Strategies
  64. 64.Offline Support and Background Sync
  65. 65.Push Notifications for Web Apps
  66. 66.Webpack vs Vite vs Parcel
  67. 67.Code Splitting, Tree Shaking, Asset Optimization
  68. 68.Module Resolution and Hot Module Replacement
  69. 69.Monorepo Tooling: Nx and Lerna
  70. 70.Atomic Design for Component Libraries
  71. 71.Theming and Customization in Design Systems
  72. 72.Accessibility in Component Libraries
  73. 73.Component Library Docs, Testing and Versioning
  74. 74.Publishing and Consuming a Component Library
  75. 75.Full-Text Search: Levenshtein and Fuzzy Matching
  76. 76.Indexing Large Datasets in the Browser
  77. 77.Search Performance: Debouncing and Web Workers
  78. 78.Integrating Backend Search Services
  79. 79.Choosing a Chart Library: D3, Chart.js, Recharts
  80. 80.Rendering Large Datasets: Canvas vs SVG
  81. 81.Interactive, Responsive Data Visualizations
  82. 82.Data Fetching and Aggregation for Dashboards
  83. 83.A/B Test Design and Rollout Strategies
  84. 84.Client-Side vs Server-Side A/B Testing
  85. 85.Feature Flags and Remote Configuration
  86. 86.Experiment Data Collection and Analytics
Frontend System Design Roadmap
12

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. HttpOnly cookies 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 use SameSite attributes and anti-CSRF tokens. Storing tokens in localStorage is 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.

Try a free mock interviewPractice system design problems
Previous

Web Workers: Multi-threading in the Browser

Next

Client-Side Storage: Limits and Security Risks