What is CORS and how do you enable it in Node.js?
Why Interviewers Ask This
Foundational questions like this help interviewers calibrate the rest of the interview. A confident, accurate answer signals that you have solid Node.js basics — a prerequisite for any developer role.
Answer
CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different domain (origin) than the one that served the page. The browser enforces this; Node.js itself does not apply it to server-to-server requests. An origin is defined by protocol + domain + port. When a browser makes a cross-origin request, the server must include appropriate Access-Control-Allow-* headers. In Express.js, the easiest approach is the cors npm package: const cors = require("cors"); app.use(cors()); — this allows all origins. For production, configure it specifically: app.use(cors({ origin: "https://yourfrontend.com", methods: ["GET", "POST"], credentials: true }));. Alternatively, set headers manually: res.setHeader("Access-Control-Allow-Origin", "*");. Preflight requests (OPTIONS method) must also be handled — the cors package does this automatically.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Node.js codebase.
Previous
What is JSON.parse() and JSON.stringify() in Node.js?
Next
How do you handle errors in Express.js?