CORS Error Troubleshooting Guide: Fix Preflight, Headers, and Credentialed Requests
CORSAPI debuggingbrowser DevToolsHTTP headersweb security

CORS Error Troubleshooting Guide: Fix Preflight, Headers, and Credentialed Requests

WWebbclass Editorial Team
2026-12-06
8 min read

Use DevTools and cURL to diagnose CORS errors, preflight failures, redirects, headers, and credentialed API requests safely.

A CORS error means the browser rejected a cross-origin request under its security rules—not necessarily that your API is down. This guide gives you a repeatable workflow for inspecting the origin, preflight request, response headers, redirects, and credentials so you can fix the configuration without weakening access controls.

Overview

Cross-Origin Resource Sharing, or CORS, controls whether browser JavaScript may read a response from a different origin. An origin is the combination of scheme, host, and port. For example, https://app.example.com and https://api.example.com have different origins even though they share a parent domain. Likewise, http://localhost:3000 and http://localhost:8080 are different origins.

The browser sends an Origin request header and expects the API to return compatible Access-Control-Allow-* response headers. CORS is enforced by browsers; command-line clients such as cURL do not enforce it. Therefore, a successful cURL request proves that the server can respond, but it does not prove that browser CORS checks will pass.

Start with this diagnostic sequence:

  1. Copy the exact frontend origin from the browser address bar.
  2. Open DevTools and inspect the failed request in the Network panel.
  3. Check whether the browser sent an OPTIONS preflight request.
  4. Compare the request method and headers with the API's allowed methods and headers.
  5. Inspect redirects, authentication settings, and the final response headers.
  6. Reproduce the request with cURL while explicitly supplying an Origin header.

For broader API investigation, pair browser DevTools with a dedicated client or command-line workflow. The API debugging tools comparison explains where cURL, HTTPie, Postman, Insomnia, and DevTools fit.

Checklist by scenario

Scenario 1: The request fails before the main call

Look for an OPTIONS request immediately before the failed request. This is commonly a CORS preflight. Browsers may preflight a request when it uses a method such as PUT, PATCH, or DELETE, or when it includes non-simple headers such as Authorization or a custom header.

A useful preflight request resembles:

OPTIONS /v1/profile HTTP/1.1
Host: api.example.com
Origin: https://app.example.com
Access-Control-Request-Method: PATCH
Access-Control-Request-Headers: authorization, content-type

The response must come from the API or a correctly configured proxy and should include compatible values, for example:

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

Check that the allowed method includes the requested method and that every requested header is permitted. Header-name comparison is generally case-insensitive, but spelling, punctuation, and proxy configuration still matter. Ensure the OPTIONS request is not redirected, rejected by authentication middleware, or handled only by application code that never runs for this method.

Scenario 2: The simple request reaches the API but the browser blocks the response

Some requests do not require a preflight. Even then, the browser expects an Access-Control-Allow-Origin response header before JavaScript can read the response. Confirm that the value exactly matches the requesting origin, including scheme and port. A trailing slash is not part of an origin, but an accidental difference such as http versus https or port 3000 versus 3001 is significant.

If a server supports several trusted frontend origins, it should select the matching origin from an allowlist and return that value. When the response varies by origin, include Vary: Origin so an intermediary does not reuse a response generated for a different origin.

Scenario 3: The error mentions credentials

Credentialed requests include cookies or other browser-managed credentials. A frontend request might use:

fetch('https://api.example.com/session', {
  credentials: 'include'
});

The server must return Access-Control-Allow-Credentials: true and a specific allowed origin. Do not combine credentials with Access-Control-Allow-Origin: *; use an explicit origin instead. Also inspect cookie attributes, especially the cookie's domain, Secure requirement, and SameSite behavior. CORS headers cannot make a cookie eligible to be sent if the cookie itself is not eligible.

Scenario 4: The API redirects

Inspect the response chain for redirects caused by a missing slash, HTTP-to-HTTPS enforcement, login middleware, or a proxy route. A redirect can change the request's destination and may fail CORS or preflight handling. Prefer calling the final HTTPS API URL directly and configure the API or proxy to handle OPTIONS without redirecting it.

Scenario 5: The configuration works locally but not after deployment

Compare the exact origins in development, staging, and production. A configuration that allows http://localhost:3000 does not automatically allow a deployed frontend. Check environment variables, reverse-proxy rules, CDN caching, TLS termination, and whether the response headers are added consistently for successful, error, and OPTIONS responses.

Reference table: error to likely cause

Browser symptomLikely causeFirst check
No Access-Control-Allow-OriginAPI or proxy does not add CORS headersInspect the final response and server layer that generated it
Preflight has no successful responseOPTIONS is blocked, redirected, or unhandledInspect the OPTIONS status and response headers
Method is not allowedRequested method is absent from Access-Control-Allow-MethodsCompare Access-Control-Request-Method with the response
Request header is not allowedRequested header is absent from Access-Control-Allow-HeadersCompare the preflight header list with the response
Credential errorWildcard origin, missing credential permission, or cookie rulesCheck credentials mode, origin value, and cookie attributes
Works in cURL but not the browsercURL did not enforce browser CORS rulesRepeat cURL with the exact Origin and preflight headers

Configuration templates

Use these as patterns, then adapt them to the application and deployment layer. Keep the allowlist explicit rather than accepting arbitrary origins.

Express

import cors from 'cors';

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

app.use(cors({
  origin(origin, callback) {
    if (!origin || allowedOrigins.has(origin)) {
      return callback(null, true);
    }
    return callback(new Error('Origin not allowed by CORS'));
  },
  credentials: true,
  methods: ['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization']
}));

The exact middleware order matters. Install CORS handling before routes that may reject or terminate the request, and verify that authentication middleware does not require a user before answering a preflight.

Next.js

For API responses handled by Next.js, add headers at the route or middleware layer used by that endpoint. A route handler can return headers explicitly:

const allowedOrigin = 'https://app.example.com';

export async function OPTIONS() {
  return new Response(null, {
    status: 204,
    headers: {
      'Access-Control-Allow-Origin': allowedOrigin,
      'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Allow-Credentials': 'true',
      'Vary': 'Origin'
    }
  });
}

For a larger application, centralize origin selection in middleware or a shared response helper so that route handlers do not drift apart. If Next.js is only the frontend and the API is hosted elsewhere, configure CORS on the API or reverse proxy; a frontend rewrite can change the browser-visible request path, but it does not replace a deliberate server-side access policy.

Nginx

location /api/ {
    if ($request_method = OPTIONS) {
        add_header Access-Control-Allow-Origin "https://app.example.com" always;
        add_header Access-Control-Allow-Methods "GET, POST, PATCH, DELETE, OPTIONS" always;
        add_header Access-Control-Allow-Headers "Authorization, Content-Type" always;
        add_header Access-Control-Allow-Credentials "true" always;
        add_header Content-Length 0;
        return 204;
    }

    add_header Access-Control-Allow-Origin "https://app.example.com" always;
    add_header Access-Control-Allow-Credentials "true" always;
    add_header Vary "Origin" always;
    proxy_pass http://api_upstream;
}

Test proxy configuration carefully before applying it broadly. In a multi-origin setup, use a controlled mapping rather than reflecting any value supplied by the client.

What to double-check

Use cURL to separate server reachability from browser policy. A preflight-style test can be written as:

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

Then test the actual request with the same origin:

curl -i 'https://api.example.com/v1/profile' \
  -H 'Origin: https://app.example.com' \
  -H 'Authorization: Bearer example-token'

Check all of the following:

  • The response comes from the intended API, not a login page, CDN error, or redirect.
  • Access-Control-Allow-Origin matches the actual origin.
  • Preflight responses include the requested method and headers.
  • Credentialed responses use a specific origin and include the credential permission when needed.
  • CORS headers appear on error responses where the browser must still receive diagnostic information.
  • Each proxy or cache layer preserves the headers and varies cached responses by origin when necessary.
  • The API's authentication policy is separate from its CORS policy; allowing an origin does not authenticate a user.

Common mistakes

  • Adding CORS headers only in the frontend: The server that receives the browser request must provide the relevant response headers.
  • Using a wildcard while sending cookies: Replace the wildcard with a controlled origin and review cookie settings.
  • Allowing every requested origin: Reflecting the request's Origin without validation can grant access to unintended sites.
  • Testing only the main request: A successful GET does not prove that a credentialed PATCH with an authorization header will pass preflight.
  • Ignoring redirects: Fix the URL or proxy route so the browser reaches the intended endpoint directly.
  • Changing application code when the proxy is responsible: Inspect which layer adds, removes, or overwrites the headers.
  • Disabling browser security: Local browser workarounds hide the configuration problem and should not be treated as a deployment fix.

When an API contract is changing, document the permitted origins, methods, headers, and authentication mode alongside the endpoint. An OpenAPI workflow can help keep endpoint behavior and generated client expectations aligned; see the OpenAPI workflow guide for a related process.

When to revisit

Return to this checklist whenever a frontend or API changes host, scheme, port, authentication method, request method, or custom headers. Recheck it after moving traffic behind a reverse proxy, CDN, serverless platform, or new framework middleware. It is also worth reviewing before a staging or production release, after changing cookie settings, and whenever an application adds a new browser client.

For a practical release check, test one simple request, one preflighted request, and one credentialed request from each supported frontend origin. Record the expected response headers and compare them with DevTools and cURL output. Confirm that disallowed origins fail, while approved origins receive only the access needed by the API. This small test becomes especially valuable when workflows or tools change, because it exposes configuration drift before users encounter a browser-only failure.

Related Topics

#CORS#API debugging#browser DevTools#HTTP headers#web security
W

Webbclass Editorial Team

Technical Editor

Senior editor and content strategist. Writing about technology, design, and the future of digital media. Follow along for deep dives into the industry's moving parts.