CORS Error Troubleshooting Guide: Diagnose Preflight, Headers, and Credential Failures
corsapisjavascriptweb-securitydebugginghttp

CORS Error Troubleshooting Guide: Diagnose Preflight, Headers, and Credential Failures

TThe Code Editorial Team
2026-11-17
7 min read

Diagnose CORS errors with a practical checklist for origins, preflight requests, headers, credentials, redirects, and reverse proxies.

CORS errors are usually configuration mismatches, not mysterious browser failures. This troubleshooting guide gives you a reusable workflow for identifying the requesting origin, inspecting preflight and actual requests, correcting response headers, and separating CORS problems from authentication, redirects, proxy, and server errors.

Overview

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

The browser sends the request, but it may prevent frontend code from reading the response unless the API explicitly grants permission with response headers. CORS is therefore a browser enforcement mechanism. A request that works in a server-side script, API client, or curl can still fail in a browser because those clients do not enforce browser CORS rules in the same way.

Use this simplified request flow when diagnosing a browser-blocked API request:

  1. Record the frontend origin, API URL, method, headers, and credential mode.
  2. Check whether the browser sent an OPTIONS preflight request.
  3. Inspect the preflight response status and CORS headers.
  4. Inspect the actual request and its response headers separately.
  5. Check redirects, reverse proxies, cookies, and server logs if the headers look correct.

For a complete view of request method, status, headers, timing, and redirects, use the browser's Network panel. The related Browser DevTools Network Panel Guide can help you trace the request rather than relying only on the short console error.

Checklist by scenario

Scenario 1: A simple request is blocked

A cross-origin request may avoid preflight when it meets the browser's conditions for a simple request. Regardless, the API still needs to return an appropriate Access-Control-Allow-Origin response header for frontend JavaScript to read the result.

  • Check the exact Origin request header, including scheme, hostname, and port.
  • Compare it with the value returned in Access-Control-Allow-Origin.
  • Do not add a trailing slash to the allowed origin unless it is actually part of the origin value; origins normally look like https://app.example.test, not https://app.example.test/.
  • Confirm that the header is present on successful responses and relevant error responses, not only on one route.

A common fix is to allow a known origin at the API layer. For Express, a narrowly scoped configuration can look like this:

import cors from "cors";

const allowedOrigins = new Set([
  "http://localhost:5173",
  "https://app.example.test"
]);

app.use(cors({
  origin(origin, callback) {
    if (!origin || allowedOrigins.has(origin)) {
      return callback(null, true);
    }
    return callback(new Error("Origin not allowed"));
  }
}));

The exact middleware API varies by framework and version, so verify that the middleware runs before the routes it needs to cover.

Scenario 2: The browser sends a CORS preflight request

Browsers commonly send an OPTIONS request before the actual request when the request uses a method such as PUT, PATCH, or DELETE, or includes headers outside the simple-request set. The preflight asks whether the server permits the proposed origin, method, and request headers.

Inspect these request headers:

  • Origin
  • Access-Control-Request-Method
  • Access-Control-Request-Headers, when applicable

The preflight response should address the request explicitly. Check for:

  • Access-Control-Allow-Origin
  • Access-Control-Allow-Methods containing the requested method
  • Access-Control-Allow-Headers containing requested non-simple headers such as Authorization or Content-Type, when required
  • A successful status that your server, framework, and proxy handle consistently

Do not assume that a route's normal POST handler also handles OPTIONS. The server or middleware must respond to the preflight before authentication, routing, or business logic rejects it unnecessarily.

Scenario 3: Credentials or cookies fail

Credentialed requests include cookies or other browser-managed credentials. In Fetch, the frontend must opt into credentials when needed:

fetch("https://api.example.test/account", {
  method: "GET",
  credentials: "include"
});

The server must then return a specific allowed origin rather than a wildcard. A credentialed CORS response cannot use Access-Control-Allow-Origin: * as a substitute for the requesting origin. The server also needs Access-Control-Allow-Credentials: true.

If the headers appear correct but the cookie is still absent, investigate cookie attributes and browser privacy behavior separately. Check the cookie's Domain, Path, Secure, and SameSite settings, and confirm that the frontend and API deployment model matches those settings.

Scenario 4: The API is behind Nginx or Apache

A reverse proxy may terminate TLS, answer OPTIONS, redirect HTTP to HTTPS, or remove headers. First identify which layer produced the response in the Network panel and server logs.

A simplified Nginx pattern might look like this, but should be adapted to the routes and origins in your deployment:

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

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

Proxy directives differ across environments. Treat this as a configuration shape, not a universal drop-in. In particular, make sure the same origin policy is applied consistently to normal responses, errors, and preflight responses.

Scenario 5: The console mentions a redirect

Redirects can complicate preflight handling. Check whether the API URL redirects from HTTP to HTTPS, from one hostname to another, or from a bare host to a canonical host. Update the frontend to call the final HTTPS URL directly when possible, then verify CORS headers on the final response. Also check whether the redirect response itself is handled by the browser as part of a preflight flow.

What to double-check

Compare the exact origin

Use the origin shown in the request, not the page title or a remembered environment name. Differences in protocol, port, subdomain, or a local development host are enough to change the origin. Keep separate allowlists for local, staging, and production where practical.

Separate preflight headers from actual-response headers

A successful preflight does not prove that the actual response is readable. Inspect both entries in the Network panel. The actual response also needs a suitable Access-Control-Allow-Origin header. If the API returns a different origin dynamically, add Vary: Origin so caches do not serve one origin's response headers to another origin.

Check custom headers and authorization

Adding an Authorization header commonly triggers preflight. Confirm that the server permits it and that the API is not expecting a different authentication mechanism. If you are debugging token-based authentication, inspect the request headers without exposing live tokens in screenshots or logs. The site's curl API Request Examples guide is useful for comparing browser and non-browser requests.

Distinguish CORS from HTTP failures

A 401, 403, 404, or 500 can be the underlying server problem while the browser reports a CORS symptom because the error response lacks CORS headers. Check the response status and server logs before changing security policy. For status-code diagnosis, see the HTTP Status Codes Troubleshooting Guide.

Test outside the browser, but interpret the result correctly

Use curl to verify routing, TLS, authentication, and response headers:

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

This can reveal what the server returns, but a successful curl response does not bypass browser enforcement. Reproduce the request in the browser afterward.

Common mistakes

  • Using * as a permanent fix: A wildcard may be unsuitable for private APIs and cannot replace a specific origin for credentialed requests.
  • Allowing every request header and method: Broad permissions make diagnosis easy but can exceed the API's actual needs. Prefer the smallest useful set.
  • Configuring only the application server: Nginx, Apache, a gateway, CDN, or platform router may answer the request first or overwrite headers.
  • Handling only successful responses: Add consistent CORS behavior to relevant error paths so the browser does not hide useful status information.
  • Testing with a disabled browser security mode: This can conceal the real deployment problem and should not be treated as validation.
  • Sending cookies without reviewing cookie policy: CORS permission and cookie delivery are separate checks. Both must succeed.
  • Changing frontend code before reading the request: Start with the Network panel. Confirm the URL, method, headers, status, redirect chain, and response headers.

When to revisit

Revisit this checklist whenever a frontend moves between local, staging, and production environments; a new API route or HTTP method is added; authentication cookies stop working; a custom header is introduced; or a deployment changes the proxy, gateway, CDN, hostname, or TLS configuration.

It is also worth reviewing CORS configuration before a seasonal planning or release cycle, especially when teams are consolidating domains or changing frontend frameworks. Browser error wording, Fetch behavior, middleware defaults, and reverse-proxy configuration can change as tools and workflows evolve. Perform a compatibility review at least twice a year, and after major framework or infrastructure upgrades.

Before closing an incident, record the working origin, allowed methods, required headers, credential behavior, and the component responsible for the response. Then verify the fix in the browser with a real preflight and actual request. If the failure began after a code or dependency change, preserve the known-good configuration and use a controlled rollback or comparison; the Git Undo and Recovery Guide provides a safe reference for that part of the investigation.

Related Topics

#cors#apis#javascript#web-security#debugging#http
T

The Code Editorial Team

Developer Resources 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.