Routing without a framework

Topic 3 of 4 in HTTP from scratch5 min readIntermediateFree course

Overview

In the last topic, every route was an if statement:

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

An incoming request GET /courses/42 is checked against a route table: GET /courses → listCourses, POST /courses → createCourse, GET /courses/:id → getCourse, DELETE /courses/:id → deleteCourse. It matches GET /courses/:id and calls getCourse with id ‘42’. No path match gives 404 Not Found; a path match with the wrong method gives 405 Method Not Allowed.

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:

JavaScript
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');            // null

Node 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

JavaScript
// 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

JavaScript
// 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);
Terminal
curl localhost:3000/courses/2        # 200 { "id": "2", … }
curl localhost:3000/courses/99       # 404
curl -X DELETE localhost:3000/courses/2  # 405, Allow: GET

404 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 Allow header 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:

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

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

Exercise

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.

JavaScript
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);

Summary

  • A router maps a method plus a path pattern to a handler function.
  • Path parameters like /courses/:id capture parts of the URL as strings.
  • Unknown paths get 404; a known path with the wrong method gets 405 with an Allow header.
  • URLPattern (or a small regular expression) can match patterns.
  • Frameworks add middleware, body parsing and error handling on top of exactly this idea.