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
52

Frontend System Design · Lesson 52 of 86 · 5 min

Authentication Flows: OAuth and JWT

This topic tests your understanding of frontend security. You need to explain how a user's identity is managed across requests and with third-party services.

Distinguish Authentication from Authorization

You will be asked this. Get it right.

Authentication (AuthN) is about identity. It's the process of proving you are who you say you are. A username and password form is a classic authentication mechanism. The output is a decision: "Yes, this is User A" or "No, identity not verified."

Authorization (AuthZ) is about permissions. Once authenticated, what are you allowed to do? Can User A read a document? Can they delete it? That's authorization.

In an interview, state the difference clearly. AuthN is the key, AuthZ is which doors the key can open.

The trap: Candidates often use these terms interchangeably. Don't. It signals a lack of precision. Frontend work involves both: you redirect an unauthenticated user to a login page (managing AuthN state), and you hide an "Admin" button from a non-admin user (enforcing AuthZ in the UI). But always state that true authorization happens on the server.

Explain How JWTs Maintain State

A JSON Web Token (JWT) is the standard way to handle authentication in modern frontends. It's a signed, self-contained JSON object encoded as a string.

A JWT has three parts, separated by dots: header.payload.signature.

  1. Header: Metadata, like the signing algorithm (alg).
  2. Payload: The data, or "claims." This includes standard claims like exp (expiration time) and sub (the user's ID), plus any custom data like user roles.
  3. Signature: A hash of the header, payload, and a server-side secret. This is the critical part.

The signature allows the server to verify that the token was issued by a trusted source and that the payload hasn't been tampered with.

Why JWTs matter: They enable stateless authentication. The server doesn't need to store session data in memory or a database. All the information required to identify the user is in the token itself, which the client sends with every request. This scales well, especially in microservice architectures.

The trap: Thinking JWTs are encrypted. They are not. The payload is Base64Url encoded, which is trivially reversible. Anyone who intercepts a JWT can read its contents. Never store sensitive information in a JWT payload. It is for verifiable identity, not for secrecy.

Debate Where to Store Tokens

"You get a JWT from the login endpoint. Where do you store it on the client?" This is a guaranteed question. There is no single perfect answer, only trade-offs.

Option 1: localStorage

  • Pro: Simple to implement. localStorage.setItem('token', ...) and localStorage.getItem('token'). It persists across browser tabs and window closures.
  • Con: Vulnerable to Cross-Site Scripting (XSS). If an attacker can inject JavaScript onto your page (e.g., via a third-party script), they can read the token from localStorage and impersonate the user. This is a significant risk.

Option 2: HTTP-Only Cookie

  • Pro: Secure against XSS. An HttpOnly cookie cannot be accessed by client-side JavaScript. The browser automatically sends it with every request to the correct domain.
  • Con: Vulnerable to Cross-Site Request Forgery (CSRF). If a user is logged into your site and visits a malicious site in another tab, that site can make a request to your server, and the browser will helpfully attach the auth cookie. You must implement CSRF protection (e.g., synchronizer tokens) to mitigate this.

The best answer for an interview: Start by acknowledging both options and their trade-offs. For a Single-Page Application (SPA), a common and secure pattern is a hybrid approach:

  1. Store a short-lived access token (JWT, 15-60 minutes) in memory (e.g., a JavaScript variable). This limits the window for XSS damage.
  2. Store a long-lived refresh token in a secure, HttpOnly cookie. This token's only purpose is to get a new access token.
  3. When the access token expires, your API client (or an interceptor) silently uses the refresh token to fetch a new access token and retries the original request. The user sees nothing.

This approach combines the XSS resistance of HttpOnly cookies for the most valuable token (the refresh token) with the CSRF immunity of in-memory tokens for API requests.

Diagram the OAuth 2.0 Flow

OAuth 2.0 is not authentication. It is a framework for delegated authorization. It lets a user grant a third-party application limited access to their resources without sharing their credentials. "Sign in with Google" is OAuth.

For SPAs, the standard flow is the Authorization Code Flow with PKCE. You need to be able to walk through this. PKCE (Proof Key for Code Exchange) is a security extension that prevents an attacker from intercepting the authorization code and using it.

Here is the flow:

Your role as a frontend developer is to implement steps 1, 3, 4, and 6.

  1. Generate a code_verifier and a code_challenge. Redirect the user to the auth server with the challenge.
  2. On your callback page, get the authorization_code from the URL.
  3. Send that code, along with the original code_verifier, to the auth server's token endpoint.
  4. Receive the access token and store it. Now you can make authenticated requests to the resource server.

Implement an API Interceptor for Tokens

Once you have a token, you must send it with every protected API request. The standard is to use the Authorization header with the Bearer scheme.

Doing this manually for every fetch call is error-prone. A better approach is to use an interceptor pattern, which automatically attaches the token to outgoing requests and can handle token refresh logic.

This example shows a wrapper around fetch. In a real app, you'd use the interceptor feature of a library like Axios, or build a more robust wrapper.

// Assume getToken() retrieves the token from memory or storage.
const getToken = () => window.sessionStorage.getItem('accessToken');
// Assume refreshToken() handles the refresh flow and returns a new token.
const refreshToken = async () => {
  // In a real app, this would make a POST request to /refresh_token
  // using the HttpOnly refresh token cookie.
  const newAccessToken = 'new-refreshed-jwt-from-server';
  window.sessionStorage.setItem('accessToken', newAccessToken);
  return newAccessToken;
};

async function authenticatedFetch(url: string, options: RequestInit = {}) {
  let token = getToken();
  const headers = new Headers(options.headers);

  if (token) {
    headers.set('Authorization', `Bearer ${token}`);
  }

  let response = await fetch(url, { ...options, headers });

  if (response.status === 401) {
    try {
      const newAccessToken = await refreshToken();
      headers.set('Authorization', `Bearer ${newAccessToken}`);
      // Retry the original request with the new token
      response = await fetch(url, { ...options, headers });
    } catch (refreshError) {
      // Handle refresh failure: redirect to login, etc.
      console.error("Session expired. Please log in again.");
      window.location.href = '/login';
      return response; // Or throw an error
    }
  }

  return response;
}

// Usage:
// const userProfile = await authenticatedFetch('/api/profile').then(res => res.json());

This demonstrates the complete lifecycle: attach, send, detect expiration (401), refresh, and retry. This is what interviewers want to see.

Try it

Write a function that takes a JWT string as input. Without using a library, decode its payload and check if the token is expired based on the exp claim. The exp claim is a Unix timestamp (seconds since epoch). Remember that the payload is the second part of the token string and is Base64Url encoded.

Next: Global Error Boundaries in React

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Handling API Errors in the Frontend

Next

Global Error Boundaries in React