Routing without a framework
Overview
In the last topic, every route was an if statement:
if (req.method === 'GET' && req.url === '/health') { … }
if (req.method === 'POST' && req.url === '/echo') { … }That’s fine for two routes, but a real API has dozens, many with variable parts such as /courses/42/lessons/7. A router organises this: you register method + path pattern → handler, and the router finds the right handler for each request.
Building one yourself takes about 40 lines, and it removes the last bit of mystery from frameworks.
Matching path patterns
A route like /courses/:id should match /courses/42 and capture id = '42'. One simple way is to turn the pattern into a regular expression:
export function compile(pattern) {
const names = [];
const source = pattern.replace(/:(\w+)/g, (_, name) => {
names.push(name);
return '([^/]+)'; // one path segment
});
const regex = new RegExp(`^${source}/?$`);
return (path) => {
const match = regex.exec(path);
if (!match) return null;
return Object.fromEntries(names.map((n, i) => [n, decodeURIComponent(match[i + 1])]));
};
}
const match = compile('/courses/:courseId/lessons/:lessonId');
match('/courses/42/lessons/7'); // { courseId: '42', lessonId: '7' }
match('/courses/42'); // nullNode also has the standard URLPattern class (in recent versions) that does this matching for you: new URLPattern({ pathname: '/courses/:id' }).exec(url).
A small router
// router.js
import { compile } from './compile.js';
export class Router {
#routes = [];
add(method, pattern, handler) {
this.#routes.push({ method, match: compile(pattern), handler });
}
get(p, h) { this.add('GET', p, h); }
post(p, h) { this.add('POST', p, h); }
patch(p, h) { this.add('PATCH', p, h); }
delete(p, h) { this.add('DELETE', p, h); }
async handle(req, res) {
const { pathname } = new URL(req.url, 'http://localhost');
const allowed = [];
for (const route of this.#routes) {
const params = route.match(pathname);
if (!params) continue;
if (route.method !== req.method) {
allowed.push(route.method);
continue;
}
try {
return await route.handler(req, res, params);
} catch (err) {
console.error(err);
return send(res, 500, { error: 'Internal server error' });
}
}
if (allowed.length) {
res.setHeader('Allow', allowed.join(', '));
return send(res, 405, { error: 'Method not allowed' });
}
send(res, 404, { error: 'Not found' });
}
}
export function send(res, status, data) {
const body = JSON.stringify(data);
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(body);
}Using it
// server.js
import http from 'node:http';
import { Router, send } from './router.js';
const courses = new Map([
['1', { id: '1', title: 'JavaScript Essentials' }],
['2', { id: '2', title: 'Node.js' }],
]);
const router = new Router();
router.get('/courses', (req, res) => {
send(res, 200, [...courses.values()]);
});
router.get('/courses/:id', (req, res, { id }) => {
const course = courses.get(id);
if (!course) return send(res, 404, { error: `Course ${id} not found` });
send(res, 200, course);
});
http.createServer((req, res) => router.handle(req, res)).listen(3000);curl localhost:3000/courses/2 # 200 { "id": "2", … }
curl localhost:3000/courses/99 # 404
curl -X DELETE localhost:3000/courses/2 # 405, Allow: GET404 vs 405
Returning the right error helps whoever is calling your API:
- 404 Not Found — no route matches this path at all, or the specific item doesn’t exist.
- 405 Method Not Allowed — the path exists but doesn’t support this method. Include an
Allowheader listing the methods that are supported.
Order matters
Routes are checked in the order they were added, and the first match wins. A general pattern registered before a specific one can “swallow” it:
router.get('/courses/:id', getCourse);
router.get('/courses/featured', getFeatured); // never reached: ':id' matched 'featured'Register specific paths before patterns with parameters.
Query strings
The query string isn’t part of route matching — read it separately:
router.get('/courses', (req, res) => {
const url = new URL(req.url, 'http://localhost');
const level = url.searchParams.get('level'); // null if missing
const page = Number(url.searchParams.get('page') ?? 1);
// …filter and paginate
});What’s still missing?
Look at what a real API needs on top of this router:
- Shared steps for many routes — logging, authentication, rate limiting, parsing bodies. Copying them into every handler is error-prone.
- Consistent error handling — turning thrown errors into proper JSON responses with the right status.
- Helpers —
res.json(),res.status(), redirects, cookies, static files. - Nested routers — grouping
/courses/...routes in their own file.
Express provides all of these through one idea: middleware. In the next chapter you’ll switch to Express — and recognise that app.get('/courses/:id', handler) is doing exactly what your router did.
Built-in or framework? For a tiny internal tool, a hand-rolled router is fine. For anything bigger, use a framework: its routing, security fixes and ecosystem are worth far more than the few kilobytes it adds.
Add routes to the router
Using the Router class from this lesson, build an in-memory notes API: GET /notes, POST /notes, GET /notes/:id and DELETE /notes/:id. Return 404 for unknown notes and 204 after a delete.
import http from 'node:http';
import { json } from 'node:stream/consumers';
// import or paste the Router class here
const notes = new Map();
const router = new Router();
// add your routes here
http.createServer((req, res) => router.handle(req, res)).listen(3000);let nextId = 1;
router.get('/notes', (req, res) => send(res, 200, [...notes.values()]));
router.post('/notes', async (req, res) => {
const { text } = await json(req);
const note = { id: String(nextId++), text };
notes.set(note.id, note);
send(res, 201, note);
});
router.get('/notes/:id', (req, res, { id }) => {
const note = notes.get(id);
note ? send(res, 200, note) : send(res, 404, { error: 'Note not found' });
});
router.delete('/notes/:id', (req, res, { id }) => {
if (!notes.delete(id)) return send(res, 404, { error: 'Note not found' });
res.writeHead(204).end();
});Summary
- A router maps a method plus a path pattern to a handler function.
- Path parameters like
/courses/:idcapture parts of the URL as strings. - Unknown paths get 404; a known path with the wrong method gets 405 with an
Allowheader. URLPattern(or a small regular expression) can match patterns.- Frameworks add middleware, body parsing and error handling on top of exactly this idea.