Advertisement
Intermediate Node.js, Express & Middleware

What is CORS middleware in Express, and how does the cors package simplify configuring Cross-Origin Resource Sharing?

Short answer

CORS is a browser security mechanism that blocks a web page from making requests to a different origin (domain, protocol, or port) than the one it was served from, unless the target server explicitly allows it via specific response headers -- the cors npm package for Express…

Save Node.js mock interview
Advertisement
AModel answer
CORS is a browser security mechanism that blocks a web page from making requests to a different origin (domain, protocol, or port) than the one it was served from, unless the target server explicitly allows it via specific response headers -- the cors npm package for Express handles setting these headers (Access-Control-Allow-Origin, Access-Control-Allow-Methods, and others) and correctly responding to the browser's preflight OPTIONS requests, based on a simple configuration object rather than needing to set each header manually.
const cors = require('cors');

app.use(cors({
  origin: 'https://myapp.com', // only this origin can call this API from a browser
  methods: ['GET', 'POST'],
  credentials: true,
}));
Real-world example
A public API serving a separately-hosted frontend at a different domain configures cors() with that specific frontend's origin allowed, letting the browser-based frontend successfully make requests that would otherwise be blocked by the browser's same-origin policy.
Likely follow-ups
  • Why does a browser send a preflight OPTIONS request before certain cross-origin requests, and how does the cors middleware handle it?
  • What's the security risk of configuring CORS with a wildcard '*' origin combined with credentials: true?
Related topics