Full answer
Registering routes
- route('GET', '/students/:id', handler). Turn the path into a regular expression once: escape the literal parts and replace each :name with a named capture group, such as ([^/]+). Anchor the expression with ^ and $ and allow an optional trailing slash if you want that.
- Store { method, regex, keys, handlers }.
Dispatching
- Parse the URL with new URL(req.url, 'http://x') to get pathname and query. Do not match against the raw URL with the query string.
- Loop through routes in order of registration. Collect routes whose pattern matches the path. If one also matches the method, use it. Decode parameters with decodeURIComponent (and handle a malformed value as a 400).
- If some routes matched the path but none the method, answer 405 and set the Allow header. If none matched, answer 404.
- HEAD can use GET handlers, and OPTIONS can answer from the Allow list.
Middleware
- A middleware is (ctx, next). It does work, then calls next() to continue (await it for async code), or ends the response without calling next(). Compose the global middleware and the route handlers into one chain, and guard against calling next() twice.
- Errors: wrap the chain in try/catch and send 500 without leaking details.
Design points: route order matters (a static /students/new should be registered before /students/:id), specificity scoring or a radix tree is faster than a linear scan, and production code should use a tested router (the one in Express, Fastify's find-my-way, or the URLPattern API in newer Node versions).
class Router {
#routes = [];
#middleware = [];
use(fn) { this.#middleware.push(fn); return this; }
route(method, path, ...handlers) {
const keys = [];
const source = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&').replace(/:(\w+)/g, (_, name) => { keys.push(name); return '([^/]+)'; });
this.#routes.push({ method, regex: new RegExp(`^${source}/?$`), keys, handlers });
return this;
}
get(path, ...h) { return this.route('GET', path, ...h); }
post(path, ...h) { return this.route('POST', path, ...h); }
async handle(method, rawUrl) {
const url = new URL(rawUrl, 'http://localhost');
const ctx = { method, path: url.pathname, query: Object.fromEntries(url.searchParams), params: {}, status: 200, body: undefined, headers: {} };
const matches = this.#routes.filter((r) => r.regex.test(ctx.path));
const route = matches.find((r) => r.method === method);
let final;
if (route) {
const values = route.regex.exec(ctx.path).slice(1);
route.keys.forEach((key, i) => { ctx.params[key] = decodeURIComponent(values[i]); });
final = route.handlers;
} else if (matches.length) {
final = [(c) => { c.status = 405; c.headers.Allow = matches.map((m) => m.method).join(', '); c.body = 'method not allowed'; }];
} else {
final = [(c) => { c.status = 404; c.body = 'not found'; }];
}
const chain = [...this.#middleware, ...final];
let index = -1;
const run = async (i) => {
if (i <= index) throw new Error('next() called twice');
index = i;
if (chain[i]) await chain[i](ctx, () => run(i + 1));
};
try { await run(0); } catch (err) { ctx.status = 500; ctx.body = 'server error'; }
return ctx;
}
}
const app = new Router();
app.use(async (ctx, next) => { ctx.headers['x-before'] = '1'; await next(); ctx.headers['x-after'] = '1'; });
app.get('/students/new', (ctx) => { ctx.body = 'new form'; });
app.get('/students/:id', (ctx) => { ctx.body = { id: ctx.params.id, verbose: ctx.query.verbose === 'true' }; });
app.post('/students', (ctx) => { ctx.status = 201; ctx.body = 'created'; });
app.get('/boom', () => { throw new Error('secret detail'); });
(async () => {
const show = async (method, url) => {
const c = await app.handle(method, url);
console.log(`${method} ${url}`.padEnd(32), c.status, JSON.stringify(c.body), c.headers.Allow ? 'Allow: ' + c.headers.Allow : '', c.headers['x-after'] ? '(middleware ran around it)' : '');
};
await show('GET', '/students/42?verbose=true');
await show('GET', '/students/new');
await show('GET', '/students/a%20b/');
await show('POST', '/students');
await show('DELETE', '/students');
await show('GET', '/nothing');
await show('GET', '/boom');
})();The router is tested by calling handle(method, url) directly, so no HTTP server or port is needed. The same dispatch code could be called from an http.createServer callback. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, run once): GET /students/42?verbose=true 200 {"id":"42","verbose":true} (middleware ran around it) GET /students/new 200 "new form" (middleware ran around it) GET /students/a%20b/ 200 {"id":"a b","verbose":false} (middleware ran around it) POST /students 201 "created" (middleware ran around it) DELETE /students 405 "method not allowed" Allow: POST (middleware ran around it) GET /nothing 404 "not found" (middleware ran around it) GET /boom 500 "server error"
Key points
- Compile each path pattern into a regular expression once.
- Match on pathname, not on the raw URL.
- Return 405 with Allow when the path matches but the method does not.
- Middleware is a chain of (ctx, next) functions.
- Route order and specificity matter.
Common mistakes
- Matching on req.url with the query string included.
- Building a regular expression on every request.
- Registering /:id before /new and shadowing it.
- Answering 404 when the method is wrong (405 is correct).
- Not decoding parameters or not handling bad encoding.
Follow-ups
- How does a radix tree speed up routing?
- What does the URLPattern API provide?
- How do you handle a trailing slash and case sensitivity?
Tips
- Describe register, match, run chain.
- Mention 405 and Allow.
- Say that you would use a library in production.