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
61

Frontend System Design · Lesson 61 of 86 · 4 min

Storing Auth Tokens: Cookies vs localStorage

This question is a filter. Your answer reveals whether you've shipped a secure app or just followed tutorials. Get it right, and you prove you understand web security fundamentals.

The Standard: Secure, HttpOnly Cookies

For storing authentication tokens, the correct answer is almost always a secure, HttpOnly cookie. This isn't just a best practice; it's a direct defense against the most common class of web vulnerability.

An HttpOnly cookie is inaccessible to JavaScript running in the browser. This is its entire purpose. If an attacker achieves Cross-Site Scripting (XSS) on your site, their malicious script cannot read the token from document.cookie. This single attribute prevents the most straightforward session hijacking attack.

The browser handles everything for you. Once set by the server, the browser automatically attaches the cookie to every subsequent request to the same origin. You don't write any code to manage it.

For a cookie to be secure, it needs three key attributes set by the server:

  • HttpOnly: Prevents JavaScript access. Non-negotiable for auth tokens.
  • Secure: Ensures the cookie is only sent over HTTPS. Always use this in production.
  • SameSite=Lax or SameSite=Strict: A critical defense against Cross-Site Request Forgery (CSRF). Lax is a sensible default for most web apps.

Why localStorage is a Footgun for Auth

Using localStorage for auth tokens is a common pattern in tutorials and bootcamps. It is also dangerously insecure.

Any data in localStorage is accessible via JavaScript. This means any XSS vulnerability on your page, including one injected through a third-party library, gives an attacker immediate access to the user's auth token. They can copy the token and use it to impersonate your user.

The trap: In an interview, never defend localStorage for auth tokens. Acknowledge its existence and risks, then pivot to the correct cookie-based solution. Arguing for localStorage signals a lack of production security experience.

The diagram below shows exactly why. A script can read from localStorage, but the browser blocks it from reading an HttpOnly cookie.

The Implementation is Simpler Than You Think

A common misconception is that cookies are harder to work with in a Single Page Application (SPA). The opposite is true. With a secure cookie, the frontend auth code becomes trivial.

The server is responsible for setting the cookie on login.

// server.js (Node.js with Express)
// After validating credentials...

const sessionToken = 'your_generated_jwt_or_session_id';

res.cookie('session_token', sessionToken, {
  httpOnly: true,
  secure: process.env.NODE_ENV === 'production',
  sameSite: 'Lax', // Or 'Strict'
  maxAge: 24 * 60 * 60 * 1000, // 24 hours
  path: '/',
});

res.status(200).json({ message: 'Login successful' });

The frontend only needs to include one option in its fetch calls to ensure the browser sends the cookie. That's it. You don't need to read, store, or attach the token manually.

// frontend.js (React/Vue/etc.)

async function fetchUserProfile() {
  try {
    const response = await fetch('/api/profile', {
      // This tells the browser to send cookies with the request.
      credentials: 'include',
    });

    if (response.ok) {
      const user = await response.json();
      console.log('User profile:', user);
    } else {
      // Handle 401 Unauthorized, etc.
      console.error('Failed to fetch profile:', response.statusText);
    }
  } catch (error) {
    console.error('Network error:', error);
  }
}

There is no token management in your global state, no interceptors to add authorization headers, and no risk of a script stealing the token from memory or localStorage.

What About JWTs?

This is a common point of confusion. A JSON Web Token (JWT) is a token format. It is not a storage mechanism.

You can store a JWT in localStorage, which is insecure. You can store a JWT in an HttpOnly cookie, which is secure.

The debate is not "JWTs vs. Cookies." The debate is "Where do you store the token?" The answer is in an HttpOnly cookie. Whether that token is a JWT or an opaque string is a separate architectural decision.

Handling CSRF with SameSite Cookies

While HttpOnly protects against XSS, the SameSite attribute is your primary defense against Cross-Site Request Forgery (CSRF).

A CSRF attack tricks a logged-in user's browser into making a malicious request to your site from another site. Since browsers used to send cookies automatically with any cross-site request, this could trigger state-changing actions (like changing a password or transferring funds) without the user's consent.

The SameSite attribute stops this:

  • SameSite=Strict: The browser will not send the cookie with any cross-site request, including a regular link click from another site. It's the most secure but can be disruptive to the user experience.
  • SameSite=Lax: The browser sends the cookie on cross-site requests that result from top-level navigation (e.g., clicking a link), but not for requests initiated by scripts, iframes, or forms from another site. This is the modern browser default and provides a great balance of security and usability.

For auth tokens, SameSite=Lax is the recommended setting for most applications.

Try it

Open the developer tools on a site where you are logged in (e.g., GitHub, a banking site). Go to the Application/Storage tab and inspect the cookies for that domain. Find the main session or auth cookie. Check its attributes. Is it HttpOnly? Is it Secure? What is its SameSite policy? Can you articulate why the engineers chose those specific settings?

Next: We'll cover what you need to know about the PWA Manifest and Installability.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Content Security Policy (CSP)

Next

PWA Manifest and Installability