On this page3 sections
Every fullstack developer has pasted a CORS error into a search bar at 11 PM. The fix is usually two headers - the pain is not knowing which two.
The mental model
CORS is the server giving the browser permission to show a cross-origin response to JavaScript. The request usually reaches your server fine. The browser then checks the response headers and, absent permission, hides it from your code.
The three failure modes
- Simple request, missing header. Response needs
Access-Control-Allow-Origin: https://app.example.com(or*if no credentials). - Preflight. Any request with
Authorization,Content-Type: application/json, or non-GET/POST triggers anOPTIONSfirst. Your route/middleware must answer it withAllow-Origin,Allow-Methods,Allow-Headers- and answer fast, without auth. - Credentials.
fetch(..., { credentials: 'include' })requiresAccess-Control-Allow-Credentials: trueand a specific origin.*is forbidden by spec here - this combination is 80% of the mysterious cases.
// Hono
app.use('*', cors({
origin: ['https://app.example.com', 'http://localhost:5173'],
credentials: true,
}))Debug ritual
DevTools > Network > the failing request. Is there an OPTIONS above it? What status? Which Access-Control-* headers came back? Answer those three questions and you will never paste a CORS error into a search bar again. At 11 PM, anyway.