Lesson 11 of 12 · 12 min · How the browser works

CORS and the same-origin policy

Covers: Current browser behaviour and the Fetch standard. Updated 13 Nov 2026. Part of the Frontend Developer roadmap.

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 OPTIONS method, 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:

  1. Read the exact message in the console and look at the Network panel: is there a preflight OPTIONS, what status did it return (a 401, 403 or 404 or 405 on OPTIONS is common), and which headers are missing?
  2. Allow the right origin on the server, from an allow-list of known origins (not a blind echo of the Origin header).
  3. Answer the preflight (OPTIONS) before authentication: otherwise the browser's preflight, which carries no credentials, gets a 401 and fails.
  4. Allow the methods and headers the client uses (Authorization, Content-Type).
  5. For cookies, set Allow-Credentials and a specific origin, and credentials: "include" on the client.
  6. 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 POST can 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's Origin blindly with credentials: that lets any site read your users' data.
  • A browser extension or no-cors mode 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 the crossorigin attribute they are fetched in CORS mode (required for fonts, for reading canvas pixels, and for Subresource Integrity checks).
  • postMessage allows controlled messaging between windows and iframes of different origins; always check event.origin.
  • Cross-Origin-Opener-Policy, Cross-Origin-Embedder-Policy and 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 OPTIONS returns 401.
  • Duplicate CORS headers from a proxy and the app.
  • Believing CORS protects the API.
  • Forgetting that ports, http and https and subdomains are different origins.
  • Leaving localhost origins in production configuration.

Try it yourself

  1. Run a front end on localhost:5173 and an API on localhost:8080 and call it; read the CORS error.
  2. Add CORS configuration to the API for the front end's origin and check the headers in the Network panel.
  3. Send a PUT with JSON and find the preflight OPTIONS request and its response headers.
  4. Make the call with credentials: "include" and fix the * error by naming the origin and enabling credentials.
  5. Configure a dev proxy so the browser calls /api on 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 an OPTIONS preflight.
  • 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

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.