Node.js ยท Chapter 39 of 43

CORS

CORS (Cross-Origin Resource Sharing) is a browser security mechanism that restricts web pages from making requests to a different origin than the one that served the page, unless the server explicitly allows it.

APIs intended to be consumed by browser-based frontends on different domains must configure CORS headers correctly.

How CORS works

The server includes headers like `Access-Control-Allow-Origin` to tell browsers which origins are permitted to access the resource.

Using the cors package

The `cors` npm package is Express middleware that automatically sets the correct CORS headers based on configuration.

Example 1 (javascript)
const cors = require('cors');
const express = require('express');
const app = express();
app.use(cors({ origin: 'https://myfrontend.com' }));

This allows only https://myfrontend.com to make cross-origin requests to this API.

Example 2 (javascript)
app.use(cors());
Output
Access-Control-Allow-Origin: *

Calling cors() with no options allows requests from any origin (useful for public APIs).

Key points

  • CORS is enforced by browsers, not servers themselves.
  • Access-Control-Allow-Origin controls which origins are permitted.
  • The cors npm package simplifies configuring these headers in Express.
  • Restrict CORS to trusted origins in production for security.
๐Ÿ’ก Note: CORS errors only appear in browsers โ€” tools like curl or Postman ignore CORS entirely.

๐Ÿ“ Quick Quiz

1. What does CORS stand for?

2. Which header tells browsers which origins are allowed?

3. Which tool typically ignores CORS restrictions?