Skip to content
jshacks.dev
Node.js

Handle CORS in a plain node http server

Answer CORS preflight OPTIONS requests and set Access-Control headers for an allowlist of origins in a plain Node.js 24 http server, no middleware.

2 min read
Summarize in AI

A browser app on another origin calls your API and the request fails before it reaches your code. The browser sent a preflight OPTIONS request first, and the server must answer it.

cors.mjsJavaScript
import http from 'node:http';

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

http.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.writeHead(204, {
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '600',
    });
    return res.end();
  }
  res.setHeader('Content-Type', 'application/json');
  res.end('{"ok":true}');
}).listen(3000);
Text
$ curl -si -X OPTIONS -H 'Origin: https://app.example.com' localhost:3000/users
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.example.com
Vary: Origin
Access-Control-Allow-Methods: GET, POST, PUT, DELETE
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 600
Date: Sun, 15 Nov 2026 10:00:00 GMT
Connection: keep-alive
Keep-Alive: timeout=5

Echoing the request's origin only when it is on the allowlist, and adding Vary: Origin, keeps caches from serving one origin's answer to another. The 204 answers the preflight with the methods and headers the real request may use, and Max-Age lets the browser cache that answer for ten minutes. See CORS on MDN.

CORS is enforced by browsers, not by your server. It does not stop curl or another backend, so it is no substitute for authentication. Sending cookies cross-origin also needs Access-Control-Allow-Credentials: true, and then the origin can never be *.

Also inSecurity
Taggednode 24
Share

More snippets

Get new posts by email

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

Unsubscribe in one click. No spam, ever.