CORS Explained: Fix Cross-Origin Errors in Browsers, APIs, and Local Development
corsweb-securityapisjavascriptdebugging

CORS Explained: Fix Cross-Origin Errors in Browsers, APIs, and Local Development

TThe Code Website Editorial Team
2026-12-06
7 min read

Diagnose CORS errors with a practical checklist covering preflight requests, credentials, localhost, proxies, and safe API configuration.

Cross-Origin Resource Sharing (CORS) errors happen when a browser prevents JavaScript on one origin from reading a response from another. This guide gives you a reusable diagnostic checklist, explains simple requests and preflight requests, and shows safe configuration patterns for JavaScript and Python APIs without weakening server security.

Overview

An origin is the combination of a request's scheme, host, and port. For example, https://app.example.com and https://api.example.com have different origins because their hosts differ. Likewise, http://localhost:3000 and http://localhost:8000 are different origins even though they use the same host.

CORS is a browser-controlled permission system. Your frontend may send a request to another origin, but the browser checks whether the API response includes headers that permit the frontend origin to read it. A CORS error is therefore usually not an authentication error, a DNS error, or a server-side application error. It means the browser could not confirm that the cross-origin response was allowed.

The API must return the relevant CORS headers. Adding a header to the frontend request does not grant permission. In particular, do not try to fix CORS by adding Access-Control-Allow-Origin to a Fetch request. That header belongs in the server response.

Before changing configuration, record these values:

  • The exact frontend origin, including scheme and port.
  • The exact API URL and HTTP method.
  • Request headers such as Authorization or Content-Type.
  • Whether cookies or other credentials are included.
  • Whether the browser sent an OPTIONS preflight request.

Checklist by scenario

1. A simple cross-origin request

A request may avoid a preflight when it uses a permitted method and a limited set of request headers and content types. A typical read request might look like this:

fetch('https://api.example.com/products')
  .then(response => {
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    return response.json();
  });

The API response should include a matching permission, for example:

Access-Control-Allow-Origin: https://app.example.com

Check the browser's Network panel rather than relying only on the console message. Confirm that the response contains the header and that its value exactly matches the requesting origin. A different port, trailing configuration assumption, or use of http instead of https can matter.

2. A request that triggers preflight

Browsers send a CORS preflight when the planned request needs server approval before the actual request is made. This commonly occurs with methods such as PUT, PATCH, or DELETE, or with headers such as Authorization. The preflight uses OPTIONS and asks which origin, methods, and headers are allowed.

OPTIONS /users/42 HTTP/1.1
Origin: https://app.example.com
Access-Control-Request-Method: PATCH
Access-Control-Request-Headers: authorization, content-type

The server must answer the preflight successfully and include compatible headers, such as:

Access-Control-Allow-Origin: https://app.example.com
Access-Control-Allow-Methods: GET, POST, PATCH, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type

Use the Network panel to determine whether the preflight returns a redirect, a 4xx or 5xx response, or no CORS headers. A route that works in an API client may still fail in a browser because API clients do not enforce browser CORS rules in the same way.

3. Requests that include credentials

Cookies and other browser-managed credentials require deliberate configuration on both sides. The frontend must opt in:

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

The server must return Access-Control-Allow-Credentials: true and a specific allowed origin. A wildcard origin, *, is not a suitable companion to credentialed CORS. If cookies are involved, also inspect cookie attributes and the server's session settings; a correct CORS header alone does not guarantee that a browser will send or accept a cookie.

4. Local development with CORS localhost

Local development often uses separate frontend and backend ports, so the origins differ even when both applications run on localhost. Configure the API to allow the actual development origin, such as http://localhost:3000, rather than assuming that all localhost ports are interchangeable.

Keep development and production allowlists separate. A temporary local exception should not become a broad production rule. If the frontend and API are served through the same development proxy, the browser may see a same-origin request, but the proxy still needs correct upstream routing and error handling.

5. Using a development or edge proxy

A proxy can make the browser request the frontend's own origin while the proxy contacts the API server. This is useful when you control the development setup or a trusted gateway, but it is not a client-side CORS bypass. The proxy must be configured and deployed responsibly, and the API should still enforce authentication and authorization.

Use a proxy to simplify routing, not to expose private APIs or conceal a missing access-control policy. For a production integration, prefer an explicit server-to-server design or a narrowly configured CORS policy that matches the application's real origins.

ScenarioWhat to inspectTypical remedy
Simple GETResponse origin headerReturn the exact allowed frontend origin
Preflight requestOPTIONS status, methods, and headersHandle OPTIONS and allow the requested method and headers
CredentialsFetch credentials mode and cookie behaviorUse a specific origin and allow credentials deliberately
LocalhostScheme and portAllow the precise development origin
ProxyBrowser URL and upstream routeConfigure a trusted proxy without weakening API controls

Server configuration examples

Express

With Express, configure CORS middleware before routes that need it. Prefer an explicit allowlist when the API serves a known set of applications:

import cors from 'cors';

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

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

Adjust the methods, headers, and credential setting to the application rather than copying a broad configuration. Also verify that an upstream reverse proxy is not removing headers or mishandling OPTIONS requests.

Flask

A Flask application can apply a focused policy to selected routes:

from flask_cors import CORS

CORS(
    app,
    resources={r'/api/*': {
        'origins': [
            'https://app.example.com',
            'http://localhost:3000'
        ]
    }},
    supports_credentials=True
)

Confirm that the extension's configuration matches the routes, methods, and authentication model in use. If you use cookies, test the complete request flow, including cookie attributes and preflight behavior.

FastAPI

from fastapi.middleware.cors import CORSMiddleware

app.add_middleware(
    CORSMiddleware,
    allow_origins=[
        'https://app.example.com',
        'http://localhost:3000'
    ],
    allow_credentials=True,
    allow_methods=['GET', 'POST', 'PATCH', 'DELETE', 'OPTIONS'],
    allow_headers=['Authorization', 'Content-Type']
)

Middleware is only one part of the request path. Test through the same load balancer, gateway, or reverse proxy used by the browser, because an intermediate layer can change status codes, redirects, or headers.

What to double-check

  1. Exact origin matching: Compare the browser's Origin value with the server allowlist. Scheme, host, and port all count.
  2. Preflight handling: Make sure OPTIONS reaches CORS middleware and is not blocked by authentication, routing, or a web server rule.
  3. Requested headers: Every non-simple request header requested by the browser must be allowed by Access-Control-Allow-Headers.
  4. Requested methods: The actual method must be listed in Access-Control-Allow-Methods when preflight applies.
  5. Credentials: Do not combine credentialed requests with a wildcard origin. Check cookies separately from authorization headers.
  6. Redirects: Inspect redirects on both the preflight and actual request. A redirect can prevent the expected CORS exchange from completing.
  7. Error responses: CORS headers may also be needed on useful error responses so the frontend can read the status and response body.
  8. Caching: If responses vary by origin, configure the relevant cache behavior so a response for one origin is not incorrectly reused for another.

For broader API debugging, compare the browser request with the server logs and review the related HTTP status codes and API errors reference. If the request uses Fetch, the JavaScript Fetch API guide can help separate network failures from application responses.

Common mistakes

  • Adding CORS headers in JavaScript: Request headers do not grant browser permission. Configure the API response.
  • Allowing every origin by default: A broad rule can make unintended integrations possible, especially when credentials or sensitive responses are involved.
  • Testing only with curl or an API client: These tools are useful for inspecting responses, but they do not reproduce every browser CORS decision.
  • Ignoring the preflight: Fixing the actual POST route will not help if the preceding OPTIONS request fails.
  • Assuming authentication fixes CORS: A valid JWT or session does not replace a valid cross-origin policy. For token details, see the JWT authentication guide.
  • Using a browser extension as a permanent fix: An extension may change local browser behavior, but it does not fix the deployed API.
  • Confusing URL problems with CORS: Malformed query strings, encoding mistakes, and incorrect endpoints can produce separate failures. Use the URL encoding and query strings guide when parameters are involved.

When to revisit

Recheck your CORS configuration whenever the frontend or API moves to a new domain, protocol, or port; when a deployment introduces a gateway or CDN; when authentication changes from headers to cookies; or when a new HTTP method or request header is added. It is also worth revisiting before a seasonal planning cycle or any release that changes development tooling, proxy rules, or framework middleware.

Keep a small CORS test checklist with the application: one allowed origin, one rejected origin, a simple request, a preflighted request, a credentialed request if applicable, and an error response. Run it through the real deployment path, not only against a local process. When a failure returns, begin with the browser Network panel, inspect the preflight, compare the exact origin, and then check server and proxy logs. This order usually identifies whether the problem is policy, routing, authentication, or the API itself before you change security settings.

Related Topics

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

The Code Website Editorial Team

Senior SEO 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.