CORS
How Cross-Origin Resource Sharing works, preflight requests, and fixing CORS errors
Skills taught: api.cors-concept, api.preflight-request, api.cors-headers, api.cors-fix
Cross-Origin Resource Sharing
// ── What triggers a CORS error ──
// Frontend at http://localhost:3000 fetches:
fetch('https://api.example.com/data');
// Browser checks: different origin? Yes → check CORS headers
// If the response doesn't include Access-Control-Allow-Origin → BLOCKED
// ── Preflight request (browser does this automatically) ──
// Before sending POST with JSON body, browser sends OPTIONS:
//
// OPTIONS /api/users HTTP/1.1
// Origin: http://localhost:3000
// Access-Control-Request-Method: POST
// Access-Control-Request-Headers: content-type, authorization
//
// Server must respond:
// HTTP/1.1 204 No Content
// Access-Control-Allow-Origin: http://localhost:3000
// Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE
// Access-Control-Allow-Headers: Content-Type, Authorization
// Access-Control-Max-Age: 86400
//
// Then the browser sends the actual POST request
// ── Server-side fix (Express) ──
import cors from 'cors';
app.use(cors({
origin: ['https://app.example.com', 'http://localhost:3000'],
methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true, // only if sending cookies — and origin cannot be *
maxAge: 86400, // cache preflight for 24h
}));
// ── Development workaround: Vite proxy ──
// vite.config.ts — avoids CORS during development:
export default {
server: {
proxy: {
'/api': {
target: 'https://api.example.com',
changeOrigin: true,
rewrite: (path) => path.replace(/^\/api/, ''),
},
},
},
};
// Now fetch('/api/users') → proxied to https://api.example.com/users
// Same origin from browser perspective — no CORS check
// ── Fetch with credentials ──
fetch('https://api.example.com/me', {
credentials: 'include', // send cookies + require CORS credentials header
});
Tip: CORS errors are a SERVER configuration problem, not a frontend problem. You cannot fix a CORS error by changing your fetch() call. The server needs to add Access-Control-Allow-Origin headers. During development, use your framework's dev proxy (Vite, webpack-dev-server, Next.js rewrites) to avoid CORS entirely.
Frequently Asked Questions
Why does the CORS error say the request was blocked even though I can see it in the Network tab?
CORS blocking is on the RESPONSE, not the request. The request reaches the server — you can see it in the Network tab, and the server processes it. The browser then checks the response headers. If Access-Control-Allow-Origin is missing or doesn't match, the browser blocks JavaScript from reading the response. This is why `mode: 'no-cors'` requests still reach the server but return no data to JavaScript — they're allowed to send but not to read the response.