Route requests by method and path without a framework
Route requests by HTTP method and URL path with a small table of patterns in a plain Node.js 24 http server, including path parameters and 404 and 405.
A handful of endpoints does not need Express. A table of method, pattern and handler, plus new URL, covers routing with parameters and the right error codes.
import http from 'node:http';
const routes = [
['GET', /^\/users$/, () => ({ users: ['ada', 'linus'] })],
['GET', /^\/users\/(?<id>\d+)$/, ({ id }) => ({ id: Number(id) })],
['DELETE', /^\/users\/(?<id>\d+)$/, ({ id }) => ({ deleted: Number(id) })],
];
http.createServer((req, res) => {
const { pathname } = new URL(req.url, 'http://localhost');
const matches = routes.filter(([, re]) => re.test(pathname));
const route = matches.find(([method]) => method === req.method);
const status = route ? 200 : matches.length ? 405 : 404;
const body = route ? route[2](pathname.match(route[1]).groups ?? {}) : { error: status };
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}).listen(3000);$ curl -s localhost:3000/users/7
{"id":7}
$ curl -s -X POST localhost:3000/users/7
{"error":405}
$ curl -s localhost:3000/nope
{"error":404}new URL(req.url, base) splits off the query string, so /users?page=2 still matches /users. Named groups in each pattern become the handler's parameters. When the path matches but the method does not, the correct answer is 405 Method Not Allowed, not 404, which is the detail hand-written routers usually miss. See the URL class.
Patterns are tested in order, one by one, which is fine for dozens of routes and slow for thousands. A 405 should also send an Allow header listing the valid methods. Once you need middleware, body parsing and error handling, a small framework such as Fastify costs less than writing them yourself.