Lesson 11 of 12 · 12 min · How the browser works
CORS and the same-origin policy
What you will learn
- What an origin is and what the same-origin policy protects
- How CORS lets servers opt in to cross-origin requests
- Simple requests versus preflight (
OPTIONS) requests - The key headers:
Access-Control-Allow-Origin,-Methods,-Headers,-Credentials - How to fix the usual CORS errors and what CORS does not do
In simple words
Imagine you are logged in to your bank in one browser tab. In another tab, you open a random website. Without a rule, that website's script could ask your bank for your account details using your logged-in session, and read the answer. To stop this, browsers apply the same-origin policy: a page may read responses only from its own website. CORS is the controlled exception: a server can say "pages from this other website are allowed to read my responses".
Words to know
- Origin: the combination of scheme, host and port of a URL.
- Same-origin policy: the browser rule that stops a page from reading data from another origin.
- CORS: Cross-Origin Resource Sharing, the headers servers use to allow other origins.
- Preflight: a request the browser sends first, with the
OPTIONSmethod, to ask whether the real request is allowed.
What is an origin?
An origin is scheme + host + port. Two URLs are the same origin only if all three match:
| URL | Same origin as https://app.example.com? |
|---|---|
https://app.example.com/page2 |
yes (the path does not matter) |
http://app.example.com |
no: different scheme |
https://api.example.com |
no: different host (subdomains count as different origins) |
https://app.example.com:8443 |
no: different port |
https://example.com |
no: different host |
Typical situation: a React app at https://app.example.com (or http://localhost:5173 while developing) calls an API at https://api.example.com (or http://localhost:8080). Those are cross-origin requests, and CORS applies.
The same-origin policy
The browser's same-origin policy does not stop pages from sending many cross-origin requests (links, forms, images, scripts, fetch), but it blocks scripts from reading the responses of cross-origin requests unless the server permits it. It protects users from a malicious site reading their data from another site where they are logged in (cookies are attached automatically). It is enforced by the browser.
How CORS works
When your script on https://app.example.com runs:
const response = await fetch("https://api.example.com/orders");
the browser sends the request with an Origin header and checks the response for permission:
GET /orders HTTP/2
Host: api.example.com
Origin: https://app.example.com
HTTP/2 200
Access-Control-Allow-Origin: https://app.example.com
Content-Type: application/json
...
If Access-Control-Allow-Origin matches the page's origin (or is * for non-credentialed requests), the script may read the response. If it is missing or different, the browser blocks the script from reading it and logs an error such as:
Access to fetch at 'https://api.example.com/orders' from origin 'https://app.example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
Note that the request did reach the server and the server processed it; only the browser refuses to hand the answer to your script. That is why CORS is not a protection for the server.
Simple requests and preflight
Some requests are "simple" (GET, HEAD, or POST with a form-like content type and no custom headers). The browser just sends them and checks the response headers, as above.
For anything else, such as PUT, DELETE, PATCH, a JSON Content-Type (application/json), or custom headers like Authorization, the browser first sends a preflight request using OPTIONS to ask permission:
OPTIONS /orders HTTP/2
Origin: https://app.example.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorization
HTTP/2 204
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
If the server approves, the browser sends the real POST. Access-Control-Max-Age lets the browser cache the preflight for that many seconds (browsers cap it) to avoid an extra round trip every time. In the Network panel you see an OPTIONS request before the real one.
| Response header | Meaning |
|---|---|
Access-Control-Allow-Origin |
the origin allowed to read the response (one origin, or *) |
Access-Control-Allow-Methods |
methods allowed (preflight response) |
Access-Control-Allow-Headers |
request headers allowed (preflight response) |
Access-Control-Allow-Credentials: true |
allow cookies and HTTP authentication |
Access-Control-Expose-Headers |
extra response headers the script may read (by default only a few are visible) |
Access-Control-Max-Age |
how long the preflight result may be cached |
Vary: Origin |
tell caches the response depends on the Origin header (set it when you echo the origin) |
Credentials
By default, cross-origin fetch does not send cookies. To send cookies or HTTP authentication, the client must opt in and the server must agree:
fetch("https://api.example.com/orders", { credentials: "include" });
Server response headers:
Access-Control-Allow-Origin: https://app.example.com <- must be a specific origin, NOT *
Access-Control-Allow-Credentials: true
With credentials, the wildcard * is not allowed for the origin, methods or headers. The cookies must also satisfy their own rules: a cross-site cookie needs SameSite=None; Secure, and browsers' privacy restrictions on third-party cookies can interfere (the storage lesson). Many teams avoid the problem by serving the API under the same site (app.example.com and api.example.com are the same site though different origins) or the same origin through a reverse proxy.
Fixing CORS errors
CORS is configured on the server; you cannot fix it from the client code. Steps:
- Read the exact message in the console and look at the Network panel: is there a preflight
OPTIONS, what status did it return (a401,403or404or405onOPTIONSis common), and which headers are missing? - Allow the right origin on the server, from an allow-list of known origins (not a blind echo of the
Originheader). - Answer the preflight (
OPTIONS) before authentication: otherwise the browser's preflight, which carries no credentials, gets a401and fails. - Allow the methods and headers the client uses (
Authorization,Content-Type). - For cookies, set
Allow-Credentialsand a specific origin, andcredentials: "include"on the client. - In development, use a dev-server proxy (Vite:
server.proxy, Create React App:proxy) so the browser sees one origin and no CORS is needed.
Spring Boot
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com", "http://localhost:5173")
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
.allowedHeaders("Authorization", "Content-Type")
.allowCredentials(true)
.maxAge(3600);
}
}
With Spring Security, enable it in the filter chain (http.cors(Customizer.withDefaults())) and provide a CorsConfigurationSource, so preflights are handled before authentication (the Spring Boot security lesson shows this). @CrossOrigin on a controller works for simple cases.
Express
import cors from "cors";
app.use(cors({
origin: ["https://app.example.com", "http://localhost:5173"],
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Authorization", "Content-Type"],
credentials: true,
maxAge: 3600,
}));
Nginx or a gateway
Add the headers at the proxy, and answer OPTIONS with 204. If both the proxy and the application add Access-Control-Allow-Origin, the browser rejects duplicate headers, so configure it in one place only.
What CORS is not
- It is not authentication or authorisation. Anyone can call your API with
curl, Postman or a script on a server; CORS does not stop them. Protect the API with authentication, authorisation and rate limits. - It does not stop requests from reaching your server; it only blocks scripts in browsers from reading cross-origin responses. A simple
POSTcan still change data (which is why you also need CSRF protection when using cookies). - It is not a firewall, and it does not apply to server-to-server calls.
Access-Control-Allow-Origin: *is not "unsafe" for public data (public APIs, fonts, images, open data), but it is wrong for anything private or credentialed. Never reflect the request'sOriginblindly with credentials: that lets any site read your users' data.- A browser extension or
no-corsmode is not a fix:fetch(url, { mode: "no-cors" })gives an opaque response your code cannot read.
Other cross-origin features
<script>,<img>,<link>and fonts can load cross-origin without CORS, but with thecrossoriginattribute they are fetched in CORS mode (required for fonts, for reading canvas pixels, and for Subresource Integrity checks).postMessageallows controlled messaging between windows and iframes of different origins; always checkevent.origin.Cross-Origin-Opener-Policy,Cross-Origin-Embedder-Policyand CORP are related headers for isolation.- JSONP was an old workaround; do not use it.
Common mistakes
- Trying to fix CORS in the client code instead of the server.
- Using
*with credentials, or reflecting any origin. - Authentication running before the preflight is answered, so
OPTIONSreturns401. - Duplicate CORS headers from a proxy and the app.
- Believing CORS protects the API.
- Forgetting that ports,
httpandhttpsand subdomains are different origins. - Leaving
localhostorigins in production configuration.
Try it yourself
- Run a front end on
localhost:5173and an API onlocalhost:8080and call it; read the CORS error. - Add CORS configuration to the API for the front end's origin and check the headers in the Network panel.
- Send a
PUTwith JSON and find the preflightOPTIONSrequest and its response headers. - Make the call with
credentials: "include"and fix the*error by naming the origin and enabling credentials. - Configure a dev proxy so the browser calls
/apion its own origin and no CORS is needed.
Check yourself
What defines an origin?
The scheme, host and port of a URL; if any differs, it is a different origin.
What is a CORS preflight request?
An OPTIONS request the browser sends before certain cross-origin requests (non-simple methods, JSON content type, custom headers) to check whether the server allows the real request.
Does CORS stop someone from calling your API with curl?
No. CORS is enforced only by browsers on scripts reading cross-origin responses; it does not protect the server.
Why can't you use Access-Control-Allow-Origin: * with credentials?
The specification forbids the wildcard for credentialed requests; the server must name the specific origin and send Access-Control-Allow-Credentials: true.
Interview questions
What is CORS and why does it exist?
A mechanism that lets servers allow web pages from other origins to read their responses. It exists because the same-origin policy otherwise stops scripts from reading cross-origin responses, protecting users' logged-in sessions from malicious sites.
You get a CORS error calling your API from a React app. How do you debug it?
Check the console message and the Network tab for the preflight; confirm the server returns the correct Access-Control-Allow-Origin, methods and headers, that OPTIONS is answered without authentication, that credentials settings match, and that proxies do not duplicate headers.
How can you avoid CORS during development?
Use a dev-server proxy (Vite, webpack) or a reverse proxy so the browser talks to a single origin.
Summary
- An origin is scheme plus host plus port; the same-origin policy stops scripts reading cross-origin responses.
- CORS lets servers opt in with
Access-Control-Allow-*headers; non-simple requests trigger anOPTIONSpreflight. - Credentials need a specific origin and
Allow-Credentials: true; configure CORS on the server with an allow-list and answer preflights before authentication. - CORS is not security for your API; keep real authentication and CSRF protection.
Going deeper
- MDN: Cross-Origin Resource Sharing (CORS): the complete guide, with preflight and credentials.
- MDN: Same-origin policy: what is blocked and what is not.
- Fetch Standard: CORS protocol: the specification.
- Spring Framework: CORS: configuration in Spring MVC and Security.
See how much of this you can explain
A free mock interview asks you new questions on HTML, CSS and how the web works for Frontend Developer and scores every answer, with what to fix.