What is CORS and how to configure it in Express.js?
CORS in Express.js
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that blocks web pages from making requests to a different domain than the one that served the page.
The Problem
Frontend: https://myapp.com
Backend: https://api.myapp.com ← different origin!
Browser blocks the request unless the server sends CORS headers.A different origin means any difference in:
- Protocol:
httpvshttps - Domain:
myapp.comvsapi.myapp.com - Port:
3000vs4000
Installing cors Package
bash
npm install corsAllow All Origins (Development Only)
js
const cors = require('cors');
app.use(cors()); // ⚠️ Allows ANY origin — unsafe for productionConfigure Specific Origins
js
const cors = require('cors');
app.use(cors({
origin: 'https://myapp.com', // single origin
methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true, // allow cookies / auth headers
maxAge: 86400, // preflight cache (seconds)
}));Multiple Origins
js
const allowedOrigins = [
'https://myapp.com',
'https://admin.myapp.com',
'http://localhost:3000', // local dev
];
app.use(cors({
origin: (origin, callback) => {
// allow requests with no origin (Postman, curl, SSR)
if (!origin) return callback(null, true);
if (allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error(`Origin ${origin} not allowed by CORS`));
}
},
credentials: true,
}));Per-Route CORS
js
// Public endpoint — allow all
app.get('/public', cors(), (req, res) => {
res.json({ public: true });
});
// Private endpoint — restrict origin
app.get('/private', cors({ origin: 'https://myapp.com' }), (req, res) => {
res.json({ private: true });
});Manual CORS Headers (no package)
js
app.use((req, res, next) => {
res.header('Access-Control-Allow-Origin', 'https://myapp.com');
res.header('Access-Control-Allow-Methods', 'GET,POST,PUT,DELETE');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
res.header('Access-Control-Allow-Credentials', 'true');
// Handle preflight OPTIONS request
if (req.method === 'OPTIONS') {
return res.status(200).end();
}
next();
});Preflight Requests
Browsers send an OPTIONS preflight request before complex CORS requests (those with custom headers or non-simple methods). The server must respond with appropriate Access-Control-* headers.
Browser → OPTIONS /api/users
Access-Control-Request-Method: POST
Access-Control-Request-Headers: Authorization
Server → 200 OK
Access-Control-Allow-Origin: https://myapp.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: AuthorizationThe cors() package handles this automatically.
Summary
Always configure CORS explicitly in production — never use cors() without options. Set credentials: true when your frontend sends cookies or Authorization headers, and whitelist only the origins you actually trust.
Short Answer
Interview readyPremium
A concise answer to help you respond confidently on this topic during an interview.