Complete CORS Configuration Guide: Cross-Origin Resource Sharing Explained

Same-origin policy and CORS: a browser-enforced policy

Same origin means identical scheme, host, and port. Any difference makes it cross-origin:

Page URL Request URL Same origin? Why
https://app.example.com/page https://app.example.com/api ✅ Same scheme, host, and port
https://app.example.com http://app.example.com ❌ Different scheme
https://app.example.com https://api.example.com ❌ Different host
https://app.example.com https://app.example.com:8443 ❌ Different port

The key insight: the same-origin policy restricts reading responses, not sending requests. Cross-origin form posts, <img> loads, and <script> includes all reach the server and execute; CORS only relaxes whether JavaScript may see the response body.

Two conclusions follow:

  1. CORS is browser behaviour. The server handles the request as usual; the browser decides afterwards whether to hand the response to the page. curl, Postman, and server-side scripts ignore it entirely.
  2. CORS is not access control. It cannot stop anyone from calling your API; it only stops another site from reading your response inside a user's browser. Real authorization belongs on the server.

Simple requests and preflight

Browsers split requests by whether they can cause side effects.

Simple requests

When all of the following hold, the browser sends the request directly with no preflight:

  • The method is GET, HEAD, or POST;
  • Only safelisted headers are used (Accept, Accept-Language, Content-Language, Content-Type, and similar);
  • Content-Type is limited to text/plain, multipart/form-data, or application/x-www-form-urlencoded.

Note: no preflight does not mean safe. The request has already left and the server has already acted; without a correct Access-Control-Allow-Origin, the browser merely refuses to let the page read it. Protecting against side effects is a CSRF and API-design concern.

Preflight

A non-simple method, a custom header (Authorization, X-Requested-With), or Content-Type: application/json triggers an OPTIONS first, carrying Origin, Access-Control-Request-Method, and Access-Control-Request-Headers. The server must answer three things before the real request goes out:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Vary: Origin

The usual preflight failure is not a wrong CORS header but an OPTIONS request blocked by an authentication middleware (401), redirected by a gateway, or answered 405 by a router. Preflights carry no business credentials yet must be allowed — the step most often missed.

Six response headers, three of them routinely misconfigured

Header Purpose Common mistake
Access-Control-Allow-Origin Which origin may read the response Reflecting any Origin; * with credentials
Access-Control-Allow-Credentials Whether cookies may travel Paired with *, which the browser rejects
Access-Control-Allow-Methods Methods allowed by the preflight Missing the method actually used
Access-Control-Allow-Headers Request headers allowed Missing Authorization or a custom header
Access-Control-Expose-Headers Response headers JS may read Forgetting X-Total-Count and similar
Access-Control-Max-Age How long to cache the preflight Set too long; old results outlive config changes

Three hard rules:

  • Access-Control-Allow-Origin must be one origin or *, never a comma-separated list. For multiple origins, match the request Origin against an allowlist.
  • With credentials (cookies or HTTP auth), Access-Control-Allow-Origin cannot be * and Access-Control-Allow-Credentials must be true.
  • Whenever the response varies with Origin, send Vary: Origin, or a CDN or proxy will cache site A's response for site B.

The most dangerous configuration is "reflect the Origin and allow credentials":

// ❌ Any site can read your API with the user's cookies
res.setHeader('Access-Control-Allow-Origin', req.headers.origin)
res.setHeader('Access-Control-Allow-Credentials', 'true')

That is semantically "disable the same-origin policy". It is worse than no CORS at all: no CORS merely hides the response, while this hands every logged-in user's response to any site.

Four working configurations

Nginx: same-origin reverse proxy (recommended)

The most robust option is not configuring CORS but making the page and API same-origin: proxy app.example.com/api to the backend so the front end calls /api and the browser never sees a cross-origin request.

When cross-origin is genuinely required, here is the minimum working configuration:

# Allowlist: echo only matching Origins, otherwise return nothing
map $http_origin $cors_origin {
    default "";
    "~^https://(www\.)?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 Content-Length 0;
            add_header Content-Type text/plain;
            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://backend;
    }
}

Never omit always: without it, add_header only applies to 2xx/3xx responses, so a 4xx/5xx backend reply loses the CORS headers and the front end sees only "CORS error", hiding the real failure.

Re-declaring add_header inside if replaces the outer set: Nginx inheritance means any add_header at a deeper level drops all inherited ones, so the OPTIONS branch must repeat every header it needs.

Express: allowlist middleware

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

app.use((req, res, next) => {
  const origin = req.headers.origin
  if (allowlist.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin)
    res.setHeader('Access-Control-Allow-Credentials', 'true')
    res.setHeader('Vary', 'Origin')
  }

  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    return res.sendStatus(204)   // The preflight must be 2xx and must not hit auth
  }

  next()
})

Do not use cors({ origin: true, credentials: true }) — origin: true reflects any origin, exactly the dangerous configuration above. Even with the official cors package, pass a whitelist function rather than a boolean.

Spring Boot: the essentials

  • Use allowedOrigins with exact values; when wildcards are unavoidable, use allowedOriginPatterns and never combine it with allowCredentials(true) into "any origin plus credentials".
  • With Spring Security, the CorsFilter must sit before the authentication filter, or the preflight dies at a 401.
  • Permit OPTIONS in the security configuration and authenticate the real request afterwards.
  • Do not keep both a global addCorsMappings and per-controller @CrossOrigin; the more permissive one tends to win.

Wildcard subdomains: escape the regex

The *.example.com requirement is often written as endsWith('example.com'), which permits evilexample.com:

// ❌ A suffix check is bypassed by evilexample.com
if (origin.endsWith('example.com')) { /* allow */ }

// ✅ Parse, then compare hostnames with a dot boundary
function isAllowed(origin) {
  try {
    const { protocol, hostname } = new URL(origin)
    return protocol === 'https:' &&
      (hostname === 'example.com' || hostname.endsWith('.example.com'))
  } catch { return false }
}

The leading dot makes evilexample.com fail. In a regex, escape the dot in example.com as \. and anchor it with ^...$.

Watch out for Origin: null: file:// pages, sandboxed iframes, and some redirects send it. Never put null in an allowlist — that opens the door to local files and arbitrary sandboxed pages.

Debugging: walk the response headers

The browser only says blocked by CORS policy; the actual cause is in the response. Check in order:

  1. Did the preflight succeed? Look at the OPTIONS status in the network panel. 401 / 302 / 405 are configuration problems, not front-end ones.
  2. Does Access-Control-Allow-Origin exactly equal the current Origin? A different port, a missing www, or a trailing slash all count as mismatches.
  3. With credentials, is Allow-Credentials: true present and Allow-Origin not *?
  4. Does the custom header appear in Allow-Headers and the method in Allow-Methods?
  5. Is Vary: Origin missing? It shows up as intermittent success or failure across refreshes and CDN nodes.
  6. Is the response a redirect? Preflight responses may not redirect; an http → https jump fails the preflight outright.

Reproducible results

No browser needed; curl shows exactly what the server returns:

curl -i -X OPTIONS https://api.example.com/api/users \
  -H "Origin: https://app.example.com" \
  -H "Access-Control-Request-Method: POST" \
  -H "Access-Control-Request-Headers: content-type, authorization"

Check four lines: a 2xx status, an exact echo in Access-Control-Allow-Origin, POST present in Access-Control-Allow-Methods, and authorization present in Access-Control-Allow-Headers. Miss any one and the browser blocks the real request. Header semantics are in the HTTP headers cheat sheet.

Frequently Asked Questions

Is a CORS error a frontend or a backend problem?

It is a backend configuration issue; the frontend cannot fix it in code. CORS is a policy enforced by the browser: the browser sends the request, the server responds, and the browser checks whether Access-Control-Allow-Origin permits the current origin. If not, it blocks the response and throws to your JavaScript. In other words the request reached the server and the server replied — the browser simply refused to hand the data to your code. Any frontend workaround (short of a proxy) means defeating the browser's security model, which is not advisable.

Why do I get a CORS error as soon as I add credentials?

Because the specification forbids Access-Control-Allow-Origin: * when the request carries credentials (credentials: 'include' or withCredentials = true). The server must echo the specific origin (such as https://app.example.com) and also send Access-Control-Allow-Credentials: true. Missing either one gets the response blocked. This is the most commonly hit rule — many people add credentials, keep the wildcard, and only then discover it does not work.

What is the OPTIONS preflight request, and can I remove it?

A preflight is the OPTIONS round trip a browser makes before a non-simple request, to ask whether the server will allow it. It triggers when you use methods like PUT, DELETE or PATCH, send custom headers, or set a Content-Type outside application/x-www-form-urlencoded, multipart/form-data and text/plain. You cannot remove it entirely, but Access-Control-Max-Age: 86400 lets the browser cache the result for 24 hours and skip the extra round trip on subsequent requests.

Is setting Access-Control-Allow-Origin to * safe?

It depends. For public read-only assets (fonts, open APIs) the wildcard is fine. But as soon as you authenticate with cookies, sessions or an Authorization header, * is both unsafe and disallowed — you must echo a specific origin from an allow-list. Worse than the wildcard is echoing back whatever origin arrives, which opens user credentials to the entire web. The correct server-side approach is a maintained origin allow-list: echo a match, and omit the header entirely for a miss. See the [HTTP headers reference](/reference/http-headers.html) for the full set.

← Back to Blog