I opened DevTools, clicked the failed request, and found an OPTIONS call with a 405 next to it. The POST I actually cared about never fired. The console said “blocked by CORS policy”, which tells you nothing about which side broke.
Browsers send that OPTIONS request, the preflight, before any cross-origin call that isn’t “simple”. Send an Authorization header, or a Content-Type: application/json body, or use a method other than GET, HEAD or POST, and the browser asks permission first. If the answer isn’t a clean success with the right headers, it never sends the real request.
Where the 403 and 405 come from #
A Worker doesn’t drop OPTIONS on its own. It runs your code, and the status code comes from whatever your code does with a method it didn’t expect. A 405 almost always means your fetch handler or router only knows about GET and POST and answers everything else with “method not allowed”. Cloudflare’s own CORS example does this on purpose: it passes GET and HEAD through, handles OPTIONS and POST directly, and returns 405 for any other method. Delete the OPTIONS branch and that’s the response you get.
The 403 has a second cause, and it happens before your Worker runs. If the domain sits behind Cloudflare Access, a preflighted request to an Access-protected domain returns 403 whether or not you’re logged in, because browsers never attach cookies to OPTIONS requests, and Cloudflare blocks the preflight. Cloudflare gives you two ways out. You can have it bypass OPTIONS requests to the origin, or configure Access to answer the preflight itself. The bypass setting is under the application’s CORS settings, and turning it on removes all existing CORS settings for that application. Use it only if your Worker enforces CORS, because Cloudflare notes that the bypass should only be used when your origin server enforces CORS itself. One testing tip from the same docs: don’t troubleshoot CORS in an Incognito window, because the Access cookie gets blocked as a third-party cookie on cross-origin requests.
To tell which of the two you’ve got, send the preflight yourself and see who answers:
curl -i -X OPTIONS https://api.example.com/items \
-H 'Origin: https://app.example.com' \
-H 'Access-Control-Request-Method: POST' \
-H 'Access-Control-Request-Headers: content-type,authorization'If the 403 comes back with none of your headers, something in front of the Worker, like Access or a firewall rule, answered it. If the status comes from your code, the fix is in the Worker.
The fix: answer preflights explicitly, tag every response #
A real preflight is an OPTIONS request carrying an Origin header and an Access-Control-Request-Method header, so check for both rather than treating every OPTIONS call as one. Answer it with a 204 and the permission headers. Then run every other response through one helper that attaches the origin header, including 404s, 405s and errors.
const ALLOWED_ORIGINS = new Set([
'https://app.example.com',
'http://localhost:5173',
]);
const PREFLIGHT_HEADERS = {
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-Client-Version',
'Access-Control-Max-Age': '7200',
};
function allowedOrigin(request) {
const origin = request.headers.get('Origin');
return origin && ALLOWED_ORIGINS.has(origin) ? origin : null;
}
function isPreflight(request) {
return (
request.method === 'OPTIONS' &&
request.headers.has('Origin') &&
request.headers.has('Access-Control-Request-Method')
);
}
function handlePreflight(request) {
const origin = allowedOrigin(request);
if (!origin) {
return new Response(null, { status: 403 });
}
return new Response(null, {
status: 204,
headers: {
...PREFLIGHT_HEADERS,
'Access-Control-Allow-Origin': origin,
'Vary': 'Origin',
},
});
}
function withCors(request, response) {
const origin = allowedOrigin(request);
if (!origin) return response;
// Responses from fetch() have read-only headers, so copy before editing.
const out = new Response(response.body, response);
out.headers.set('Access-Control-Allow-Origin', origin);
out.headers.append('Vary', 'Origin');
return out;
}
async function handleRequest(request, env) {
const url = new URL(request.url);
if (url.pathname === '/items' && request.method === 'GET') {
return Response.json({ message: 'Hello from the Worker' });
}
return Response.json({ error: 'Not found' }, { status: 404 });
}
export default {
async fetch(request, env, ctx) {
if (isPreflight(request)) {
return handlePreflight(request);
}
try {
return withCors(request, await handleRequest(request, env));
} catch (err) {
console.error(err);
return withCors(
request,
Response.json({ error: 'Internal error' }, { status: 500 }),
);
}
},
};A few choices in there matter, and each has a reason.
The preflight-only headers stay out of normal responses. Access-Control-Max-Age, Allow-Methods and Allow-Headers only make sense on preflight responses, so the helper doesn’t spray them on every reply.
The Vary: Origin header appears because the allowed origin changes per request. Without it, a cache can hand one site’s Access-Control-Allow-Origin value to a different site. Cloudflare’s own CORS proxy example adds a Vary header so the browser caches the response correctly.
The new Response(response.body, response) copy exists because responses that come back from fetch() inside a Worker have immutable headers, and calling headers.set on one throws. The same copy pattern shows up in Cloudflare’s example.
The Max-Age is 7200 and not 86400 because browsers cap it. Chromium has capped the value at 2 hours since version 76, Firefox at 24 hours, and the default when you send nothing is 5 seconds. Asking for a day gets you two hours in Chrome anyway, so ask for what you’ll actually get.
Pitfalls #
Error responses with no CORS headers. If a handler throws and nothing catches it, Cloudflare serves its own error page, which carries none of your headers. The browser then reports a generic CORS failure and your frontend never sees the real status. That’s why the catch block runs through the same withCors helper. I also log the error and return a generic message to the client. Echoing err.message back leaks internals to anyone who triggers it.
Wildcards and credentials. Access-Control-Allow-Origin: * is fine for a public API, and it works with a bearer token in the Authorization header as long as you aren’t sending cookies. What breaks it is credentialed requests, meaning cookies sent with credentials: 'include'. Wildcard origins are incompatible with credentials, so the response has to name the specific origin. Add Access-Control-Allow-Credentials: 'true' alongside it, to the preflight response as well as the normal ones.
The tempting shortcut is echoing back whatever Origin the request sent. Don’t. With credentials on, that lets any website make authenticated requests to your API and read the responses as the logged-in user. Check the origin against an allowlist, the way allowedOrigin does above. The guidance is the same everywhere: validate the Origin header against an allowlist and return the matching origin, or an error for unrecognized ones.
Custom headers missing from the allow list. Anything your frontend sends beyond the safelisted headers has to appear in Access-Control-Allow-Headers, or the browser rejects the preflight. That includes X-Client-Version and every similar custom header. Authorization has its own rule. The * wildcard only counts as a wildcard for requests without credentials, and Authorization doesn’t accept it at all and always has to be listed by name. If you wrote Access-Control-Allow-Headers: * and your Bearer-token requests still fail, that’s why.
Redirects. A preflight can’t follow a redirect. If your API redirects www to the bare domain, http to https, or adds a trailing slash, the OPTIONS request hits the redirect and fails before your handler sees it. Call the exact final URL.
When a CORS error shows up, the browser tells you almost nothing, and the Network tab and a raw curl tell you the rest. The preflight response is the whole conversation, so read it before you change any code.