CORS
Learn Cross-Origin Resource Sharing (CORS) — why it exists and how to configure it.
What you'll learn
- What the same-origin policy is and why browsers enforce it
- What CORS is and how it relaxes the same-origin policy safely
- How preflight requests (OPTIONS) work for non-simple requests
- Configuring CORS headers on the server: Access-Control-Allow-Origin and more
Concept
CORS
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that controls how a web page can request resources from a *different origin* than its own. An origin is the combination of scheme, host, and port — https://api.example.com and https://app.example.com are different origins. CORS is the source of the infamous "blocked by CORS" error, but understanding it turns that error from a mystery into a configuration task.
The Same-Origin Policy
By default, browsers enforce the same-origin policy: JavaScript on a page from origin A can only make fetch requests to origin A. A page at https://app.example.com cannot fetch https://api.example.com unless the API explicitly allows it. This policy prevents malicious sites from reading data from other sites where you might be logged in. It is a fundamental security boundary.
How CORS Works
CORS lets the server *opt in* to cross-origin requests by sending specific HTTP headers. The browser checks these headers and allows or blocks the response:
Access-Control-Allow-Origin: https://app.example.com— allows this specific origin.- **
Access-Control-Allow-Origin: *** — allows any origin (use only for public APIs, never with credentials). Access-Control-Allow-Methods: GET, POST, PUT, DELETE— which methods are allowed.Access-Control-Allow-Headers: Content-Type, Authorization— which request headers are allowed.
The browser does the checking automatically — you do not handle CORS in client-side code. The server must send the right headers.
Preflight Requests
For "simple" requests (GET/POST with basic headers), the browser sends the request directly. For "non-simple" requests — custom headers like Authorization, methods like PUT or DELETE, or Content-Type: application/json — the browser first sends a preflight OPTIONS request to check if the actual request is allowed. Only if the preflight passes does the browser send the real request. This two-step process is why you sometimes see an OPTIONS request in DevTools before your actual request.
Credentials and CORS
If your cross-origin request includes cookies (credentials), Access-Control-Allow-Origin: * is not allowed — you must specify the exact origin, and set Access-Control-Allow-Credentials: true. This is a common stumbling block: a wildcard origin with credentials fails, even if everything else is correct.
CORS is a Browser Feature
CORS is enforced by the browser, not the server. The server sends headers; the browser decides whether to let your JavaScript see the response. Server-to-server requests (e.g., your backend calling another API) do not have CORS restrictions — there is no browser involved. This is why CORS errors only appear in browser-based code.
Example
// Server-side CORS configuration (Node.js / Express)
const express = require("express");
const app = express();
// Manual CORS headers for a specific origin
app.use((req, res, next) => {
const allowedOrigin = "https://app.example.com";
res.setHeader("Access-Control-Allow-Origin", allowedOrigin);
res.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Max-Age", "86400"); // cache preflight
// Handle the preflight OPTIONS request
if (req.method === "OPTIONS") {
return res.sendStatus(204);
}
next();
});
// Client-side: a cross-origin fetch with credentials
async function fetchProfile() {
const response = await fetch("https://api.example.com/profile", {
credentials: "include", // send cookies cross-origin
headers: { "Authorization": "Bearer " + token }
});
return response.json();
}
The server sets CORS headers for a specific origin (not a wildcard, because credentials are involved). It handles OPTIONS preflight requests by returning 204. The client uses credentials: 'include' to send cookies cross-origin. The preflight is cached for 86400 seconds to reduce overhead.
Try it
- JSON Formatter
CORS errors often involve JSON API responses — format them to inspect the error.
- URL Encoder
Cross-origin URLs sometimes need encoding — check your request URLs.
Common mistakes
The mistake
Using Access-Control-Allow-Origin: * with credentials: 'include' in the fetch.
The fix
The wildcard origin is not allowed when credentials are involved. You must specify the exact origin (e.g., https://app.example.com) and set Access-Control-Allow-Credentials: true on the server.
The mistake
Thinking CORS is a server-side restriction that blocks the request from arriving.
The fix
CORS is enforced by the browser. The server receives and processes the request normally — it is the browser that blocks your JavaScript from reading the response if the CORS headers are missing or wrong. The fix is always on the server (send the right headers), not the client.
Related Resources
Related Guides
- JWT Security Guide
How JWTs and CORS interact when building cross-origin APIs.
Practice CORS
3 exercises
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.