A router in 20 lines
Each path gets its own handler, and /posts/:slug hands the slug over as a parameter. None of the 20 lines is a regular expression.
Last chapter ended with a server that answers every request with the same text. That was fine for one page and useless for two. This chapter gives each path its own handler, and /posts/:slug hands the slug over as a parameter. The whole router is 20 lines, and none of them is a regular expression.

Splitting the path
A pattern and a path are both split at /. They match when they have the same number of parts and every part is equal, except parts that start with :. Those become parameters.
function compare(parts: string[], path: string[]) {
if (parts.length !== path.length) return null;
const params: Record<string, string> = {};
for (const [i, part] of parts.entries()) {
if (part.startsWith(':')) params[part.slice(1)] = path[i]; // [!code highlight]
else if (part !== path[i]) return null;
}
return params;
}Registering and matching
export function route(method: string, pattern: string, handler: Handler) {
routes.push({ method, parts: pattern.split('/'), handler });
}
export function match(req: Request) {
const path = new URL(req.url).pathname.split('/');
for (const r of routes) {
const params = r.method === req.method && compare(r.parts, path);
if (params) return r.handler(req, params);
}
return new Response('Not found', { status: 404 });
}Wiring it into the server
-const handle = () => new Response('Hello');
+import { match, route } from './router.ts';
+route('GET', '/posts/:slug', (req, { slug }) => new Response(`You asked for: ${slug}`));
+const handle = match;Is it fast enough?
Routes are compared in order, so the cost grows with their number. With twelve routes it does not show: the router costs 6 % against no router at all.

| Setup | Requests a second | p99 latency |
|---|---|---|
| No router | 41,380 | 4.1 ms |
| Router | 38,905 | 4.4 ms |
| Router and logging | 31,270 | 5.6 ms |
The code as it stands after this chapter, if you want to run it:
subscribe
New entries and the next chapter by mail, nothing else.