Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Next.js and React

The browser blocks your API response: no Access-Control-Allow-Origin header

ErrorAccess 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.

Short answer

The browser received the response but refused to hand it to your script, because it did not carry an Access-Control-Allow-Origin header naming the page's origin. curl and Postman skip this check, so the API can look fine there. Usually the OPTIONS preflight failed first, credentials met a wildcard, a proxy dropped or doubled the header, or the allowed origin is spelled differently.

  • Applies to Express 5, cors 2.8, NestJS 11 and 12 on Express, nginx 1.26, current Chrome and Firefox
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Send the preflight yourself, with the same Origin and the same method and headers the page uses. The status line and the Access-Control-* headers that come back point to the cause. JavaScript only ever sees a generic network failure, so DevTools (Network tab, then the OPTIONS row) and curl are the only places the details show.

    curl -s -o /dev/null -D - -X OPTIONS https://api.example.com/orders \
      -H "Origin: https://app.example.com" \
      -H "Access-Control-Request-Method: POST" \
      -H "Access-Control-Request-Headers: content-type,authorization"
  2. 2Match what you see, then jump to its fix

    1. 1In DevTools the OPTIONS row has a 401, 403, 404 or 405 status and no Access-Control-* headers; the real request is never sent.The preflight OPTIONS request never reaches the CORS codeFix
    2. 2Firefox names it directly: Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*'. The frontend uses credentials: 'include', withCredentials or a cookie session.Cookies or credentials are sent, but the server answers with *Fix
    3. 3Calling the app's own port shows the header but the public URL does not; or the error only appears on 413, 502 or 504 responses; or Firefox reports Multiple CORS header 'Access-Control-Allow-Origin' not allowed.nginx in front drops the header, or adds a second oneFix
    4. 4The header is present but the browser still refuses it; Firefox says CORS header 'Access-Control-Allow-Origin' does not match, and the value differs by a slash, a scheme, www or a port.The allowed origin is written differently from the one the browser sendsFix

What does the error look like?

  • 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.
  • Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://api.example.com/orders. (Reason: CORS header 'Access-Control-Allow-Origin' missing).
  • Reason: Credential is not supported if the CORS header 'Access-Control-Allow-Origin' is '*'
  • Reason: Multiple CORS header 'Access-Control-Allow-Origin' not allowed

Cause 1 of 4

The preflight OPTIONS request never reaches the CORS code

1Check

A request with a JSON body, an Authorization header or a method other than GET, HEAD or POST is preflighted. The preflight carries no cookies or tokens, and the browser accepts it only with a 2xx status plus the right headers. If an auth guard, a rate limiter or the router answers OPTIONS before the CORS middleware, it fails.

curl -s -o /dev/null -w "%{http_code}\n" -X OPTIONS https://api.example.com/orders \
  -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: POST"

2Fix

Register CORS before anything that can reject a request. Used as application-level middleware, the cors package answers every preflight with 204 and ends it there. In NestJS, enableCors() registers the same package for the Express platform.

// Express 5
import express from 'express'
import cors from 'cors'

const app = express()
app.use(cors({
  origin: ['https://app.example.com'],
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 600,
}))            // first: before auth, rate limits and routes
app.use(requireAuth)

// NestJS (main.ts)
const app = await NestFactory.create(AppModule)
app.enableCors({ origin: ['https://app.example.com'], allowedHeaders: ['Content-Type', 'Authorization'] })

3Verify

Repeat the preflight: it should return 204 with Access-Control-Allow-Origin set to the page's origin and the method listed in Access-Control-Allow-Methods.

curl -s -o /dev/null -D - -X OPTIONS https://api.example.com/orders \
  -H "Origin: https://app.example.com" -H "Access-Control-Request-Method: POST" \
  | grep -i "^access-control"
Did this fix it?

Cause 2 of 4

Cookies or credentials are sent, but the server answers with *

1Check

Send the real request with an Origin header and read what comes back. With credentials the browser accepts only an exact origin plus Access-Control-Allow-Credentials: true; a wildcard is rejected, and a Set-Cookie on a wildcard response is ignored.

curl -s -o /dev/null -D - https://api.example.com/me \
  -H "Origin: https://app.example.com" -H "Cookie: session=test" | grep -i "^access-control"

2Fix

Echo the caller's origin only when it is on your allowlist, and turn credentials on. Never combine credentials with origin: true, which reflects any site that asks and lets it read signed-in responses.

const allowed = new Set(['https://app.example.com', 'https://admin.example.com'])

app.use(cors({
  origin(origin, callback) {
    // no Origin header: same-origin page, curl or server-to-server call
    callback(null, !origin || allowed.has(origin))
  },
  credentials: true,
}))

3Verify

The response now carries the exact origin and Access-Control-Allow-Credentials: true, and the browser stores the session cookie.

curl -s -o /dev/null -D - https://api.example.com/me -H "Origin: https://app.example.com" \
  | grep -iE "^access-control-allow-(origin|credentials)"
Did this fix it?

Cause 3 of 4

nginx in front drops the header, or adds a second one

1Check

Compare the app directly with the public URL, then read the nginx config. add_header only applies to a short list of success and redirect codes unless you add always, and a location with any add_header of its own silently drops the ones set at server level. If both nginx and the app set the header, the browser sees two values and refuses both.

curl -s -o /dev/null -D - -H "Origin: https://app.example.com" http://127.0.0.1:3000/orders | grep -i access-control
curl -s -o /dev/null -D - -H "Origin: https://app.example.com" https://api.example.com/orders | grep -i access-control
grep -RnE "add_header|proxy_hide_header" /etc/nginx/

2Fix

Let exactly one layer own CORS. If the app owns it, delete the CORS add_header lines from nginx. If nginx owns it, answer OPTIONS there, add the headers with always so error pages carry them too, and hide the app's copy.

# http {} block
map $http_origin $cors_origin {
    default                    "";
    "https://app.example.com"  $http_origin;
}

# server {} block
location /api/ {
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin $cors_origin always;
        add_header Access-Control-Allow-Methods "GET, POST, PUT, PATCH, DELETE" 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;
    }
    proxy_hide_header Access-Control-Allow-Origin;
    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;
}

3Verify

Reload nginx, then request a path that returns an error: the header must appear once, even on the 404.

sudo nginx -t && sudo systemctl reload nginx
curl -s -o /dev/null -D - -H "Origin: https://app.example.com" https://api.example.com/api/no-such-route \
  | grep -ci "^access-control-allow-origin"   # expect 1
Did this fix it?

Cause 4 of 4

The allowed origin is written differently from the one the browser sends

1Check

An origin is only scheme, host and port: https://app.example.com, never https://app.example.com/ and never with a path. Copy the Origin request header from DevTools and compare it character by character with your configuration, including the value of the environment variable that feeds it.

node -e "console.log(JSON.stringify(process.env.CORS_ORIGINS))"
curl -s -o /dev/null -D - https://api.example.com/orders -H "Origin: http://localhost:5173" | grep -i allow-origin

2Fix

Normalise every configured value with the URL parser, which strips paths, trailing slashes and default ports, and list each development port you actually use.

const allowed = new Set(
  (process.env.CORS_ORIGINS ?? '')
    .split(',')
    .map((s) => s.trim())
    .filter(Boolean)
    .map((s) => new URL(s).origin),   // 'https://app.example.com/' -> 'https://app.example.com'
)

3Verify

Request with the exact Origin value copied from DevTools; the response must echo it back unchanged.

curl -s -o /dev/null -D - https://api.example.com/orders -H "Origin: https://app.example.com" | grep -i allow-origin
Did this fix it?

How do I stop it coming back?

  • Decide which layer owns CORS (app or proxy) and keep the other one silent.
  • Keep the allowlist in one environment variable, normalised at start-up, and add a curl preflight check to the deploy pipeline.
  • Send Vary: Origin whenever the allowed origin is echoed per request, so a shared cache cannot hand one site's answer to another.
  • Treat CORS as a browser rule, not as protection: the API still needs authentication for every request.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Web apps

A POST to a Google Apps Script web app returns 405 or a CORS error

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Apps Script web apps run doPost for POST and doGet for GET, and the Apps Script guides describe no other entry points.

3 causes, each with a fix

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.