Code Reference

Express Routing

Node.js · Reference cheat sheet

Express Routing

Node.js · Reference cheat sheet


📋 Overview

Express matches HTTP method + path patterns to handlers. Use Router to split large apps into mountable modules.

🔧 Core concepts

PatternMatches
/usersExact path
/users/:idParam req.params.id
/files/*Wildcard (version-dependent syntax)
/ + Router mountPrefixed paths
APIRole
app.METHOD(path, ...handlers)Method-specific
app.allAny method
router.route(path)Chain verbs for one path
req.params / req.queryPath params / query string

💡 Examples

Params and query:

app.get("/users/:id", (req, res) => {
  res.json({ id: req.params.id, q: req.query.q });
});
// GET /users/42?q=active

Router module:

import { Router } from "express";

const users = Router();
users.get("/", (req, res) => res.json([]));
users.get("/:id", (req, res) => res.json({ id: req.params.id }));

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

Route chaining:

router
  .route("/items/:id")
  .get((req, res) => res.send("get"))
  .put((req, res) => res.send("put"))
  .delete((req, res) => res.send("delete"));

⚠️ Pitfalls

  • More specific routes must be registered before generic /:id catchers.
  • req.params values are strings — coerce IDs explicitly.
  • Trailing-slash behavior depends on settings; be consistent in clients and routes.

On this page