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, orPOST. - No custom headers (only a few standard ones are allowed).
- If it's a
POSTrequest, theContent-Typemust beapplication/x-www-form-urlencoded,multipart/form-data, ortext/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, likeOrigin: 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 totrueto indicate that requests with credentials (like cookies orAuthorizationheaders) 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 repeatedOPTIONScalls.
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
OPTIONSrequest.
- If there's no
OPTIONSrequest, the browser thought it was a simple request, but the server didn't returnAccess-Control-Allow-Origin.- If there is an
OPTIONSrequest that failed (e.g., 404, 500), the server isn't configured to handle it for that route.- If the
OPTIONSrequest succeeded (200 or 204), I inspect its Response Headers. I compare the server'sAccess-Control-Allow-Origin,...-Methods, and...-Headerswith theOrigin,Access-Control-Request-Method, and...-Request-Headersof 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.