CORS Error: What It Means and How to Fix It
A CORS error means your browser blocked a web page from reading a response because the server did not say that page is allowed to see it, and the fix almost always belongs on the server, not in your frontend code.
This guide is for developers and site owners who just saw a red CORS message in the browser console. You will learn why the error happens, how to tell what is actually wrong, and how to fix it with copy-paste examples for Node/Express, Nginx, Spring Boot, Django, Laravel and FastAPI. You will also see why the quick fix of allowing every origin (*) can be a real security risk.
What is a CORS error?
CORS stands for Cross-Origin Resource Sharing. An origin is the combination of scheme, host and port. So https://app.example.com and https://api.example.com are different origins. So are http://localhost:3000 and http://localhost:5173.
By default, browsers follow the same-origin policy. JavaScript on one origin cannot read responses from another. CORS is the opt-in system that lets a server say "yes, that other origin may read this." It works through HTTP response headers, such as Access-Control-Allow-Origin. The MDN CORS guide covers the full mechanism.
A CORS error is the browser telling you the server did not opt in. It is not a bug in the browser, and it is not a hack attempt.
Why does a CORS error occur?
There are a few common causes:
- The server sends no CORS headers at all. This is the most common case.
- The origin is not on the allow list. Maybe you added
https://example.combut call fromhttps://www.example.com. - The preflight request fails. For "non-simple" requests, the browser first sends an
OPTIONSrequest (a preflight) to ask permission. Requests with anAuthorizationheader, aContent-Type: application/jsonbody, or methods likePUTandDELETEtrigger one. If the server answers it with an error or without the right headers, the real request never goes out. - Credentials are mixed with a wildcard. If your request sends cookies (
credentials: 'include'), the server cannot answer withAccess-Control-Allow-Origin: *. - Duplicate headers. Your app and your proxy both add CORS headers, and the browser sees two values.
- The real problem is hidden. A crash (500), a missing route (404) or a redirect can produce a response with no CORS headers. The console then shows a CORS error, but the root cause is something else.
Is a CORS error a frontend or backend problem?
The browser enforces the rule, but the server decides the answer. So the fix is on whichever server owns the resource you are calling (usually your API).
A few things you might try on the frontend do not help:
- Setting
mode: 'no-cors'infetchdoes not fix anything. It gives you an opaque response your code cannot read. - Adding
Access-Control-Allow-Originto your request does not help. It is a response header, and sending it as a request header can even trigger a preflight that fails. - Browser extensions that disable CORS only hide the problem on your own machine.
What the frontend can legitimately do:
- Fix the URL (wrong port,
httpinstead ofhttps, missingwww). - Stop sending headers you do not need, so no preflight is triggered.
- Use a dev proxy during local development (for example, Vite's
server.proxy), so the browser only talks to one origin. This is for development only. - If the API is a third party that will not add CORS support, call it from your own backend and let your frontend call your backend.
Decision flow: from error message to fix
Open the browser's Network tab first. Click the failing request and check the status code and response headers. Then match your console message:
| Console message (shortened) | What it means | Fix |
|---|---|---|
| No 'Access-Control-Allow-Origin' header is present | Server sent no CORS header, or it crashed or redirected | Add CORS on the server. Check for 4xx/5xx and redirects first |
| Header has a value that is not equal to the supplied origin | Your origin is not on the allow list | Add the exact origin (scheme, host, port) |
| Response to preflight request doesn't pass access control check | The OPTIONS request failed or returned a non-2xx status | Answer OPTIONS with 204 or 200 and the allow headers. Check auth middleware is not blocking it |
| Request header field authorization is not allowed by Access-Control-Allow-Headers | Header is missing from the allow list | Add Authorization (and Content-Type) to allowed headers |
| Must not be the wildcard '*' when credentials mode is 'include' | Wildcard plus cookies is forbidden | Return the specific origin and Access-Control-Allow-Credentials: true |
| Header contains multiple values | Two layers add the header | Set CORS in one place only |
Test the preflight yourself
This command mimics what the browser sends. Swap in your own URL and origin:
curl -i -X OPTIONS https://api.example.com/items \
-H 'Origin: https://app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: authorization,content-type'
You want a 2xx status and headers like Access-Control-Allow-Origin: https://app.example.com. If you get a 401, 404 or 500, fix that first.
Copy-paste fixes by stack
All examples use an allow list with one example origin, https://app.example.com. Replace it with your real frontend origin. Set CORS in one layer only, either the app or the proxy.
Node/Express (cors package)
Install with npm install cors. Register it before your routes.
const cors = require('cors');
const allowed = ['https://app.example.com'];
app.use(cors({
origin(origin, cb) {
// no Origin header means a non-browser client, such as curl
if (!origin || allowed.includes(origin)) return cb(null, true);
cb(null, false);
},
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
maxAge: 600
}));
Nginx
The map block goes in the http context. It echoes the origin only if it is on the list.
map $http_origin $cors_origin {
default '';
'https://app.example.com' $http_origin;
}
server {
location /api/ {
if ($request_method = OPTIONS) {
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Methods 'GET, POST, PUT, DELETE, OPTIONS' always;
add_header Access-Control-Allow-Headers 'Content-Type, Authorization' always;
add_header Access-Control-Allow-Credentials 'true' always;
add_header Access-Control-Max-Age 600 always;
add_header Vary Origin always;
return 204;
}
add_header Access-Control-Allow-Origin $cors_origin always;
add_header Access-Control-Allow-Credentials 'true' always;
add_header Vary Origin always;
proxy_pass http://127.0.0.1:3000;
}
}
Nginx skips add_header when the value is empty, so unlisted origins get no CORS header. Run nginx -t before nginx -s reload.
Spring Boot
@Configuration
public class CorsConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/api/**")
.allowedOrigins("https://app.example.com")
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
.allowedHeaders("Content-Type", "Authorization")
.allowCredentials(true)
.maxAge(600);
}
}
If you use Spring Security, also enable CORS there with http.cors(Customizer.withDefaults()). Otherwise the security filter can reject the preflight first. See the Spring CORS docs.
Django (django-cors-headers)
Run pip install django-cors-headers, then edit settings.py:
INSTALLED_APPS = [
# ...
'corsheaders',
]
MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware', # as high as possible
'django.middleware.common.CommonMiddleware',
# ...
]
CORS_ALLOWED_ORIGINS = ['https://app.example.com']
CORS_ALLOW_CREDENTIALS = True
The package's defaults already allow authorization and content-type headers. See the django-cors-headers docs.
Laravel
Laravel includes CORS handling. On newer versions, publish the config with php artisan config:publish cors. Then edit config/cors.php:
return [
'paths' => ['api/*'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
'allowed_origins' => ['https://app.example.com'],
'allowed_headers' => ['Content-Type', 'Authorization'],
'max_age' => 600,
'supports_credentials' => true,
];
Run php artisan config:clear afterward so cached config does not hide your change. See the Laravel docs.
FastAPI
from fastapi.middleware.cors import CORSMiddleware
app.add_middleware(
CORSMiddleware,
allow_origins=['https://app.example.com'],
allow_credentials=True,
allow_methods=['GET', 'POST', 'PUT', 'DELETE'],
allow_headers=['Authorization', 'Content-Type'],
max_age=600,
)
The FastAPI CORS tutorial notes that allow_origins=['*'] does not work with credentials.
Why a wildcard origin is a security risk
Setting Access-Control-Allow-Origin: * is the most copied "fix" online. It makes the error vanish. It also tells every website on the internet that its JavaScript may read your responses.
For truly public data, such as a public font file or an open read-only API, that is fine. For anything else, it is risky:
- Internal or private-network APIs. A visitor's browser can act as a bridge. A malicious page can read responses from an admin panel or local service the visitor can reach but the attacker cannot.
- Dynamic reflection. Some developers copy the incoming
Originheader into the response and addAccess-Control-Allow-Credentials: true. That is effectively a wildcard that works with cookies. Any site can then read a logged-in user's private data. - Sloppy matching. Checking that an origin "ends with
example.com" also matchesevilexample.com. Always compare against exact origins. - Allowing
null. Thenullorigin can be produced by sandboxed pages and other contexts. Do not put it on your allow list.
OWASP explains these patterns in its CORS testing guide.
Two more points to keep in mind. CORS is not authentication. Tools like curl ignore it, so your API still needs real login and permission checks. And for simple requests, the browser may still send the request; CORS only stops the page from reading the reply. Keep other protections, such as CSRF defenses, in place.
If you do reflect origins dynamically, check them against an exact allow list and send Vary: Origin so caches do not serve one origin's answer to another.
Safe CORS checklist
- Allow only exact origins you control, with scheme and port.
- Never combine a wildcard or an unchecked reflected origin with credentials. Echoing an origin is only safe after matching it against an exact allow list.
- List only the methods and headers your app really uses.
- Make sure
OPTIONSrequests return 2xx and are not blocked by authentication. - Set CORS in one layer, not both app and proxy.
- Add
Vary: Originwhen the answer changes by origin. - Re-test after deploys. You can also review your other response headers with the security headers tool.
If you wonder whether CORS is one of several gaps, our guide on whether your website is hackable shows what attackers typically look at first.
Key takeaways
- A CORS error means the browser blocked a cross-origin read because the server did not allow it. Fix it on the server that owns the resource.
- Read the exact console message and check the Network tab. A 401, 404 or 500 can hide behind a CORS error.
- Use an exact-origin allow list, answer preflight
OPTIONSrequests, and set headers in only one layer. - Avoid
*for anything private, and never combine a wildcard or an unchecked reflected origin with credentials. Echo an origin only after matching it against an exact allow list. - CORS is not a login system. Keep real authentication and authorization on every endpoint.
Want a human to check it?
CORS settings are easy to get slightly wrong, and automated scanners often miss how they combine with cookies and login. A Circuit audit is $49 one time. A real security engineer reviews your site by hand and writes up every issue with severity, evidence and exact fixes. It is a focused small-site audit, not an enterprise pentest or a compliance certification. If you want a no-cost first look, try the free website security check.
A real human security engineer audits your whole site by hand and sends a full report: every issue, its severity, and the exact fix. From $49, with a 14-day money-back guarantee.
See pricing