Working with Routing

1. Creating Basic Routes

MethodPurpose
app.get(path, ...handlers)HTTP GET
app.post(path, ...handlers)HTTP POST
app.put(path, ...handlers)HTTP PUT
app.patch(path, ...handlers)HTTP PATCH
app.delete(path, ...handlers)HTTP DELETE
app.head(path, ...handlers)HTTP HEAD
app.options(path, ...handlers)HTTP OPTIONS (CORS preflight)

Example: Basic CRUD

app.get("/users", (req, res) => res.json(users));
app.post("/users", (req, res) => res.status(201).json(newUser));
app.get("/users/:id", (req, res) => res.json(findUser(req.params.id)));

2. Handling All HTTP Methods

Example: app.all()

app.all("/api/*", (req, res, next) => {
  console.log(`[${req.method}] ${req.path}`);
  next();
});
Use CaseWhy app.all()
Auth checkApply to all methods on a path
LoggingMethod-agnostic instrumentation
Method-not-allowedCatch unsupported methods

3. Using Route Methods

VerbIdempotentSafeBody
GETYesYesNo
POSTNoNoYes
PUTYesNoYes (full)
PATCHNo*NoYes (partial)
DELETEYesNoOptional

4. Defining Route Paths

PatternMatches
/aboutExact
/users/:idNamed param
/users/:id?Optional param
/files/*Wildcard (Express 4); use /files/{*splat} in Express 5+ EXPRESS 5
/ab(cd)?eRegex group: /abe or /abcde
/^\/users\/\d+$/Full RegExp
Warning: Express 5 uses path-to-regexp v8 — * wildcard syntax changed to {*name}; : chars in URLs need escaping.

5. Using Route Parameters

Example: Multi-segment params

app.get("/users/:userId/posts/:postId", (req, res) => {
  const { userId, postId } = req.params;
  res.json({ userId, postId });
});
DefinitionSample URLreq.params
/u/:id/u/42{ id: "42" }
/u/:id-:name/u/42-bob{ id:"42", name:"bob" }

6. Accessing Route Parameters

PropertyDescription
req.paramsObject of named segments (always strings)
req.params[0]Wildcard / unnamed groups
req.params.splatExpress 5 named wildcard array

7. Chaining Route Handlers

Example: app.route() chain

app.route("/books/:id")
  .get(getBook)
  .put(updateBook)
  .patch(patchBook)
  .delete(deleteBook);
BenefitDetail
DRYPath declared once
CohesionAll verbs for resource together

8. Using Multiple Handler Functions

Example: Middleware chain per route

app.post("/posts",
  authenticate,
  authorize("posts:write"),
  validate(postSchema),
  rateLimit({ max: 10 }),
  createPost
);
FormEffect
Variadic argsEach runs in order; next() advances
Arrayapp.get(path, [mw1, mw2], handler)
MixedArrays + funcs combined

9. Implementing Route Arrays

Example: Multiple paths, same handler

// Express 4 syntax
app.get(["/about", "/about-us", "/info"], aboutHandler);

// Express 5 — use multiple registrations or a regex
["/about", "/about-us"].forEach(p => app.get(p, aboutHandler));
PatternPurpose
Array of pathsAliases (legacy URLs)
Array of handlersComposable middleware groups

10. Creating Modular Routes

Example: Router module

// routes/users.js
import { Router } from "express";
const router = Router();

router.get("/", listUsers);
router.post("/", createUser);
router.get("/:id", getUser);

export default router;

// app.js
import usersRouter from "./routes/users.js";
app.use("/api/users", usersRouter);
BenefitDetail
IsolationEach resource self-contained
MountablePlug router under any prefix
TestableMount on a fresh app for unit tests