Interview Q&A / Node.js

IntermediateQuick answer1 min readUpdated 3 Oct 2026

What is CORS and how do you enable it safely in an Express API?

SHORT ANSWER

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

js
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.

#express#cors#security

Related questions

Practise more Node.js questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Node.js quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.