TExcelTAD
Home › Node.js › Node.js Routing

Node.js Routing

A real server answers different URLs in different ways: / shows the home page, /about an about page, /users/42 one user. Deciding which code handles a request is called routing. Frameworks do it for you, but writing a small router by hand shows exactly how they work.

Routing with if and switch

The simplest router looks at req.method and the URL's pathname:

node · try it yourself
const http = require('node:http');

const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');
  res.setHeader('Content-Type', 'text/plain');

  if (req.method === 'GET' && pathname === '/') {
    res.end('Home page');
  } else if (req.method === 'GET' && pathname === '/about') {
    res.end('About us');
  } else {
    res.statusCode = 404;
    res.end(`No route for ${req.method} ${pathname}`);
  }
});

server.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const path of ['/', '/about?ref=menu', '/contact']) {
    const res = await fetch(base + path);
    console.log(res.status, await res.text());
  }
  server.close();
});
200 Home page
200 About us
404 No route for GET /contact

Parsing with new URL() strips the query string (?ref=menu), so /about?ref=menu still matches /about.

Tip: Always have a final "catch-all" branch that sends a 404. Without it, unknown URLs would hang forever.

A route table

Long if/else chains get messy. A cleaner approach is a table that maps "METHOD path" to a handler function:

node · try it yourself
const http = require('node:http');

const routes = {
  'GET /': (req, res) => res.end('Welcome!'),
  'GET /time': (req, res) => res.end('It is always coffee time.'),
  'POST /echo': async (req, res) => {
    let body = '';
    for await (const chunk of req) body += chunk;
    res.end(`echo: ${body}`);
  },
};

const server = http.createServer(async (req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');
  const handler = routes[`${req.method} ${pathname}`];
  if (!handler) {
    res.statusCode = 404;
    return res.end('Not found');
  }
  await handler(req, res);
});

server.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  const show = async (res) => console.log(res.status, await res.text());
  await show(await fetch(`${base}/`));
  await show(await fetch(`${base}/time`));
  await show(await fetch(`${base}/echo`, { method: 'POST', body: 'ping' }));
  await show(await fetch(`${base}/echo`)); // GET is not registered
  server.close();
});
200 Welcome!
200 It is always coffee time.
200 echo: ping
404 Not found

Adding a route is now a one-line change.

Route parameters

URLs like /users/42 or /posts/2024/hello-world carry data inside the path. Frameworks write these as patterns such as /users/:id. Modern Node (23.8+, and 22 behind a flag) — and every browser — has the global URLPattern class. A portable alternative that works everywhere is a regular expression with named groups:

node · try it yourself
const http = require('node:http');

const users = { 1: 'Ada', 2: 'Linus' };

// [method, regex, handler]
const routes = [
  ['GET', /^\/users$/, (req, res) => res.end(JSON.stringify(Object.values(users)))],
  ['GET', /^\/users\/(?<id>\d+)$/, (req, res, params) => {
    const name = users[params.id];
    if (!name) { res.statusCode = 404; return res.end('no such user'); }
    res.end(`user ${params.id} is ${name}`);
  }],
  ['GET', /^\/posts\/(?<year>\d{4})\/(?<slug>[\w-]+)$/, (req, res, p) => {
    res.end(`post "${p.slug}" from ${p.year}`);
  }],
];

const server = http.createServer((req, res) => {
  const { pathname } = new URL(req.url, 'http://localhost');
  for (const [method, pattern, handler] of routes) {
    const match = pathname.match(pattern);
    if (req.method === method && match) return handler(req, res, match.groups ?? {});
  }
  res.statusCode = 404;
  res.end('Not found');
});

server.listen(0, async () => {
  const base = `http://localhost:${server.address().port}`;
  for (const path of ['/users', '/users/2', '/users/9', '/posts/2024/hello-node', '/users/abc']) {
    const res = await fetch(base + path);
    console.log(path.padEnd(22), res.status, await res.text());
  }
  server.close();
});
/users                 200 ["Ada","Linus"]
/users/2               200 user 2 is Linus
/users/9               404 no such user
/posts/2024/hello-node 200 post "hello-node" from 2024
/users/abc             404 Not found

Notice the two different 404s: /users/9 matched a route but the user doesn't exist, while /users/abc didn't match any route because \d+ only accepts digits.

Query strings

Data after ? is not part of the route. Read it from url.searchParams:

js
const url = new URL(req.url, 'http://localhost');
// GET /search?q=node&page=2
url.searchParams.get('q');     // 'node'
Number(url.searchParams.get('page') ?? 1); // 2
url.searchParams.getAll('tag'); // all values of a repeated parameter

Routing checklist

Concern How to handle it
Unknown path respond 404 Not Found
Known path, wrong method respond 405 Method Not Allowed with an Allow header
Trailing slash (/about/) normalise it or redirect to one form
Query string ignore it when matching; read it with searchParams
Errors inside a handler wrap in try/catch and send 500

Note: Order matters in a list of routes: the first match wins. Put specific patterns before general ones.

Test yourself

Why do we parse req.url with new URL() before matching?

  1. To check the port
  2. To separate the pathname from the query string
  3. To make it lower case
  4. To decode JSON

In the regex /^\/users\/(?<id>\d+)$/, how is the id read after a match?

  1. match.id
  2. match[0]
  3. match.groups.id
  4. req.params.id

Which status code fits a known URL called with an unsupported method?

  1. 400
  2. 404
  3. 405
  4. 500