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.
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.
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();204 https://app.example.comEcho 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.