Working with Routing
1. Creating Basic Routes
| Method | Purpose |
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 Case | Why app.all() |
| Auth check | Apply to all methods on a path |
| Logging | Method-agnostic instrumentation |
| Method-not-allowed | Catch unsupported methods |
3. Using Route Methods
| Verb | Idempotent | Safe | Body |
| GET | Yes | Yes | No |
| POST | No | No | Yes |
| PUT | Yes | No | Yes (full) |
| PATCH | No* | No | Yes (partial) |
| DELETE | Yes | No | Optional |
4. Defining Route Paths
| Pattern | Matches |
/about | Exact |
/users/:id | Named param |
/users/:id? | Optional param |
/files/* | Wildcard (Express 4); use /files/{*splat} in Express 5+ EXPRESS 5 |
/ab(cd)?e | Regex 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 });
});
| Definition | Sample URL | req.params |
/u/:id | /u/42 | { id: "42" } |
/u/:id-:name | /u/42-bob | { id:"42", name:"bob" } |
6. Accessing Route Parameters
| Property | Description |
req.params | Object of named segments (always strings) |
req.params[0] | Wildcard / unnamed groups |
req.params.splat | Express 5 named wildcard array |
7. Chaining Route Handlers
Example: app.route() chain
app.route("/books/:id")
.get(getBook)
.put(updateBook)
.patch(patchBook)
.delete(deleteBook);
| Benefit | Detail |
| DRY | Path declared once |
| Cohesion | All 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
);
| Form | Effect |
| Variadic args | Each runs in order; next() advances |
| Array | app.get(path, [mw1, mw2], handler) |
| Mixed | Arrays + 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));
| Pattern | Purpose |
| Array of paths | Aliases (legacy URLs) |
| Array of handlers | Composable 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);
| Benefit | Detail |
| Isolation | Each resource self-contained |
| Mountable | Plug router under any prefix |
| Testable | Mount on a fresh app for unit tests |