Skip to main content

One Handler per Route

Routing decides which handler answers which request. The node:http module has no router of its own: it hands every request to one function, and you decide where it goes. That takes only a few lines — and writing them once shows exactly what a router does.

The pieces are the request's method (req.method), its path and its query. new URL(req.url ?? "/", "http://localhost") splits the path from the query string, because req.url is only the part after the host. A pattern like "/users/{id}" is then matched segment by segment, and the matching piece is handed to the handler as params.id. Frameworks add conveniences on top, but this covers the everyday needs.


Routes and Path Values

Two routes: the list at /users and one user at /users/{id}. The braces part is the path parameter — the piece of the URL that is data.

A route with a path parameter

The same router sends /users to one handler and /users/7 to another, and matchPath hands the 7 to the handler as params.id — the handler itself does no string cutting.

Prompt
Write a TypeScript program with a small router over node:http and two routes: GET /users returning a list line, and GET /users/{id} whose handler receives the id as a path parameter. Serve it on port 0, request both routes with fetch and print the responses.
Output: TypeScript file and captured output

Query Parameters

The part after ? holds query parameters — options for the request, like a search text or a limit: /search?q=api&limit=2. They come from url.searchParams, always as strings, and get() returns null for a missing one — so ?? can supply a default.

The rule of thumb: the path says which resource, the query says how — filters, sorting, paging.

Reading the query string

The handler reads q and limit from the query. The second request skips limit, so the handler falls back to 10 — missing parameters are normal, plan for them.

Prompt
Write a TypeScript program with a /search handler that reads the q and limit query parameters from url.searchParams, using 10 as the default limit when it is missing. Serve it on port 0, request it once with both parameters and once with only q, printing the responses.
Output: TypeScript file and captured output