What is CORS and how do you configure the cors middleware safely in Express?
❓ Interview Prompt: Explain Cross-Origin Resource Sharing (CORS), preflight OPTIONS requests, and why wildcard (*) origins are dangerous with authentication cookies.
CORS (Cross-Origin Resource Sharing) is a browser security mechanism blocking AJAX requests from a different domain than the server, unless explicitly permitted via HTTP headers.
Preflight ('OPTIONS') Requests:
For complex requests (PUT/DELETE or custom headers like 'Authorization'), the browser automatically sends an HTTP 'OPTIONS' preflight request to verify if the server permits the actual request.
Safe Express Configuration:
Use the official 'cors' npm package. *Never use 'origin: ""' in production* with authenticated sessions! Browsers reject responses using wildcard '' when requests include cookies ('credentials: "include"'). Whitelist explicit domains and set 'credentials: true'.
Code Implementation Example
import express from 'express';
import cors from 'cors';
const app = express();
const allowedOrigins = ['https://myadmin.com', 'https://www.myapp.com'];
const corsOptions = {
origin: (origin, callback) => {
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error('Blocked by CORS policy'));
}
},
credentials: true, // Required for cookies and Authorization headers!
methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
allowedHeaders: ['Content-Type', 'Authorization'],
maxAge: 86400 // Cache preflight OPTIONS response for 24 hours
};
app.use(cors(corsOptions));Never use wildcard (*) CORS origins with authenticated endpoints. Whitelist trusted frontend origins and enable credentials: true.