MyInternships.in

Express.js & REST APIs

Node.js CORS Configuration

CORS is a browser rule that blocks a page on one origin from reading a response from another unless the server explicitly allows it. The cors middleware adds the required headers.


What is CORS Configuration in Node.js?

CORS is a browser rule that blocks a page on one origin from reading a response from another unless the server explicitly allows it. The cors middleware adds the required headers.

CORS Configuration example

A restrictive CORS setup
JavaScript
import cors from 'cors';

const allowed = ['https://myinternships.in', 'http://localhost:5173'];

app.use(cors({
  origin: (origin, cb) => {
    if (!origin || allowed.includes(origin)) return cb(null, true);
    cb(new Error('Not allowed by CORS'));
  },
  credentials: true,                       // required for cookies
  methods: ['GET', 'POST', 'PUT', 'DELETE'],
}));

Key points to remember

  • CORS is enforced by browsers only — curl and Postman ignore it entirely.
  • With credentials: true the origin must be explicit; the wildcard * is rejected.
  • A preflight OPTIONS request precedes non-simple requests.

Common mistakes with CORS Configuration

  • Setting origin: "*" together with credentials, which browsers refuse.
  • Leaving the wildcard in production, letting any site call your authenticated API.

Node.js CORS Configuration— Interview Questions & FAQs

Why does my API work in Postman but fail in the browser?+

Postman does not enforce CORS. The browser is blocking the response because the server did not send an Access-Control-Allow-Origin header permitting your front-end origin.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships