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
57

Frontend System Design · Lesson 57 of 86 · 5 min

CORS: Cross-Origin Resource Sharing

This topic tests your grasp of fundamental browser security. Get it wrong, and you signal a major gap in your knowledge.

Why CORS exists: The Same-Origin Policy

Before CORS, there was the Same-Origin Policy (SOP). It's a browser security rule that stops a script on site-a.com from reading data from site-b.com. This is critical. Without it, any malicious site you visit could make a fetch request to your bank's API, read your account balance from the JSON response, and send it to their own server.

An "origin" is the combination of scheme, host, and port. https://app.example.com and http://app.example.com are different origins (scheme). https://app.example.com and https://api.example.com are different origins (host).

But modern apps need to make cross-origin requests. Your frontend at app.my-service.com needs to call your API at api.my-service.com. CORS is the mechanism that lets a server safely opt-out of the SOP for specific origins.

It's a negotiation between the browser and the server. The browser sends extra headers, and the server responds with extra headers. CORS is not an API you call; it's a set of rules the browser enforces based on HTTP headers.

How the browser handles cross-origin requests

The browser categorizes every cross-origin request into one of two types: simple or preflighted.

Simple requests don't trigger a preflight. They are sent directly. To qualify, a request must meet all these conditions:

  • Method is GET, HEAD, or POST.
  • No custom headers (only a few standard ones are allowed).
  • If it's a POST request, the Content-Type must be application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Notice what's missing: application/json. This means nearly every modern API call that sends a JSON body is not a simple request.

Preflighted requests are for everything else. This includes requests using methods like PUT or DELETE, requests with custom headers like Authorization, or requests sending application/json.

Before sending the actual request, the browser first sends a preflight OPTIONS request to the same URL. This OPTIONS request asks the server for permission. If the server responds with the right headers saying "yes, a PUT request with a Content-Type header from your origin is okay," the browser then sends the actual PUT request. If not, the browser blocks the PUT request and throws a CORS error in the console.

The trap: A common failure point is the server not being configured to handle the OPTIONS method. If your API endpoint only listens for PUT at /resource/123, the browser's preflight OPTIONS request to that same URL will get a 404 Not Found or 405 Method Not Allowed. The preflight fails, and the browser never even attempts the PUT.

The headers you must know

You need to know the key headers involved in the CORS negotiation.

Request Headers (sent by the browser):

  • Origin: Present on every cross-origin request. It simply states the origin of the client, like Origin: https://app.my-service.com.

  • Access-Control-Request-Method: Sent on preflight requests. Tells the server what method the actual request will use, e.g., Access-Control-Request-Method: PUT.

  • Access-Control-Request-Headers: Sent on preflight requests. Tells the server what non-standard headers the actual request will include, e.g., Access-Control-Request-Headers: Content-Type, X-Auth-Token.

Response Headers (sent by the server):

  • Access-Control-Allow-Origin (ACAO): The most important one. The server uses this to specify which origin is allowed to access the resource. It can be a specific origin (https://app.my-service.com) or a wildcard (*).

  • Access-Control-Allow-Methods: Sent in response to a preflight. Specifies the methods allowed for the resource, e.g., GET, POST, PUT.

  • Access-Control-Allow-Headers: Sent in response to a preflight. Specifies the headers allowed in the actual request, e.g., Content-Type, X-Auth-Token.

  • Access-Control-Allow-Credentials: Set to true to indicate that requests with credentials (like cookies or Authorization headers) are allowed.

The trap: You cannot use Access-Control-Allow-Origin: * if Access-Control-Allow-Credentials is true. This is a hard rule enforced by browsers. For credentialed requests, the server must respond with a specific, non-wildcard origin.

  • Access-Control-Max-Age: Tells the browser how long (in seconds) it can cache the results of a preflight request, avoiding repeated OPTIONS calls.

Implementing a preflighted request

Here is a complete, practical example. The client on localhost:3000 sends a PUT request with a JSON body and a custom header to a server on localhost:8080. This will trigger a preflight.

Client-side code (localhost:3000)

This fetch call will cause the browser to send an OPTIONS request first.

// Client-side code on http://localhost:3000
async function updateResource() {
  try {
    const response = await fetch('http://localhost:8080/update-resource', {
      method: 'PUT',
      headers: {
        'Content-Type': 'application/json', // Triggers preflight
        'X-Auth-Token': 'secret-token-123', // Custom header also triggers preflight
      },
      body: JSON.stringify({ id: 42, name: 'Updated Item' }),
    });

    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }

    const result = await response.json();
    console.log('Update successful:', result);
  } catch (error) {
    console.error('Error updating resource:', error);
  }
}

updateResource();

Server-side code (localhost:8080)

Using the cors middleware in Express is the standard way to handle this. It automatically responds to OPTIONS requests based on your configuration.

// Server-side Node.js/Express on http://localhost:8080
import express from 'express';
import cors from 'cors';

const app = express();
app.use(express.json());

const corsOptions = {
  origin: 'http://localhost:3000',
  methods: ['GET', 'PUT', 'POST'],
  allowedHeaders: ['Content-Type', 'X-Auth-Token'],
};

// The cors middleware handles the OPTIONS preflight request automatically
app.use(cors(corsOptions));

app.put('/update-resource', (req, res) => {
  const authToken = req.headers['x-auth-token'];
  console.log(`Received update with token: ${authToken}`, req.body);
  res.json({ success: true, message: `Resource ${req.body.id} updated.` });
});

app.listen(8080, () => {
  console.log('Server listening on port 8080');
});

How to debug a CORS error

When an interviewer asks how you'd debug a CORS issue, they're testing your practical knowledge. Don't just say "I'd check the headers." Be specific.

My process is always the same. First, I open the browser's Network tab and look for the failed request, which will be highlighted in red. I check the console for the exact CORS error message; it's usually very specific, like "Header X is not allowed" or "Method Y is not allowed."

Then, I filter the Network tab for the request URL to see if there was a preflight OPTIONS request.

  • If there's no OPTIONS request, the browser thought it was a simple request, but the server didn't return Access-Control-Allow-Origin.
  • If there is an OPTIONS request that failed (e.g., 404, 500), the server isn't configured to handle it for that route.
  • If the OPTIONS request succeeded (200 or 204), I inspect its Response Headers. I compare the server's Access-Control-Allow-Origin, ...-Methods, and ...-Headers with the Origin, Access-Control-Request-Method, and ...-Request-Headers of my intended actual request. The mismatch is almost always right there.

Try it

Set up a minimal Node/Express server on one port (8080) and a simple index.html file served by another simple server on a different port (3000). In the HTML file, write a fetch call that triggers a preflight request (e.g., a DELETE request). Use your browser's dev tools to inspect the OPTIONS call and its response headers. Then, intentionally break the server's CORS config (e.g., remove DELETE from allowed methods) and observe the new error.

Next: You'll learn how to defend against a different class of attacks in "Preventing XSS (Cross-Site Scripting)".

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice system design problems
Previous

Real User Monitoring (RUM)

Next

Preventing XSS (Cross-Site Scripting)