Learning objectives
After reading this article you will be able to:
- Read the browser's CORS message and tell which header is missing
- Configure CORS in Express and FastAPI, with and without cookies
- Test the preflight with curl before touching the front end
On this page
- What does the error look like in the browser?
- What is the same-origin policy, and where does CORS fit?
- When does the browser send an OPTIONS preflight?
- What causes it, from most to least common?
- How do you fix it in Express and FastAPI?
- How do you test it with curl?
- Why isn't disabling CORS in the browser a fix?
- How to do this on Square Cloud
- FAQs
You call your API with fetch and, instead of data, the console shows a red line about a CORS policy. The same URL works fine in Postman and in curl. The API is up: what blocked the response was the browser.
CORS (Cross-Origin Resource Sharing) is how a server tells the browser which other sites may read its responses. The fix almost always lives on the server, in one or two headers, and almost never in the front end.
What does the error look like in the browser?#
Chrome and other Chromium-based browsers print it like this:
Access to fetch at 'https://api.example.com/api/items' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.The part after CORS policy: is the reason, and it points to the cause. Other common reasons:
Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
The 'Access-Control-Allow-Origin' header has a value 'https://app.example.com/' that is not equal to the supplied origin.
The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.In Firefox, the same failure looks like this, with the reason in parentheses:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/api/items. (Reason: CORS header 'Access-Control-Allow-Origin' missing).Your JavaScript gets none of these details. For security, fetch only rejects with a generic error, and the reason shows up in the console alone.
What is the same-origin policy, and where does CORS fit?#
An origin is the combination of scheme, host and port. https://app.example.com and https://api.example.com are different origins, and so are http://localhost:5173 and http://localhost:3000. The path does not count.
The same-origin policy is the browser rule that stops a script from one origin reading responses from another. It protects the user: without it, any site open in a tab could read your data from another site where you are signed in, using your cookies.
CORS is the controlled exception. The browser sends an Origin header with the page's origin, and the server answers with Access-Control-Allow-Origin saying who may read. If the value does not match, the browser receives the response but does not hand it to your code.
Two details clear up a lot of confusion:
- Only browsers enforce CORS. curl, Postman, a bot or another server call the API without this check. That is why CORS does not protect your API: authentication does, together with rate limiting.
- The block is on reading, not on sending. For a simple request, like a form
POST, the server receives it and runs the action; only the response is blocked. A CORS error does not prove that nothing happened on the other side, and that gap is what CSRF protection closes.
When does the browser send an OPTIONS preflight?#
Before some requests, the browser asks the server whether it may send them. That question is the preflight: an OPTIONS request with the Origin and Access-Control-Request-Method headers and, when there are extra headers, Access-Control-Request-Headers.
There is no preflight only for simple requests: a GET, HEAD or POST, only safelisted headers (such as Accept and Content-Language), and a Content-Type of application/x-www-form-urlencoded, multipart/form-data or text/plain. In practice, almost every modern API call is preflighted, because it sends Content-Type: application/json or an Authorization header.
For the browser to go ahead, the preflight response must:
- have a 2xx status (the Fetch standard requires an "ok status", 200 to 299);
- carry
Access-Control-Allow-Originwith the page's origin; - list the method in
Access-Control-Allow-Methods(when it is notGET,HEADorPOST) and the extra headers inAccess-Control-Allow-Headers.
Access-Control-Max-Age tells the browser how many seconds it may reuse that answer before asking again. Each browser caps the value at its own maximum.
What causes it, from most to least common?#
- Missing header. The server has no CORS setup, or it only runs on some routes. The message is the
No 'Access-Control-Allow-Origin' headerone. - Origin does not match the configured one. The comparison is exact, character by character. A trailing slash (
https://app.example.com/),httpinstead ofhttps, a missingwwwor a different port is enough to block. The message says the value "is not equal to the supplied origin". - Credentials with
*. If the front end sends cookies withcredentials: "include"(orwithCredentialsin XHR and Axios), the browser rejectsAccess-Control-Allow-Origin: *. The response needs the exact origin andAccess-Control-Allow-Credentials: true. In this mode*does not work inAllow-HeadersorAllow-Methodseither. And theAuthorizationheader is never covered by the wildcard: list it by name. - Preflight without a valid answer. The route does not accept
OPTIONSand returns 404 or 405; an auth middleware returns 401, because the preflight never carries credentials; or the server redirects (fromhttptohttps, or to the URL with a slash). A preflight accepts neither redirects nor a status outside 2xx. - A 500 dressed up as CORS. The API crashed, and the error response came from a layer that does not add the headers: the framework's exception handler, or a proxy returning 502 because the app went down. The browser sees a response without
Access-Control-Allow-Originand reports CORS. Starlette, which FastAPI is built on, documents this:ServerErrorMiddleware, which turns unhandled exceptions into a 500, always sits outside every other middleware, CORS included. If the Network tab shows 500 or 502, the cause is in your application logs, and the codes are explained in 500, 502, 503 and 504 errors. - Duplicate header. The app and a reverse proxy in front of it both add
Access-Control-Allow-Origin. The browser rejects more than one value, so configure CORS in one place only.
Uploads straight from the browser to S3-compatible object storage, with a presigned URL, are a separate case: there the storage answers the CORS check, not your API. See CORS error when uploading to object storage.
How do you fix it in Express and FastAPI?#
The rule is the same in both: an explicit list of origins, read from an environment variable so development and production differ without code changes, applied before the routes.
Express#
Install the packages with npm install express cors. The code uses ES modules, so set "type": "module" in package.json:
import express from "express";
import cors from "cors";
const app = express();
// e.g. CORS_ORIGINS="https://app.example.com,http://localhost:5173"
const allowed = (process.env.CORS_ORIGINS ?? "")
.split(",")
.map((origin) => origin.trim())
.filter(Boolean);
// Before the routes and before any auth middleware
app.use(
cors({
origin: allowed,
credentials: true, // only if the front end sends cookies
methods: ["GET", "POST", "PUT", "PATCH", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"],
maxAge: 600, // seconds the preflight may be cached
}),
);
app.use(express.json());
app.get("/api/items", (req, res) => {
res.json([{ id: 1, name: "example" }]);
});
app.listen(Number(process.env.PORT) || 3000, "0.0.0.0");With an array in origin, the package echoes the incoming origin in Access-Control-Allow-Origin only when it is on the list. Mounted with app.use, it also answers the preflight for every route, with a 204 status by default. Since the value changes with the origin, the package also sends Vary: Origin, so a cache never serves one origin's response to another. If you write the headers by hand, include Vary too.
FastAPI#
CORSMiddleware comes from Starlette and ships with FastAPI:
import os
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
# e.g. CORS_ORIGINS="https://app.example.com,http://localhost:5173"
origins = [o.strip() for o in os.environ.get("CORS_ORIGINS", "").split(",") if o.strip()]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True, # only if the front end sends cookies
allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
allow_headers=["Content-Type", "Authorization"],
max_age=600,
)
@app.get("/api/items")
async def list_items():
return [{"id": 1, "name": "example"}]The middleware's defaults are strict: without allow_methods, only GET passes, and allow_credentials starts off. The FastAPI docs ask for explicit lists when allow_credentials=True. To make even unhandled-exception responses carry the headers, the Starlette docs recommend wrapping the whole application in CORSMiddleware. Still, the real fix is getting rid of the 500.
How do you test it with curl?#
Before touching the front end, reproduce what the browser does. curl does not enforce CORS, but it shows the headers the browser will judge:
# 1. The preflight the browser sends before a JSON POST
curl -i -X OPTIONS https://api.example.com/api/items \
-H "Origin: https://app.example.com" \
-H "Access-Control-Request-Method: POST" \
-H "Access-Control-Request-Headers: content-type, authorization"
# 2. The real request, with the origin
curl -i https://api.example.com/api/items -H "Origin: https://app.example.com"In the preflight response, check four things: a 2xx status; Access-Control-Allow-Origin equal to the origin you sent (same scheme, same port, no slash); the requested method and headers inside Allow-Methods and Allow-Headers; and, if the front end sends cookies, Access-Control-Allow-Credentials: true. With the Express example, the part that matters looks like this:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Max-Age: 600If curl shows the right headers and the browser still complains, open the request in the Network tab and compare the Origin it sent with your list. Run the test against the production URL too, not just the local one: a proxy along the way can change the result.
Why isn't disabling CORS in the browser a fix?#
Extensions that "unblock CORS" and launch flags that turn off web security change only your browser. Your users open the page in a normal browser and get the same error. And browsing day to day with that protection off exposes your own sessions to any site.
fetch's mode: "no-cors" does not fix anything either: the request goes out, but the response comes back opaque, with no readable status, headers or body.
Two alternatives are legitimate:
- A development proxy. Vite's
server.proxy(and similar features in other dev servers) forwards/apito the local API. To the browser, everything comes from the same origin, so there is no CORS. It only applies while you develop. - Same origin in production. If a reverse proxy serves the front end at
/and the API at/apion the same domain, the calls are no longer cross-origin and CORS drops out of the picture.
// vite.config.js
import { defineConfig } from "vite";
export default defineConfig({
server: {
proxy: {
"/api": { target: "http://localhost:3000", changeOrigin: true },
},
},
});Beyond that, the fix is on the server. A public "CORS proxy" hides the symptom by routing your traffic, and sometimes your tokens, through someone else's server. For the other checks before opening your API to the world, see the API production checklist.
How to do this on Square Cloud#
On Square Cloud, the headers your application sends pass through the platform's proxy untouched. So CORS is configured in your code, as in the examples above, including the answer to the OPTIONS preflight.
Every published web application gets an HTTPS *.squareweb.app subdomain, and from the Standard plan up you can use a custom domain. If the front end and the API are separate applications, they are different origins: put the front end's exact URL (with https:// and no trailing slash) in a variable such as CORS_ORIGINS, set in the dashboard. The change applies on the next restart, with no rebuild.
If the CORS error shows up only on some calls, open the real-time logs and look for the API's exception at that moment: a 500 without the headers turns into "CORS" in the console. You can deploy by ZIP upload, CLI or GitHub, on the Node.js, Python or another available runtime. See how to publish your API on the API hosting page.
API hosting
APIs in always-on containers, with no cold starts
FAQs
Does CORS protect my API?
No. CORS is a browser rule that protects the user, not the server. curl, Postman and other servers ignore it, so your API still needs authentication.
Why does the request work in Postman but fail in the browser?
Postman does not enforce the same-origin policy, so it does not require CORS headers. Only the browser checks Access-Control-Allow-Origin before handing the response to JavaScript.
Can I use Access-Control-Allow-Origin: * in production?
For a public API with no cookies and no login, yes. If the front end sends cookies with credentials: 'include', the browser rejects *: return the exact origin and Access-Control-Allow-Credentials: true.
Does fetch's mode: 'no-cors' fix the error?
No. The request goes out, but the response comes back opaque: your code cannot read the status, headers or body. It only helps when you fire a request whose result you never need to read.
How do I fix a CORS error on localhost?
Add your local front end's exact origin, port included (such as http://localhost:5173), to the API's list of allowed origins. Or use your dev server's proxy, such as Vite's server.proxy, so the front end and the API share one origin.
More in APIs
See all 36 articles- How to host an APIHosting an API means running its HTTP server around the clock at a public address with HTTPS. Step-by-step with Node.js and Python, testing and common errors.
- How to host a Node.js appTo host a Node.js app, prepare package.json, read the port and secrets from the environment, pick an LTS version and run it with node. Step-by-step guide.
- How much does it cost to host an API?Hosting a small API costs a few to a few dozen dollars a month. See what goes into the bill (compute, database, bandwidth, requests, logs) and how to estimate it.
- REST vs GraphQL: which to use for your APIREST exposes one URL per resource and uses HTTP caching; GraphQL has one endpoint where the client picks the fields. Compare caching, errors, N+1 and use cases.