> ## Content Index
> Fetch the complete content index at: https://logbuch-dev-blog.nichedthemes.com/llms.txt
> Use this file to discover other available public pages before exploring further.

# A router in 20 lines
- URL: https://logbuch-dev-blog.nichedthemes.com/a-router-in-20-lines/
- Published: 2026-10-05T07:30:00.000Z
- Updated: 2026-10-05T07:30:00.000Z
- Description: 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.
- Author: Mira Okafor
- Tags: Backend, TypeScript, A tiny HTTP server in TypeScript, #Import 2026-11-19 07:37

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.

![A diagram: socket to parse to match to handler, and the response written back to the socket.](https://logbuch-dev-blog.nichedthemes.com/content/images/logbuch/request-flow.jpg)

Where the router sits between the parsed request and the handler.

## 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.

```ts
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

```ts
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

```diff-ts
-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.

![A bar chart: 41,380 requests a second without a router, 38,905 with it, 31,270 with the router and logging.](https://logbuch-dev-blog.nichedthemes.com/content/images/logbuch/router-benchmark.jpg)

autocannon, 30 seconds, 100 connections, on the mini PC.

| 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:

[The tiny server after chapter 3src/router.ts, src/server.ts and a README. 2 KB.tiny-server-chapter-3.zip1 KBdownload-circle](https://logbuch-dev-blog.nichedthemes.com/content/files/logbuch/tiny-server-chapter-3.zip "Download")