Skip to content
Tutorials Center
My learning

Topics

Lesson 51 of 133 ยท Networking and HTTP

Building a Router from Scratch

Build an HTTP router in Node.js with URLPattern - path parameters, query strings, method matching, 404 and 405 responses, route groups, composed handlers and error handling.

A web server answers different requests differently: GET /books lists books, GET /books/7 shows one, POST /books creates one, and GET /nonsense says "not found". Deciding which function handles which request is called routing. In The http Module: Servers we routed with an if chain. That is fine for three routes and miserable for thirty.

In this lesson you build a small, real router with about 60 lines of code. Along the way you learn URLPattern (a standard way to describe URL shapes, global in Node 24), how path parameters and query strings differ, the difference between 404 Not Found and 405 Method Not Allowed, why route order matters, and how to group routes and wrap handlers. Express, Fastify and Hono all work on the same ideas, so afterwards their documentation will read like familiar territory. See Express and Minimal Frameworks for the comparison.

Describing paths with URLPattern

A route needs a pattern such as /books/:id that can say whether a path matches and extract the :id part. Writing that with regular expressions by hand is error-prone. Node 24 has the web-standard URLPattern class built in (no import needed). You give it the part of the URL you care about, usually pathname, and ask test() for a yes/no answer or exec() for the details. The extracted values are in result.pathname.groups.

Node.js URLPattern: test, exec and groups

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

A few rules to remember:

  • :name matches one segment (everything up to the next /). :name+ matches one or more segments, :name* zero or more, :name? zero or one segment.
  • (regex) after a name restricts what it may match. Inside a JavaScript string, backslashes are doubled: '\\d+'.
  • { ... }? makes a group optional, as in /guide{/:chapter}?.
  • A pattern built from an object only looks at the components you named; the others (host, search, ...) accept anything.
  • Matching is exact: /books/42/ does not match /books/:id. Many apps normalise trailing slashes before routing.
  • Invalid patterns throw TypeError: Failed to construct URLPattern when you build them, which means mistakes show up at startup, not on the first request.

Parameters versus query strings

Two different kinds of input travel in a URL, and a router treats them differently.

  • Path parameters are part of the identity of the resource: /books/42. The router extracts them, and a route will not match without them.
  • Query strings are optional adjustments: /books?genre=fantasy&page=2. The router ignores them when matching; the handler reads them with URLSearchParams.

Both are always strings. Convert and validate them (Number(id), check Number.isInteger), and remember that percent-encoded characters in path parameters are not decoded for you: /greet/Ana%20Maria gives Ana%20Maria. Decode with decodeURIComponent, wrapped in try/catch because malformed input like %E0%A4%A throws.

A first router

The core of a router is a list of routes. Each has an HTTP method, a compiled pattern and a handler. To handle a request, walk the list and run the first route that matches. Handlers receive one object (a context) holding the request, the response, the parameters and the query.

Node.js A 40-line router and a server using it

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

That is a working router. Notice /books/abc gives a 404 because the pattern :id(\d+) does not match at all; the regular expression acts as validation for free. And a handler that finds nothing returns null, which is sent as null with status 200: we will fix that with proper errors shortly.

404 versus 405

There are two different "no" answers, and good APIs distinguish them:

  • 404 Not Found: no route matches this path at all.
  • 405 Method Not Allowed: the path exists, but not for this HTTP method (a DELETE to a read-only resource). The response must include an Allow header listing the methods that are supported.

To produce a 405 you cannot stop at the first non-matching method. Keep walking, and remember the methods of every route whose path matched. If you reach the end with a non-empty set, answer 405 with that set; if it is empty, answer 404. The same loop also collects the information you need to answer an OPTIONS request.

Node.js 404 and 405 from the same matching loop

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

DELETE /books is a 405 with Allow: GET, POST, while GET /shelves is a plain 404. Real routers also answer HEAD requests with the GET handler (without a body) and OPTIONS with the Allow list; both are small additions to this loop.

Order matters

With a "first match wins" strategy, the order in which you register routes is part of the behaviour. The classic bug is a specific route hiding behind a general one.

Node.js A general route registered first swallows a specific one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

In the wrong order, /users/me is treated as "show the user whose id is me". The fixes are to register literal routes before parameterised ones, or to constrain the parameter with a regex (:id(\\d+)) so it cannot match me in the first place. The second approach makes the order irrelevant, which is more robust. Some frameworks sort routes by specificity automatically; ours stays simple and predictable.

Errors, groups and composed handlers

Three more features turn the router into something you could build an application on.

Errors as exceptions. Instead of writing a response in every failure branch, let handlers throw new HttpError(404, 'no such book'). A single catch in the router turns it into a response. Any other exception is a bug: answer a generic 500 and never leak the message.

Route groups. Routes often share a prefix (/api/v1). A group(prefix, build) method adds the prefix to everything registered inside the callback.

Composed handlers. Pass several functions to one route: guards first, then the real handler. Each guard receives next and either throws or returns next(). This is the small version of the middleware pattern.

The final version of the router below includes all of that, plus 404/405 handling, decoded parameters and a JSON body reader.

Node.js The complete router: groups, guards, errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Study how each line of output is produced. The missing API key is rejected by the guard before the handler runs. A handler that returns nothing yields 204 No Content. The unexpected Error in /boom prints its real message on the server log only, while the client sees a generic message: leaking hunter2 to the client would be a security bug (see Web Application Security). And the decoding error becomes a clean 400 instead of crashing the request.

This router reads the body in none of its handlers. Real handlers parse JSON or form data with a size limit; see Request Bodies, JSON and Forms. Adding a ctx.json() helper that does so is a natural next step.

When to build your own, when to use a framework

Writing a router once is the best way to understand frameworks, and for a small internal service or a learning project it is perfectly reasonable. But production routers handle many details we skipped: HEAD and OPTIONS, trailing-slash policy, case sensitivity, wildcard and regex edge cases, route caching for speed (a linear scan through thousands of routes gets slow), nested routers, async error propagation and better 404 pages. Frameworks have solved and tested those. For performance-sensitive services, specialised routers use a radix tree instead of a list, so the lookup cost depends on the length of the path rather than the number of routes.

A sensible path: learn on this router, then use Express or a minimal framework for real applications, and keep your handlers free of framework details so you can switch (Project Structure and Architecture shows how). You will use this router again when you build the REST API project.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which pattern matches /books/42 but not /books/abc?

    A regular expression in parentheses after the parameter name restricts what it may match. :id(\d+) accepts only digits.
  2. 2. What is the difference between a 404 and a 405 response?

    A 405 response also carries an Allow header listing the methods the path does support.
  3. 3. Why were /users/:id and /users/me a problem when registered in that order?

    With first-match-wins, a general route registered before a specific one swallows requests meant for the specific one. Order literal routes first or constrain the parameter.
  4. 4. What happens to a path parameter such as Ana%20Maria in URLPattern groups?

    Groups hold the raw text. Use decodeURIComponent inside try/catch, because malformed input throws.
  5. 5. Why does the final router answer 500 with a generic message when a handler throws a plain Error?

    Unexpected errors are bugs. Log the details on the server and give clients a generic response so secrets and internals do not leak.

Summary

  • Routing maps a method and path to a handler; URLPattern (global in Node 24) describes paths with :params, regex constraints, optional groups and wildcards.
  • Path parameters identify the resource and are extracted by the pattern; query strings are optional extras read from URLSearchParams. Both are strings and need validation; path groups are not percent-decoded for you.
  • Loop through routes, run the first match, and remember the methods of path-only matches to return 405 with an Allow header; otherwise 404.
  • Registration order is behaviour: register specific routes first, or constrain parameters.
  • Throw HttpError for expected failures, answer generic 500 for bugs, group routes with a shared prefix, and compose guards in front of handlers.
  • Use a framework for production, but now you know how they work.

Next: Request Bodies, JSON and Forms