CORS Error: What It Means and How to Fix It

By Bug Circuit Security Team
CORS Error: What It Means and How to Fix It

Is your own website affected? Check it free in 2 minutes.

Passive outside check only. Nothing is attacked, no signup.

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.com but call from https://www.example.com.
  • The preflight request fails. For "non-simple" requests, the browser first sends an OPTIONS request (a preflight) to ask permission. Requests with an Authorization header, a Content-Type: application/json body, or methods like PUT and DELETE trigger 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 with Access-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' in fetch does not fix anything. It gives you an opaque response your code cannot read.
  • Adding Access-Control-Allow-Origin to 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, http instead of https, missing www).
  • 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 meansFix
No 'Access-Control-Allow-Origin' header is presentServer sent no CORS header, or it crashed or redirectedAdd CORS on the server. Check for 4xx/5xx and redirects first
Header has a value that is not equal to the supplied originYour origin is not on the allow listAdd the exact origin (scheme, host, port)
Response to preflight request doesn't pass access control checkThe OPTIONS request failed or returned a non-2xx statusAnswer 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-HeadersHeader is missing from the allow listAdd Authorization (and Content-Type) to allowed headers
Must not be the wildcard '*' when credentials mode is 'include'Wildcard plus cookies is forbiddenReturn the specific origin and Access-Control-Allow-Credentials: true
Header contains multiple valuesTwo layers add the headerSet 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 Origin header into the response and add Access-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 matches evilexample.com. Always compare against exact origins.
  • Allowing null. The null origin 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

  1. Allow only exact origins you control, with scheme and port.
  2. 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.
  3. List only the methods and headers your app really uses.
  4. Make sure OPTIONS requests return 2xx and are not blocked by authentication.
  5. Set CORS in one layer, not both app and proxy.
  6. Add Vary: Origin when the answer changes by origin.
  7. 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 OPTIONS requests, 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.

Want certainty, not guesswork?

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

Frequently asked questions

What is a CORS error?
A CORS error is a browser message saying a web page tried to read a response from a different origin, and the server did not give permission. An origin is the scheme, host and port together. The browser blocks the read to protect users, and the server must add the right CORS headers to allow it.
How to fix a CORS error?
First, check the Network tab for the real status code and the exact console message. Then configure the server that owns the API to send `Access-Control-Allow-Origin` for your exact frontend origin, answer `OPTIONS` preflight requests, and allow needed headers like `Authorization`. Do not use a wildcard for private data.
Is a CORS error a frontend or backend problem?
The browser enforces CORS, but the fix is almost always on the backend, because only the server can grant permission. The frontend can fix wrong URLs, avoid unneeded custom headers, or use a dev proxy while developing. Setting `no-cors` in fetch does not solve it.
Why does a CORS error occur only in the browser and not in Postman or curl?
CORS is enforced by browsers, not by servers or command-line tools. Postman and curl do not apply the same-origin policy, so they show the response no matter what. That is why an API can work in Postman and still fail in your web app.
Is it safe to set Access-Control-Allow-Origin to *?
It is safe only for truly public, non-sensitive data. It is risky for private or logged-in APIs, and browsers refuse it when cookies are included. Use an allow list of exact origins instead.

Keep reading

See what attackers see, for free

Run the free passive check on your website. No login, no impact on your site, results in seconds.

Ready for the full manual audit? See pricing

Published by Bug Circuit. Written with AI assistance and reviewed for accuracy before publishing.