Skip to content

Express Routing

beginner2 min read
  • Express
  • Node.js
  • HTTP

How Express matches an incoming HTTP method and path to a handler, including route parameters and modular routers for organising endpoints.

Prerequisites

  • Express basics and HTTP methods (see Related Topics)

What you'll understand

  • How Express matches a request to a handler by method and path
  • How route parameters capture values from the URL
  • How routers group related endpoints into modules

Explanation

Routing is how Express decides which handler runs for a given request. Each route pairs an HTTP method with a path, such as GET /users or POST /orders. When a request arrives, Express walks its routes in order and runs the first handler whose method and path match. Because reads, creates, and deletes use different methods, the same path can have several handlers.

Paths can contain parameters, named segments that capture part of the URL. A route for /users/:id matches /users/42 and exposes 42 as req.params.id. This is how you address a specific resource. Parameters keep routes declarative: you describe the shape of the URL once rather than parsing it yourself.

As an app grows, defining every route on the main app becomes unwieldy. Express Routers let you group related routes into their own module, a users router, an orders router, and mount each under a base path. This keeps files focused and makes the API's structure obvious from how the routers are mounted.

Examples

This TypeScript example defines a route with a parameter and reads it from req.params:

app.get('/users/:id', (req, res) => {
  const { id } = req.params;
  res.json({ id });
});

This example groups user routes in a Router and mounts it under /users:

import { Router } from 'express';

const users = Router();
users.get('/', listUsers);       // GET /users
users.get('/:id', getUser);      // GET /users/:id
users.post('/', createUser);     // POST /users

app.use('/users', users);

Common mistakes

  • Declaring a broad route before a specific one so the specific route never matches.
  • Forgetting that method matters; GET /users and POST /users are different routes.
  • Reading a parameter under the wrong name; :id is req.params.id, not req.params.userId.
  • Putting every route in one file instead of grouping them with routers.

Best practices

  • Order routes from most specific to most general.
  • Use route parameters for resource identifiers rather than parsing the URL manually.
  • Group related endpoints into routers and mount them under a clear base path.
  • Keep paths as resource nouns and let the HTTP method express the action (see Related Topics).

Further reading

Related topics

Express Routing — Padlor · Padlor