Skip to content
jshacks.dev
APIs

Add CORS headers to Node.js API

Add CORS headers to a Node.js API by echoing an allowed origin, answering the OPTIONS preflight with 204, and sending Vary: Origin.

1 min read
Summarize in AI

A browser blocks a page from reading a response from another origin unless the server opts in with CORS headers. Preflight requests, which use OPTIONS, need an answer of their own.

cors.jsJavaScript
import { createServer } from 'node:http';

const allowed = new Set(['https://app.example.com']);

const server = createServer((req, res) => {
  const origin = req.headers.origin;
  if (allowed.has(origin)) {
    res.setHeader('Access-Control-Allow-Origin', origin);
    res.setHeader('Vary', 'Origin');
  }

  if (req.method === 'OPTIONS') {
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST');
    res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    res.writeHead(204).end();
    return;
  }

  res.setHeader('Content-Type', 'application/json');
  res.end('{"ok":true}');
});
await new Promise((resolve) => server.listen(0, resolve));

const res = await fetch(`http://localhost:${server.address().port}/`, {
  method: 'OPTIONS',
  headers: { Origin: 'https://app.example.com' },
});
console.log(res.status, res.headers.get('access-control-allow-origin'));

server.close();
Text
204 https://app.example.com

Echo the request's origin only when it is on your list, and add Vary: Origin so a cache never serves one origin's answer to another. Avoid * when the API uses cookies: browsers refuse a wildcard together with credentials.

CORS is enforced by the browser, not by the server, so it does not protect your API from curl. See CORS on MDN.

Also inNode.js
Share

More snippets

APIs

Fetch JSON and handle HTTP errors

Fetch JSON in the browser or Node.js 24 and throw on 404 or 500 yourself, because fetch only rejects on network failure and does not check the status.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.