Lesson 199 of 296
CORS
What you will learn
- The same-origin policy and what an origin is
- What CORS is and what problem it solves
- Simple requests vs preflight requests
- The CORS headers
- Credentials and cookies with CORS
- Common mistakes, and what CORS does not protect
On this page
Origins and the same-origin policy
An origin is the combination of scheme + host + port:
| URL | Origin |
|---|---|
https://app.jobprep.co.uk/lessons | https://app.jobprep.co.uk |
https://api.jobprep.co.uk/users | https://api.jobprep.co.uk (different host: different origin) |
http://app.jobprep.co.uk | Different scheme: different origin |
https://app.jobprep.co.uk:8443 | Different port: different origin |
The same-origin policy is a browser security rule: JavaScript on one origin cannot read responses from another origin. Without it, a malicious website you visit could call fetch("https://yourbank.com/api/balance") with your logged-in cookies and read the result.
What is CORS?
CORS (Cross-Origin Resource Sharing) is how a server tells the browser: "I allow JavaScript from these other origins to read my responses." It relaxes the same-origin policy in a controlled way.
Key facts:
- CORS is enforced by browsers only. curl, Postman and other servers ignore it.
- The server decides, through response headers; the front end cannot "fix" CORS.
- A CORS error means the browser blocked JavaScript from reading the response. The request may still have reached the server.
Simple requests
A simple request (GET, HEAD or POST with only basic headers and a content type of text/plain, application/x-www-form-urlencoded or multipart/form-data) is sent directly. The browser includes an Origin header and checks the response:
Request: Origin: https://app.jobprep.co.uk
Response: Access-Control-Allow-Origin: https://app.jobprep.co.ukIf the allowed origin matches (or is *), JavaScript may read the response.
Preflight requests
For anything else (PUT, PATCH, DELETE, Content-Type: application/json, or custom headers like Authorization), the browser first sends a preflight: an OPTIONS request asking permission:
OPTIONS /api/orders/5
Origin: https://app.jobprep.co.uk
Access-Control-Request-Method: PATCH
Access-Control-Request-Headers: content-type, authorizationThe server answers:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.jobprep.co.uk
Access-Control-Allow-Methods: GET, POST, PATCH, DELETE
Access-Control-Allow-Headers: content-type, authorization
Access-Control-Max-Age: 600Only if this is acceptable does the browser send the real PATCH. Access-Control-Max-Age lets the browser cache the preflight result (here for 10 minutes), avoiding an extra request each time.
Credentials
By default, cross-origin fetch does not send cookies. To send them:
- The client uses
fetch(url, { credentials: "include" }). - The server must reply
Access-Control-Allow-Credentials: true. - The server must name the exact origin:
Access-Control-Allow-Origin: *is not allowed with credentials. - Cookies also need suitable
SameSiteandSecureattributes (Lesson 200).
A safe CORS middleware
import type { Request, Response, NextFunction } from "express";
export function cors(allowedOrigins: string[]) {
const allowed = new Set(allowedOrigins);
return (req: Request, res: Response, next: NextFunction) => {
const origin = req.header("Origin");
res.append("Vary", "Origin");
if (origin && allowed.has(origin)) {
res.setHeader("Access-Control-Allow-Origin", origin);
res.setHeader("Access-Control-Allow-Credentials", "true");
}
if (req.method === "OPTIONS") {
if (origin && allowed.has(origin)) {
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Idempotency-Key");
res.setHeader("Access-Control-Max-Age", "600");
}
res.status(204).end();
return;
}
next();
};
}- An allow-list of exact origins (from config).
Vary: Origintells caches that the response differs per origin, so a CDN does not serve one origin's headers to another. It is set on every response, including ones for origins that are not allowed. (An earlier draft of this example set it only for allowed origins; the test caught that a cached response without the header could then be reused for the wrong origin.)- In real projects the
corsnpm package does this; in NestJS,app.enableCors({ origin: [...], credentials: true }).
Common mistakes
| Mistake | Problem |
|---|---|
Reflecting any Origin back with credentials allowed | Any website can make authenticated requests and read your users' data |
Access-Control-Allow-Origin: * on private APIs | Anyone's JavaScript can read it (without cookies) |
Allowing null origin | Sandboxed iframes and local files send null; attackers can use them |
| Trying to fix CORS in the front end | Impossible; it is a server setting. A dev-server proxy can avoid it in development |
| Thinking CORS protects the server | It does not: non-browser clients ignore it. Authentication and authorisation do that |
Avoiding CORS entirely: serve the front end and the API from the same origin (for example jobprep.co.uk and jobprep.co.uk/api through a reverse proxy, or Next.js route handlers). Then no CORS is needed at all.
How to say it in an interview
"The same-origin policy stops JavaScript from reading responses from another origin, meaning scheme, host and port. CORS lets a server allow specific origins through response headers, and it is enforced only by browsers. Simple requests are sent directly with an Origin header, while others such as JSON bodies, PATCH or an Authorization header trigger an OPTIONS preflight that must return allowed methods and headers, cacheable with Max-Age. For cookies the client uses credentials include and the server must return the exact origin and Allow-Credentials true, never a wildcard. I use an allow-list with Vary: Origin, never reflect arbitrary origins, and remember CORS is not access control."
Key words
| Word | Meaning |
|---|---|
| Origin | Scheme + host + port |
| Same-origin policy | Browsers block reading responses from other origins |
| CORS | Server headers that allow chosen origins |
| Preflight | The OPTIONS request a browser sends before a non-simple request |
| Credentials | Cookies and HTTP authentication sent with a request |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.