Learn the concept
CORS
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks cross-origin requests unless the server explicitly allows them via HTTP headers like Access-Control-Allow-Origin.
What is CORS?
What Triggers CORS?
fetch(), XMLHttpRequest, Web Fonts, WebGL texturesSimple vs Preflighted Requests:
Simple Requests (no preflight):
text/plain, multipart/form-data, application/x-www-form-urlencodedPreflighted Requests (OPTIONS sent first):
application/jsonKey CORS Headers:
Access-Control-Allow-Origin: Allowed origin(s) or *Access-Control-Allow-Methods: Allowed HTTP methodsAccess-Control-Allow-Headers: Allowed request headersAccess-Control-Allow-Credentials: Allow cookies/authAccess-Control-Max-Age: Preflight cache duration// Frontend code (https://myapp.com)
// This triggers CORS error if server doesn't allow it
fetch('https://api.other-domain.com/data')
.then(res => res.json())
.catch(err => {
// "Access to fetch at 'https://api.other-domain.com/data'
// from origin 'https://myapp.com' has been blocked by CORS policy"
console.error('CORS error:', err);
});
// Preflight triggered by JSON content-type
fetch('https://api.other-domain.com/data', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // Triggers preflight!
},
body: JSON.stringify({ name: 'test' })
});
// Preflight triggered by custom header
fetch('https://api.other-domain.com/data', {
headers: {
'Authorization': 'Bearer token', // Triggers preflight!
'X-Custom-Header': 'value' // Also triggers preflight!
}
});Building a BFF (Backend for Frontend) proxy handling CORS, authentication, and rate-limiting for APIs like Stripe or OpenAI that require server-side calls
Configuring CORS headers on CDN-hosted fonts, images, and API responses with proper Vary header usage for correct caching
Centralized API gateway handling preflight caching, credential forwarding, and per-route origin whitelisting across services
Build a local dev proxy that logs all CORS headers, visualizes preflight request/response pairs, and highlights misconfigurations
Build Next.js App Router route handlers proxying to multiple backends with per-service CORS policies and JWT validation
Requires server-side API calls for sensitive operations; documentation recommends the BFF proxy pattern
Provides edge-based CORS handling and reverse proxy capabilities for cross-origin requests