← Back to Node.js, page 8

nodejs-0160 · Easy fresher

How does CORS work in Express: simple requests, preflight, credentials and a safe origin allowlist?

CORS is a browser rule that lets a page read a response from another origin only if the server allows it with Access-Control-Allow-Origin. Some requests (JSON bodies, custom headers, PUT or DELETE) first send an OPTIONS preflight. With cookies you must name the exact origin (not *) and send Access-Control-Allow-Credentials: true. Use an allowlist, add Vary: Origin, and remember that CORS is not authentication.

Full answer

What CORS is

  • Browsers block JavaScript on one origin (scheme, host, port) from reading responses from another origin, unless the server opts in. The server still receives and runs the request, so CORS does not replace authentication or CSRF protection.
  • Non-browser clients such as curl, mobile apps and servers ignore CORS completely.

Request types

  • Simple requests (GET, HEAD, POST with form content types and no custom headers) go straight through. The browser checks the response header Access-Control-Allow-Origin.
  • Preflighted requests (JSON content type, Authorization header, PUT, PATCH, DELETE): the browser first sends OPTIONS with Origin, Access-Control-Request-Method and Access-Control-Request-Headers. The server answers 204 with Access-Control-Allow-Methods and Access-Control-Allow-Headers, and Access-Control-Max-Age to cache the answer.

Credentials

  • To send cookies or HTTP auth, the client sets credentials: 'include' and the server must answer with Access-Control-Allow-Credentials: true and a specific origin. The wildcard * is not allowed with credentials.

Allowlist

  • Compare the request Origin with a list you control and echo it back when it matches. Never reflect any origin blindly, and do not trust a pattern such as endsWith('example.com') (evilexample.com matches).
  • Add Vary: Origin so caches do not serve one origin's headers to another.
  • The cors package does this: cors({ origin: (origin, cb) => ..., credentials: true }).

Common errors: forgetting that the error response also needs the CORS headers, mixing up CORS errors with server errors (the browser hides the response), and 'fixing' CORS with * in production for private APIs.

javascript
const express = require('express');
const cors = require('cors');

const allowed = new Set(['https://app.school.example']);
const app = express();
app.use(cors({
  origin: (origin, callback) => callback(null, !origin || allowed.has(origin)),   // requests without Origin (curl, servers) pass
  credentials: true,
  methods: ['GET', 'POST', 'PUT'],
  allowedHeaders: ['content-type', 'authorization'],
  maxAge: 600,
}));
app.get('/data', (req, res) => res.json({ ok: true }));

const server = app.listen(0, '127.0.0.1', async () => {
  const base = 'http://127.0.0.1:' + server.address().port;
  const show = async (label, path, init) => {
    const res = await fetch(base + path, init);
    const h = (name) => res.headers.get(name) ?? '-';
    console.log(label.padEnd(26), res.status, '| allow-origin:', h('access-control-allow-origin'), '| credentials:', h('access-control-allow-credentials'), '| vary:', h('vary'));
  };
  await show('allowed origin', '/data', { headers: { origin: 'https://app.school.example' } });
  await show('other origin', '/data', { headers: { origin: 'https://evil.example' } });
  await show('look-alike origin', '/data', { headers: { origin: 'https://app.school.example.evil.example' } });
  await show('no Origin (curl)', '/data');

  const pre = await fetch(base + '/data', { method: 'OPTIONS', headers: { origin: 'https://app.school.example', 'access-control-request-method': 'PUT', 'access-control-request-headers': 'content-type' } });
  console.log('preflight:', pre.status, '| methods:', pre.headers.get('access-control-allow-methods'), '| headers:', pre.headers.get('access-control-allow-headers'), '| max-age:', pre.headers.get('access-control-max-age'));
  server.close();
});

The server is called with a fixed Origin header, as a browser would do. The look-alike origin does not get the allow header. Real browsers enforce the result, and Node's fetch does not. Install first with npm install express cors (run here with express 5.3.0, cors 2.8.6). Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): allowed origin 200 | allow-origin: https://app.school.example | credentials: true | vary: Origin other origin 200 | allow-origin: - | credentials: - | vary: - look-alike origin 200 | allow-origin: - | credentials: - | vary: - no Origin (curl) 200 | allow-origin: - | credentials: true | vary: Origin preflight: 204 | methods: GET,POST,PUT | headers: content-type,authorization | max-age: 600

Key points

  • CORS controls who can read cross-origin responses in browsers.
  • JSON, custom headers and PUT or DELETE trigger a preflight.
  • Credentials need an exact origin, never *.
  • Use an allowlist and Vary: Origin.
  • CORS is not authentication and does not stop CSRF.

Common mistakes

  • Reflecting any Origin back with credentials enabled.
  • Using a wildcard with cookies.
  • Matching origins with endsWith or includes.
  • Thinking CORS protects the API from other clients.
  • Forgetting that error responses also need the headers.

Follow-ups

  • Why does the browser send a preflight request?
  • What does Vary: Origin do?
  • How is CORS different from CSRF protection?

Tips

  • Define it as a browser rule.
  • Explain simple versus preflight.
  • Say 'exact origin with credentials'.