Back to 20 Concepts
sessions-cookies • Intermediate
Cross-Origin Resource Sharing (CORS): Preflight OPTIONS & Credentials
CORS is a browser security mechanism that restricts cross-origin HTTP requests. Requests with custom headers or non-simple methods trigger an HTTP OPTIONS Preflight request to verify allowed origins, methods, and credentials.
Intuitive Mental Model
The Embassy Passport Verification: Before a foreign diplomat (cross-origin script) enters the country with documents, the border guard sends an advance scout (OPTIONS Preflight) to check if their embassy has an active mutual treaty (Access-Control-Allow-Origin).
Architecture Blueprint & CodeProduction Standard
// Express.js Secure CORS Configuration:
import cors from 'cors';
app.use(cors({
origin: ['https://app.corp.io', 'https://admin.corp.io'], // Explicit whitelist!
credentials: true, // Allows HttpOnly session cookies
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization', 'X-CSRF-Token']
}));Key Architectural Takeaways
- •Never use Wildcard with Credentials: Browsers strictly reject Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials: true.
- •Browser-Enforced Security: CORS is enforced by the client browser, not the server; backend curl/Postman scripts bypass CORS entirely.
Common Architectural Pitfall
Setting Access-Control-Allow-Origin: * on authenticated endpoints requiring cookies or Authorization headers.
Production Best Practice
Explicitly validate origin against a dynamic whitelist of approved domains.