What is CORS and how do you enable it safely in an Express API?
CORS is a browser rule that blocks a page from reading responses from a different origin unless the server allows it with headers. In Express, use the cors package with an allow-list of origins, not a wildcard for private APIs.
Explain it simply
Your frontend runs at https://app.college.in and your API at https://api.college.in. These are different origins (scheme, host or port differs). Browsers protect users by refusing to let one site's JavaScript read another site's response unless that server says, "Yes, this origin is welcome." The server says it through headers such as Access-Control-Allow-Origin.
Important: CORS is enforced by browsers only. Postman and curl ignore it, and it does not protect your server from other servers.
For some requests (a JSON POST, or any with an Authorization header), the browser first sends a "preflight" OPTIONS request to ask permission.
Example
const express = require("express");
const cors = require("cors");
const app = express();
const allowed = ["https://app.college.in", "http://localhost:5173"];
app.use(cors({
origin(origin, callback) {
// no origin means curl or server-to-server, not a browser page
if (!origin || allowed.includes(origin)) return callback(null, true);
callback(new Error("Not allowed by CORS"));
},
methods: ["GET", "POST", "PATCH", "DELETE"],
credentials: true, // allow cookies
}));origin: "*" is fine for fully public data, but it cannot be combined with credentials: true.
What to say in the interview
"CORS is the browser's same-origin protection relaxed by server headers. I use the cors middleware with an explicit list of origins, handle preflight, and only enable credentials for trusted origins. It is not a server-side security control."
Common mistakes
- Using
*everywhere to make an error disappear. - Believing CORS prevents non-browser clients from calling the API.