CORS

CORS controls which other websites are allowed to call your API from a browser.

Syntaxapp.use(cors({ origin: '...' }))

Browsers block a web page from calling an API on a different origin unless the API opts in with CORS headers. The cors package adds them.

Passing no options allows all origins, which is fine for public APIs. For private APIs, restrict it to your own front-end origin.

Example

Example · javascript
const cors = require('cors');

// Allow only your front-end
app.use(cors({
  origin: 'https://app.soundscode.com',
  methods: ['GET', 'POST'],
}));

When to use it

  • A developer configures the cors middleware to only allow requests from the production frontend domain, blocking untrusted cross-origin callers.
  • An API enables CORS preflight caching with an maxAge of 86400 seconds to reduce the number of OPTIONS requests from the browser.
  • A public read-only API sets Access-Control-Allow-Origin: * so any website can fetch its data, while mutation endpoints restrict origins.

More examples

Restrict to one origin

Allows requests only from the specific frontend origin and enables cookie/credential forwarding.

Example · js
const cors = require('cors');

app.use(cors({
  origin: 'https://app.example.com',
  credentials: true,
}));

Allowlist of origins

Uses a callback-form origin option to check against a dynamic allowlist, rejecting any unlisted origin.

Example · js
const allowed = ['https://app.example.com', 'https://admin.example.com'];

app.use(cors({
  origin: (origin, cb) => {
    if (!origin || allowed.includes(origin)) return cb(null, true);
    cb(new Error('CORS not allowed'));
  },
}));

CORS options for preflight caching

Specifies allowed methods and headers, and sets maxAge so browsers cache the OPTIONS response for 24 hours.

Example · js
app.use(cors({
  origin: 'https://app.example.com',
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'PATCH'],
  allowedHeaders: ['Content-Type', 'Authorization'],
  maxAge: 86400, // cache preflight for 24 hours
}));

Discussion

  • Be the first to comment on this lesson.