Routing in Express

Map URL Patterns to Handler Functions

Routing in Express

Methods, paths, params, query strings, route files — the essentials.

4 min read Level 1/5 #nodejs#express#routing
What you'll learn
  • Use app.METHOD for each verb
  • Capture path params with :name
  • Organize routes with express.Router

Routing maps HTTP method + path → handler. Express makes it delightful.

Methods

app.get("/users",  handler);
app.post("/users", handler);
app.put("/users/:id", handler);
app.patch("/users/:id", handler);
app.delete("/users/:id", handler);

app.all("/admin/*splat", requireAdmin);   // any method

Path Params

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

app.get("/posts/:postId/comments/:commentId", (req, res) => {
  res.json(req.params);
  // { postId: '...', commentId: '...' }
});

Multiple params, all on req.params.

Query Strings

app.get("/search", (req, res) => {
  const { q, limit = 10 } = req.query;
  res.json({ q, limit });
});

// GET /search?q=express&limit=20
// { q: "express", limit: "20" }

Note query values are always strings — coerce explicitly.

Route Files with Router

For non-trivial apps, split routes per resource:

// routes/users.mjs
import { Router } from "express";

const r = Router();

r.get("/",       listUsers);
r.post("/",      createUser);
r.get("/:id",    getUser);
r.patch("/:id",  updateUser);
r.delete("/:id", deleteUser);

export default r;
// app.mjs
import express from "express";
import users from "./routes/users.mjs";

const app = express();
app.use("/api/users", users);

All routes inside users.mjs get prefixed with /api/users.

Route Order Matters

Express matches in declaration order. First match wins.

app.get("/users/me", getCurrentUser);    // ✓ more specific first
app.get("/users/:id", getUserById);

Swap them and me is parsed as :id — bug.

Async Handlers

Express 5 awaits async handlers and forwards rejections to error middleware:

app.get("/users/:id", async (req, res) => {
  const user = await db.findUser(req.params.id);
  if (!user) {
    res.status(404).json({ error: "not found" });
    return;
  }
  res.json(user);
});

On Express 4 you need express-async-handler to get the same.

Middleware →