To fix CORS errors like "No 'Access-Control-Allow-Origin' header is present on the requested resource", configure the server that owns the API to return Access-Control-Allow-Origin with your front-end's exact origin, answer OPTIONS preflight requests with a 2xx status and the allowed methods and headers, and add Access-Control-Allow-Credentials: true (never *) if you send cookies. You cannot fix CORS from front-end code; mode: 'no-cors' only hides the response from you.

This guide explains why browsers block the request, then shows how to fix CORS errors in Express, FastAPI, Hono, Next.js, Spring, Nginx and the Vite dev server, with configs I tested against current versions where possible. There is also a table that maps each browser error message to its cause and fix, because the exact wording usually tells you which header is wrong.

Why the browser blocks the request

CORS (Cross-Origin Resource Sharing) is defined in the Fetch standard. An origin is scheme + host + port, so https://app.example.com, http://app.example.com and https://app.example.com:8443 are three different origins. By default, the same-origin policy lets a page send a cross-origin request but not read the response. CORS headers are how the server opts in to letting a specific origin read it.

Two things follow from that, and they explain most confusion:

  1. The request often still reaches your server. In my tests, an Express 5 API with an allowlist returned 200 OK to a request from an unlisted origin; it simply omitted the CORS headers, so the browser refused to hand the body to JavaScript. CORS protects the user's data in the browser. It is not authentication, and it is not CSRF protection.
  2. Only the browser enforces it. curl, Postman and server-to-server calls ignore CORS entirely. "It works in Postman" tells you nothing about CORS.

Simple requests vs preflight requests

The browser sends some requests directly and checks the response headers afterwards. MDN calls these simple requests. A request is simple only if all of these are true:

  • The method is GET, HEAD or POST.
  • It only sets CORS-safelisted headers such as Accept, Accept-Language and Content-Language.
  • Any Content-Type is application/x-www-form-urlencoded, multipart/form-data or text/plain.

Everything else gets a preflight: before the real request, the browser sends an OPTIONS request asking for permission.

OPTIONS /api/me HTTP/1.1
Origin: http://localhost:5173
Access-Control-Request-Method: PUT
Access-Control-Request-Headers: content-type,authorization

The server must answer with a 2xx status and headers that cover that origin, method and header list:

HTTP/1.1 204 No Content
Access-Control-Allow-Origin: http://localhost:5173
Access-Control-Allow-Methods: GET,POST,PUT,PATCH,DELETE
Access-Control-Allow-Headers: Content-Type,Authorization
Access-Control-Allow-Credentials: true
Access-Control-Max-Age: 600
Vary: Origin

A fetch() that sends JSON (Content-Type: application/json) or a bearer token (Authorization) always triggers a preflight. That is why "GET works but POST fails" is such a common report: the POST is the first request that needs OPTIONS handling.

Access-Control-Max-Age controls how long the browser caches a preflight. Per MDN, the default is 5 seconds, Firefox caps it at 24 hours and Chromium at 2 hours.

Credentials and the wildcard rule

If the front-end sends cookies or HTTP auth (fetch(url, { credentials: 'include' }) or axios with withCredentials: true), the rules tighten:

  • Access-Control-Allow-Origin must be the exact requesting origin, not *.
  • Access-Control-Allow-Credentials: true must be present.
  • * in Access-Control-Allow-Headers, Access-Control-Allow-Methods and Access-Control-Expose-Headers is treated as a literal string, not a wildcard.

Cookies have their own rules on top of CORS. A cookie for a different site (registrable domain) needs SameSite=None; Secure, and some browsers block third-party cookies by default. If you can, host the API on a subdomain of the same site (app.example.com calling api.example.com): that is still cross-origin for CORS, but same-site for cookies, so SameSite=Lax cookies are sent.

Why Vary: Origin matters

If your server returns a different Access-Control-Allow-Origin depending on the request, add Vary: Origin. Without it, a CDN or browser cache can store the response generated for origin A and serve it to origin B, producing intermittent CORS failures that look random. The cors package for Express, Hono's cors() and Starlette's CORSMiddleware all added Vary: Origin automatically in my tests.

Private Network Access is now Local Network Access

If a public website calls http://localhost or a 192.168.x.x device, an extra browser policy applies. Chrome's older Private Network Access proposal used special preflight headers (Access-Control-Request-Private-Network). Chrome replaced it with Local Network Access, a user permission prompt that started shipping in Chrome 142. Chrome's current guidance says not to add PNA preflight handling to new code; access is governed by the permission prompt plus ordinary CORS headers. If a public page cannot reach a local service even with correct CORS headers, this permission is the likely reason.

CORS error messages: cause and fix

Chrome's wording is shown; Firefox reports equivalent reasons, each with a page in MDN's CORS errors reference. JavaScript never sees these details, only a generic TypeError: Failed to fetch, so always read the browser console and the Network tab.

Error message (Chrome) Cause Fix
No 'Access-Control-Allow-Origin' header is present on the requested resource Server sent no CORS headers: not configured, origin not in the allowlist, or an error page from a proxy Configure CORS on the API; make sure error responses (401, 500, 502) also carry the headers
Response to preflight request doesn't pass access control check: It does not have HTTP ok status OPTIONS hit auth middleware (401), a missing route (404) or a 405 Handle OPTIONS before auth and return 204
Redirect is not allowed for a preflight request Preflight got a 301/302/307, often HTTP to HTTPS or a trailing-slash redirect Call the final URL directly
The value of the 'Access-Control-Allow-Origin' header must not be the wildcard '*' when the request's credentials mode is 'include' * combined with cookies or auth Echo the allowlisted origin and send Access-Control-Allow-Credentials: true
The value of the 'Access-Control-Allow-Credentials' header is '' which must be 'true' Credentials sent, header missing Add Access-Control-Allow-Credentials: true
Request header field authorization is not allowed by Access-Control-Allow-Headers Header missing from the preflight response Add it to the allowed headers
Method PUT is not allowed by Access-Control-Allow-Methods Method missing from the preflight response Add it to the allowed methods
The 'Access-Control-Allow-Origin' header contains multiple values CORS added twice, usually by both the proxy and the app Configure CORS in exactly one layer
The 'Access-Control-Allow-Origin' header has a value that is not equal to the supplied origin Trailing slash, wrong scheme or port in the allowlist Use the exact origin, e.g. https://app.example.com with no path

Debug CORS with curl first

Before touching code, reproduce what the browser sends. Simulate the preflight:

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

Then the actual request:

curl -i https://api.example.com/api/me -H 'Origin: https://app.example.com'

Check four things: the status of the OPTIONS response is 2xx, Access-Control-Allow-Origin exactly matches the Origin you sent, every requested method and header is listed, and nothing redirects. If the response body is JSON, a JSON formatter makes error payloads from gateways easier to read.

How to fix CORS errors in each stack

Every example below uses an explicit allowlist, supports credentials, and allows the headers a typical JSON API needs. Adjust the origins.

Express 5 with the cors package

Tested with express 5.3.0 and cors 2.8.6:

import express from 'express';
import cors from 'cors';

const app = express();
const allowlist = new Set(['https://app.example.com', 'http://localhost:5173']);

app.use(cors({
  origin(origin, callback) {
    // No Origin header: same-origin request, curl, or server-to-server
    if (!origin || allowlist.has(origin)) return callback(null, true);
    return callback(null, false); // no CORS headers, so the browser blocks it
  },
  credentials: true,
  methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 600,
}));

app.use(express.json());
app.put('/api/me', (req, res) => res.json({ updated: true }));
app.listen(3001);

Register cors() before your routes and before any auth middleware, so preflights are answered without a token. The package handles OPTIONS itself and returns 204.

FastAPI (Starlette CORSMiddleware)

Tested with FastAPI 0.165.0 on Starlette 1.10.0:

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

app.add_middleware(
    CORSMiddleware,
    allow_origins=["https://app.example.com", "http://localhost:5173"],
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],
    allow_headers=["Content-Type", "Authorization"],
    max_age=600,
)

@app.get("/api/me")
def me():
    return {"ok": True}

A preflight from a disallowed origin gets 400 Disallowed CORS origin, which is a useful signal in logs. For subdomain patterns use allow_origin_regex, and anchor it (r"^https://[a-z0-9-]+\.example\.com$"). Do not combine allow_origins=["*"] with allow_credentials=True. If you are choosing between Python and TypeScript for an API, see FastAPI vs Hono.

Hono

Tested with Hono 4.13.22 on @hono/node-server; the same middleware runs on Workers, Bun and Deno:

import { Hono } from 'hono';
import { cors } from 'hono/cors';

const app = new Hono();

app.use('/api/*', cors({
  origin: ['https://app.example.com', 'http://localhost:5173'],
  allowMethods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],
  allowHeaders: ['Content-Type', 'Authorization'],
  credentials: true,
  maxAge: 600,
}));

app.put('/api/me', (c) => c.json({ updated: true }));

export default app;

origin also accepts a function (origin, c) => string | undefined for dynamic checks. Mount cors() before any JWT or session middleware on the same path.

Next.js (App Router route handlers and proxy.ts)

For a single route handler, export an OPTIONS function and add headers to each response:

// app/api/items/route.ts
const ALLOWED = new Set(['https://app.example.com', 'http://localhost:5173']);

function corsHeaders(origin: string | null): Headers {
  const headers = new Headers({ Vary: 'Origin' });
  if (origin && ALLOWED.has(origin)) {
    headers.set('Access-Control-Allow-Origin', origin);
    headers.set('Access-Control-Allow-Credentials', 'true');
  }
  return headers;
}

export async function OPTIONS(request: Request) {
  const headers = corsHeaders(request.headers.get('origin'));
  headers.set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
  headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  headers.set('Access-Control-Max-Age', '600');
  return new Response(null, { status: 204, headers });
}

export async function GET(request: Request) {
  return Response.json({ items: [] }, { headers: corsHeaders(request.headers.get('origin')) });
}

For many routes, do it once in proxy.ts. In Next.js 16 the middleware file convention was renamed to proxy and defaults to the Node.js runtime; a codemod (npx @next/codemod@canary middleware-to-proxy .) renames existing files. The docs include a CORS example that answers preflights and sets headers for allowed origins with matcher: '/api/:path*'. If you adapt it, add Vary: Origin and Access-Control-Allow-Credentials yourself; the docs example omits both.

Spring Boot (Spring MVC and Spring Security)

In Spring MVC, register mappings globally:

@Configuration
public class CorsConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/api/**")
            .allowedOrigins("https://app.example.com", "http://localhost:5173")
            .allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE")
            .allowedHeaders("Content-Type", "Authorization")
            .allowCredentials(true)
            .maxAge(600);
    }
}

If Spring Security is on the classpath, preflights hit the security filter chain first and are rejected without a token unless you enable CORS there. The Spring Security 7.2 reference shows the pattern:

@Bean
SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
    http
        .cors(Customizer.withDefaults()) // uses the Spring MVC CORS config
        .authorizeHttpRequests(auth -> auth.anyRequest().authenticated());
    return http.build();
}

Spring throws an IllegalArgumentException if you combine allowedOrigins("*") with allowCredentials(true); use allowedOriginPatterns if you need wildcards such as https://*.example.com. Upgrading as well? Our Spring Boot 4 migration guide covers the security configuration changes.

Nginx in front of your API

Use Nginx for CORS only if the application does not set CORS headers; doing both produces the "multiple values" error. A map keeps the allowlist explicit:

map $http_origin $cors_origin {
    default                         "";
    "https://app.example.com"       $http_origin;
    "~^http://localhost:(3000|5173)$" $http_origin;
}

server {
    listen 443 ssl;
    server_name api.example.com;

    location /api/ {
        if ($request_method = OPTIONS) {
            add_header Access-Control-Allow-Origin      $cors_origin always;
            add_header Access-Control-Allow-Credentials "true" always;
            add_header Access-Control-Allow-Methods     "GET, POST, PUT, PATCH, DELETE, OPTIONS" always;
            add_header Access-Control-Allow-Headers     "Content-Type, Authorization" 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:3001;
    }
}

Three Nginx-specific gotchas. always is required, or the headers disappear from 4xx and 5xx responses and you get the "No 'Access-Control-Allow-Origin' header" error exactly when you need to see the real error. add_header directives are not inherited into a block that defines its own add_header, which is why they are repeated. And Nginx skips add_header when the value is empty, so unlisted origins simply get no Access-Control-Allow-Origin.

Vite dev server: avoid CORS with a proxy

In development, the cleanest fix is often not to make the request cross-origin at all. The Vite server.proxy option forwards /api from the dev server to your backend, so the browser only ever talks to localhost:5173:

// vite.config.js
import { defineConfig } from 'vite';

export default defineConfig({
  server: {
    proxy: {
      '/api': {
        target: 'http://localhost:3001',
        changeOrigin: true,
      },
    },
  },
});

The front-end calls fetch('/api/me') with a relative URL. In production, put the app and API behind the same domain with a reverse proxy, or configure real CORS on the API. Note that Vite's own server.cors setting only controls CORS for the dev server's assets (by default it allows localhost origins); it does not add headers to your API. Toolchain details are in our Vite 8 migration guide.

Fixes that do not work

  • mode: 'no-cors' in fetch. It suppresses the error by giving you an opaque response with no readable body and status 0. Your code still cannot use the data.
  • Adding Access-Control-Allow-Origin to the request. These are response headers; sending them from the client only adds a non-safelisted header and triggers a preflight.
  • Browser extensions or disabling web security. They hide the problem on your machine only.
  • Public CORS proxies. They route your users' traffic, and possibly tokens, through a third party.
  • Reflecting any Origin with credentials. Echoing back whatever origin arrives, with Access-Control-Allow-Credentials: true, lets any website read authenticated responses. Always check against an allowlist.

Security checklist

  1. Allowlist exact origins; avoid substring checks (origin.includes('example.com') accepts example.com.evil.net).
  2. Anchor regexes with ^ and $ and escape dots.
  3. Do not allow the literal origin null; sandboxed iframes and file:// pages send it.
  4. Keep CSRF protection for cookie-authenticated, state-changing endpoints. CORS does not stop a form POST from another site.
  5. Send Vary: Origin whenever Access-Control-Allow-Origin is dynamic.
  6. Configure CORS in one layer only: app, gateway or proxy.

If you are using cookie-based sessions with an auth library, the same-site deployment advice above matters more than any header; Better Auth vs Auth.js discusses session cookie setups across subdomains.

Frequently Asked Questions

How do I fix "No 'Access-Control-Allow-Origin' header is present on the requested resource"?

Configure the API server to return Access-Control-Allow-Origin with your front-end's exact origin, handle OPTIONS preflights with a 2xx response, and make sure error responses carry the same headers. Check with curl -i -H 'Origin: ...' that the header actually appears.

Can I fix a CORS error from the front-end?

No. The server must opt in. In development you can avoid cross-origin requests with a dev-server proxy such as Vite's server.proxy, and in production you can serve the app and API from the same origin through a reverse proxy.

Why does my GET request work but POST or PUT fails?

Your GET is a simple request, but a POST with Content-Type: application/json or an Authorization header triggers a preflight OPTIONS request. The server is probably not handling OPTIONS, or auth middleware rejects it with 401.

Can I use Access-Control-Allow-Origin: * with cookies?

No. With credentials, the browser requires the exact origin in Access-Control-Allow-Origin and Access-Control-Allow-Credentials: true. Use an allowlist and echo the matching origin.

Why does CORS work in Postman but not in the browser?

CORS is enforced only by browsers. Postman and curl do not apply the same-origin policy, so they succeed even when the server sends no CORS headers.

Does CORS protect my API from attackers?

No. It controls which websites can read responses in a user's browser. Anyone can still call your API directly, and cross-site form posts still reach it, so you need authentication, authorization and CSRF protection regardless.

Conclusion

Every CORS error comes down to the response headers the browser receives for a specific origin, method and header set. Reproduce the preflight with curl, read the exact console message, and fix it in one layer: the cors package in Express, CORSMiddleware in FastAPI, cors() in Hono, an OPTIONS handler or proxy.ts in Next.js, CorsRegistry plus http.cors() in Spring, or a map-based allowlist in Nginx. Use an explicit allowlist, send Vary: Origin, never pair * with credentials, and use a dev proxy so local development does not need CORS at all.