How Do You Handle CORS in Node.js?
Handle CORS in Node.js with Access-Control-Allow headers and the Express cors middleware. Learn preflight requests, credentials, and secure origin setup.
Expected Interview Answer
CORS (Cross-Origin Resource Sharing) is a browser security mechanism, and you handle it in Node.js by sending the right Access-Control-Allow-* response headers so browsers permit requests from other origins — most easily with the cors middleware in Express.
Browsers block a page on one origin (scheme + host + port) from reading responses served by another origin unless the server explicitly opts in. The server signals permission with headers such as Access-Control-Allow-Origin, Access-Control-Allow-Methods, and Access-Control-Allow-Headers. For unsafe methods or custom headers, the browser first sends an OPTIONS preflight request that your server must answer with those headers and a 204 status. In Express you typically use app.use(cors(options)) to set them automatically; in raw Node.js you set the headers manually and short-circuit the OPTIONS request. When credentials like cookies are involved, you must set Access-Control-Allow-Credentials to true and specify an exact origin, not the '*' wildcard.
- Lets trusted front-end origins safely call your API
- Preflight negotiation keeps unsafe cross-origin requests controlled
- The cors middleware handles headers and preflight in one line
- Fine-grained control over allowed origins, methods, and headers
- Supports credentialed requests when configured correctly
AI Mentor Explanation
CORS is like the boundary rope with a gatekeeper deciding which outside players may step onto the pitch. Your API is the field; a request from another origin is a player from a different club. The Access-Control-Allow-Origin header is the gatekeeper's team sheet naming who's allowed in, and the preflight OPTIONS check is asking permission at the gate before actually walking onto the ground.
Step-by-Step Explanation
Step 1
Understand the problem
Browsers block cross-origin responses unless the server sends explicit Access-Control-Allow-* headers.
Step 2
Install or set headers
In Express run npm install cors; in raw Node.js set the headers manually on res.
Step 3
Allow the origin
Set Access-Control-Allow-Origin to a specific origin (or '*' for public, non-credentialed APIs).
Step 4
Declare methods and headers
Set Access-Control-Allow-Methods and Access-Control-Allow-Headers so preflight passes.
Step 5
Answer the preflight
Respond to OPTIONS requests with those headers and a 204 status before the real request runs.
Step 6
Handle credentials
For cookies, set Access-Control-Allow-Credentials to true and use an exact origin, never '*'.
What Interviewer Expects
- CORS is enforced by the browser, not the server
- Knowing the key Access-Control-Allow-* headers
- Understanding the OPTIONS preflight request
- Using the cors middleware in Express
- Why '*' cannot be used with credentials
Common Mistakes
- Thinking CORS is a server-side or backend-to-backend restriction
- Using Access-Control-Allow-Origin '*' together with credentials
- Forgetting to handle the OPTIONS preflight request
- Not listing custom headers in Access-Control-Allow-Headers
- Disabling CORS entirely instead of allowing specific trusted origins
Best Answer (HR Friendly)
“CORS is a browser rule that stops a website from calling an API on a different domain unless that API says it's allowed. In Node.js you handle it by sending permission headers — usually with the cors package in Express — that name which sites can talk to your server.”
Code Example
const express = require('express');
const cors = require('cors');
const app = express();
// Allow only your front-end origin, with credentials
app.use(cors({
origin: 'https://app.example.com',
methods: ['GET', 'POST', 'PUT', 'DELETE'],
allowedHeaders: ['Content-Type', 'Authorization'],
credentials: true,
}));
app.get('/api/data', (req, res) => {
res.json({ message: 'CORS enabled' });
});
app.listen(3000);const http = require('http');
http.createServer((req, res) => {
res.setHeader('Access-Control-Allow-Origin', 'https://app.example.com');
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
// Answer the preflight request
if (req.method === 'OPTIONS') {
res.writeHead(204);
res.end();
return;
}
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ ok: true }));
}).listen(3000);Follow-up Questions
- What is a CORS preflight request and when is it triggered?
- Why can't you use '*' for Access-Control-Allow-Origin with credentials?
- Which headers make a request 'non-simple' and force a preflight?
- How would you allow multiple specific origins dynamically?
- Is CORS a substitute for authentication or authorization?
MCQ Practice
1. Where is CORS actually enforced?
CORS is enforced by the browser, which blocks cross-origin responses unless the server sends the appropriate Access-Control-Allow headers.
2. Which HTTP method is used for a CORS preflight request?
The browser sends an OPTIONS preflight request to check permissions before the actual unsafe request is made.
3. When sending credentials (cookies), Access-Control-Allow-Origin must be?
With credentials the wildcard '*' is disallowed; you must specify an exact origin and also set Access-Control-Allow-Credentials to true.
Flash Cards
What does CORS stand for? — Cross-Origin Resource Sharing — a browser mechanism controlling cross-origin HTTP requests.
What triggers a preflight request? — Unsafe methods (PUT, DELETE) or custom headers cause the browser to send an OPTIONS preflight first.
Key header to allow an origin? — Access-Control-Allow-Origin, set to a specific origin or '*' for public APIs.
Wildcard with credentials? — Not allowed — with credentials you must name an exact origin and set Allow-Credentials to true.