What Is CORS? Why Browser API Calls Fail and How to Fix It

CORS, short for Cross-Origin Resource Sharing, is a browser-enforced security policy that prevents JavaScript on one origin (say, https://app.example.com) from reading responses from a different origin (say, https://api.example.com) unless the server on that second origin explicitly says the first one is allowed. It is not a bug, a firewall rule, or a server crash; it is the browser itself refusing to hand your code the response. Apidoke's built-in try-it console sends real HTTP requests directly from your browser, so understanding CORS is essential for anyone testing or documenting live APIs.
- CORS is enforced by the browser, not the server; the server still receives and processes the request, but the browser withholds the response from your JavaScript if the right headers are absent.
- The fix always lives on the server: add
Access-Control-Allow-Origin(and related headers) to your API responses. - Simple GET and POST requests with standard headers fire immediately; requests with custom headers, methods like PUT or DELETE, or JSON bodies trigger a preflight
OPTIONSrequest first. - When you use a browser-based try-it console, your authorization tokens stay in your browser and never pass through any third-party server, which is exactly why browser-side security like CORS matters.
What does "origin" actually mean?
An origin is the combination of three things: protocol, hostname, and port. https://app.example.com and https://api.example.com are different origins because the hostnames differ. http://example.com and https://example.com are also different origins because the protocol differs. https://example.com and https://example.com:8443 are different origins because the port differs. If any one of those three components changes, the browser considers it a cross-origin request and applies CORS rules.
This policy is called the Same-Origin Policy (SOP). It has been a core browser security feature since the late 1990s. MDN's Same-Origin Policy documentation covers the full scope of what it restricts beyond just fetch requests.
What triggers a CORS error?
You write this in a browser tab loaded from https://frontend.example.com:
fetch('https://api.example.com/v1/users', {
method: 'GET',
headers: { 'Authorization': 'Bearer eyJhbGc...' }
})
.then(res => res.json())
.then(data => console.log(data));
The browser sends the request. The server returns a 200 OK with a JSON body. But in the console you see:
Access to fetch at 'https://api.example.com/v1/users' from origin
'https://frontend.example.com' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the
requested resource.
The server responded successfully. The browser suppressed the response from your JavaScript because the response lacked the Access-Control-Allow-Origin header granting permission to https://frontend.example.com.
How does the browser decide what to block?
The browser checks the response headers. At minimum it looks for:
Access-Control-Allow-Origin: https://frontend.example.com
or the wildcard:
Access-Control-Allow-Origin: *
If neither is present, or if the value does not match the requesting origin, the browser blocks the response. The HTTP status code you chose on the server (200, 201, 404, whatever) is irrelevant to this check.
What is a preflight request?
Not every cross-origin request fires straight away. The browser first classifies the request as either "simple" or "preflighted".
Simple requests
A request is simple when all of the following are true: the method is GET, HEAD, or POST; the only headers are the browser-controlled set (like Accept, Content-Type with application/x-www-form-urlencoded, multipart/form-data, or text/plain); and no ReadableStream object is in the body. Simple requests go straight to the server.
Preflighted requests
Everything else triggers a preflight. That includes:
- Any method other than GET, HEAD, or POST (so PUT, PATCH, DELETE, etc.)
- A
Content-Typeofapplication/json - Any custom header, including
Authorization
The browser automatically sends an OPTIONS request to the same URL before your actual request:
OPTIONS /v1/users HTTP/1.1
Host: api.example.com
Origin: https://frontend.example.com
Access-Control-Request-Method: GET
Access-Control-Request-Headers: Authorization
The server must respond to that OPTIONS request with something like:
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://frontend.example.com
Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
Access-Control-Allow-Headers: Authorization, Content-Type
Access-Control-Max-Age: 86400
Access-Control-Max-Age (in seconds) tells the browser how long to cache this preflight result so it does not repeat the round-trip on every request. 86400 is 24 hours. Only after a successful preflight does the browser send your actual GET, POST, or DELETE.
The formal specification for HTTP semantics is RFC 9110, with CORS itself defined in the WHATWG Fetch standard.

The full set of CORS response headers explained
| Header | What it does | Example value |
|---|---|---|
Access-Control-Allow-Origin | Specifies which origin(s) may read the response. Use a specific origin in production, not *, if you need cookies or Authorization headers. | https://app.example.com |
Access-Control-Allow-Methods | Lists the HTTP methods the browser is permitted to use in the actual request. | GET, POST, PUT, DELETE, OPTIONS |
Access-Control-Allow-Headers | Lists the request headers that are allowed. Required whenever the client sends a custom header. | Authorization, Content-Type, X-Request-ID |
Access-Control-Allow-Credentials | Set to true if the browser should expose the response when the request includes credentials (cookies, TLS client certs, or HTTP auth). Cannot be combined with Access-Control-Allow-Origin: *. | true |
Access-Control-Expose-Headers | Whitelists response headers that JavaScript is allowed to read beyond the default safe list. | X-RateLimit-Remaining, X-Request-ID |
Access-Control-Max-Age | How many seconds the preflight response can be cached by the browser. | 86400 |
How to fix a CORS error: step-by-step
- Identify the exact error message. Open DevTools (F12), go to the Network tab, find the failing request, and check the response headers. A missing
Access-Control-Allow-Originis the most common cause. A blocked preflight shows up as a failedOPTIONSrequest with a non-204/200 status or missing headers. - Determine the correct origin to allow. In development this might be
http://localhost:3000. In production it is the exact origin your frontend is served from, including the protocol and any non-standard port. - Add CORS middleware or headers on the server. Do this at the framework or reverse proxy level, not inside each individual route handler. See the server-specific examples below.
- Handle OPTIONS explicitly. Make sure your server returns a 204 (or 200) for
OPTIONSrequests and does not hit authentication middleware that returns a 401 before the CORS headers are written. - Test the preflight separately. Run this from a terminal to confirm the server is responding correctly before you involve the browser:
curl -v -X OPTIONS https://api.example.com/v1/users \
-H "Origin: https://frontend.example.com" \
-H "Access-Control-Request-Method: GET" \
-H "Access-Control-Request-Headers: Authorization"
You should see a response with Access-Control-Allow-Origin and Access-Control-Allow-Headers set, and a status of 204. If you see a 401 or 403 instead, your auth middleware is running before your CORS middleware, which is the number-one production mistake.
Server-side CORS configuration examples
Node.js with Express (cors package)
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors({
origin: 'https://frontend.example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Authorization', 'Content-Type'],
maxAge: 86400
}));
// Your routes here
app.get('/v1/users', (req, res) => {
res.json([{ id: 1, name: 'Alice' }]);
});
Python with FastAPI
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["https://frontend.example.com"],
allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type"],
max_age=86400,
)
@app.get("/v1/users")
def get_users():
return [{"id": 1, "name": "Alice"}]
Nginx reverse proxy
location /v1/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' 'https://frontend.example.com';
add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS';
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type';
add_header 'Access-Control-Max-Age' 86400;
add_header 'Content-Length' 0;
return 204;
}
add_header 'Access-Control-Allow-Origin' 'https://frontend.example.com';
proxy_pass http://backend;
}
CORS and credentials: the wildcard trap
If your frontend sends a request with credentials: 'include' (for cookies or HTTP authentication), you cannot use Access-Control-Allow-Origin: *. The browser will refuse the response with a message saying it cannot use a wildcard when the credentials flag is true. You must specify the exact origin and also set Access-Control-Allow-Credentials: true on the server. This combination is intentional; a wildcard with credentials would let any website silently read cookie-authenticated responses from your API.
Common CORS mistakes and what they look like in the Network tab
| Symptom | Root cause | Fix |
|---|---|---|
| OPTIONS returns 401 | Auth middleware runs before CORS middleware | Move CORS middleware to run first, before any authentication checks |
| CORS works for GET but not POST with JSON | Content-Type: application/json triggers a preflight that is not handled | Explicitly allow Content-Type in Access-Control-Allow-Headers |
| Works in development, fails in production | Dev server proxied requests; production does not | Add CORS headers on the production API, not just the dev proxy |
Access-Control-Allow-Origin: * set but credentials still blocked | Wildcard cannot be used with credentials: 'include' | Use the specific origin and add Access-Control-Allow-Credentials: true |
| Custom response header unreadable in JavaScript | Header not in Access-Control-Expose-Headers | Add the header name to Access-Control-Expose-Headers in the response |
| Preflight cached but headers changed on server | Browser cached the old preflight result | Set a shorter Access-Control-Max-Age during development, or hard-reload with DevTools cache disabled |
CORS in the context of API documentation and try-it consoles
When you use a try-it console built into API docs, your browser sends real HTTP requests directly to whatever base URL is specified in the documentation. This is exactly the same CORS context as your production frontend code. If the API you are documenting does not send back Access-Control-Allow-Origin, the console will show a CORS error rather than a response body, even though the API itself is working perfectly.
Apidoke's try-it console works this way by design: requests go from your browser straight to the target API. Your authorization tokens and credentials never pass through Apidoke's servers. That is a privacy benefit, but it also means your API must have CORS configured correctly for the console to show real live responses. See how try-it consoles work in interactive API docs for a full breakdown of what happens under the hood.
When you are documenting a REST API step by step, noting which endpoints require CORS configuration is worth including in your API docs, especially if you serve a mix of browser clients and server-to-server integrations. Server-to-server calls are never subject to CORS because the Same-Origin Policy only applies inside browsers.

CORS versus other access-control mechanisms
CORS is often confused with authentication and authorization, but they are completely separate layers. A 401 Unauthorized means the server received the request but rejected it because valid credentials were missing. A 403 Forbidden means the server received the request, understood the credentials, but the user lacks permission for that resource. CORS is enforced by the browser before it shows you either of those responses, and a CORS block does not necessarily mean the API is broken or secured; it may simply mean the API was designed only for server-to-server use and was never configured for browser clients.
When CORS does not apply
Four situations bypass CORS entirely:
- Server-to-server calls (Node.js calling another service, Python scripts, cURL from a CI pipeline). No browser, no Same-Origin Policy.
- Requests to the same origin.
https://example.com/apicalled from a page athttps://example.com/appis same-origin. - Browser extensions that have been granted broad host permissions, though extension-specific rules apply.
- Specific browser flags used in automated testing (like
--disable-web-securityin Chromium), which you should never use in production or for real CORS debugging.
Try it live: open the JSONPlaceholder demo on Apidoke and send real GET, POST, PUT, PATCH and DELETE requests against a free fake REST API from your browser. Nothing passes through Apidoke; the request goes straight from your browser to the API.
Frequently asked questions
Why does my API work fine in Postman but fail in the browser?
Postman is not a browser and does not enforce the Same-Origin Policy, so it never applies CORS rules. Your API may be responding correctly in both cases; the browser is simply refusing to pass the response body to your JavaScript because the server did not include Access-Control-Allow-Origin. The fix is always on the server side, not in the client.
Is it safe to use Access-Control-Allow-Origin: *?
For public, read-only APIs that require no authentication or cookies, a wildcard is fine and is common practice. For any API that uses cookies, session tokens, or the Authorization header, you must specify the exact origin instead of * and add Access-Control-Allow-Credentials: true. Using a wildcard with credentials would let any website silently make authenticated requests on behalf of your users.
Can I fix CORS from the frontend without touching the server?
Not directly. The browser enforces CORS based on what the server returns. The only frontend workaround is routing your requests through a same-origin proxy (a backend endpoint on your own domain that forwards the call to the external API), which shifts the cross-origin call from the browser to your server where CORS does not apply.
Why is the preflight returning 401 even though my API key is correct?
The OPTIONS preflight does not carry your API key or Authorization header by design; it is only a permission check. Your server's authentication middleware is probably running before CORS middleware and rejecting the preflight because it has no credentials. Move CORS handling to run before authentication so the OPTIONS request gets a 204 with the correct headers without hitting auth checks.
How do I allow multiple specific origins without using a wildcard?
The Access-Control-Allow-Origin header only accepts a single value or *. The standard pattern is to read the Origin header from the incoming request, check it against an allowlist in your server code, and then echo it back in Access-Control-Allow-Origin if it matches. This keeps the response specific to the requesting origin while supporting multiple approved domains.
Ready to test your API endpoints live from interactive docs? Sign in to Apidoke to publish your first API Blueprint document with a built-in try-it console and confirm your CORS setup works exactly as documented.
Technically reviewed by the Apidoke engineering team.
Related reading: PUT vs PATCH vs POST: Which HTTP Method Should Your API Use?