Lesson 4 of 8 · 11 min · Building APIs with Express

Express 5: routing and middleware

Covers: Express 5 on Node.js 22 or newer. Updated 13 Nov 2026. Part of the Full Stack Developer roadmap.

What you will learn

  • Create an Express 5 server and define routes
  • Read route parameters, query strings and request bodies
  • Organise code with express.Router
  • Understand middleware, its order and next()
  • Use common middleware (JSON parsing, CORS, security headers, logging) and write your own

In simple words

Express is a small framework for building web servers and APIs in Node.js. You tell it: "when someone sends a GET request to /orders, run this function". Middleware are the checkpoints in between: small functions that every request passes through in order, such as one that reads the JSON body, one that checks the login and one that logs the request, before reaching the function that answers.

Words to know

  • Route: a rule matching an HTTP method and path to a handler function.
  • Handler: the function that receives the request and sends the response.
  • Middleware: a function that runs between receiving a request and sending a response.
  • Router: a mini application that groups related routes.

A first Express app

npm init -y
npm install express            # Express 5 is the default version on npm
// src/server.js   ("type": "module" in package.json)
import express from "express";

const app = express();
app.use(express.json());                         // parse JSON request bodies

app.get("/health", (req, res) => {
  res.json({ status: "ok" });
});

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

const port = Number(process.env.PORT ?? 3000);
app.listen(port, () => console.log(`API listening on http://localhost:${port}`));

Express 5 requires Node.js 18 or newer. Run it with node --watch src/server.js, and call it with curl localhost:3000/health.

Routing

A route is app.METHOD(path, ...handlers):

app.get("/orders", listOrders);
app.post("/orders", createOrder);
app.put("/orders/:id", replaceOrder);
app.patch("/orders/:id", updateOrder);
app.delete("/orders/:id", deleteOrder);
app.all("/ping", (req, res) => res.send("pong"));       // any method

Reading the request:

app.get("/customers/:customerId/orders/:orderId", (req, res) => {
  const { customerId, orderId } = req.params;           // from the path (strings)
  const { status, page = "1" } = req.query;             // from ?status=paid&page=2 (strings)
  const token = req.get("Authorization");               // a header
  res.json({ customerId, orderId, status, page });
});

app.post("/orders", (req, res) => {
  const body = req.body;                                // parsed JSON (needs express.json())
  res.status(201).location("/orders/101").json({ id: 101, ...body });
});

Sending the response (once per request): res.json(obj), res.send(text), res.status(404).json({...}), res.sendStatus(204), res.redirect(302, "/new"), res.sendFile(path), res.download(path), res.set("Cache-Control", "no-store"), res.cookie(...). Handlers must end the request, or the client waits forever.

Path patterns in Express 5

Express 5 uses a stricter path syntax (from the official migration guide):

Express 4 Express 5
/* /*splat (wildcards must be named); /{*splat} also matches the root
/:file.:ext? /:file{.:ext} (braces for optional parts)
regex characters in paths not supported: use an array of paths

Also, req.query is a read-only getter and the default query parser is simple; req.body is undefined (not {}) when no body parser ran; some old methods are removed (app.del() is app.delete(), res.json(obj, status) is res.status(status).json(obj), res.redirect(url, status) is res.redirect(status, url)).

Parameter validation with app.param

app.param("id", (req, res, next, value) => {
  if (!/^\d+$/.test(value)) return res.status(400).json({ error: "id must be a number" });
  next();
});

(Validation libraries, next lesson, are usually better.)

Routers: modular code

Split routes by feature so server.js stays small:

// src/routes/orders.js
import { Router } from "express";
import * as orders from "../controllers/orders.js";

const router = Router();
router.get("/", orders.list);
router.post("/", orders.create);
router.get("/:id", orders.get);
router.delete("/:id", orders.remove);
export default router;

// src/server.js
import ordersRouter from "./routes/orders.js";
app.use("/api/orders", ordersRouter);           // mounted at a prefix

A typical structure:

src/
  server.js          (create the app, global middleware, mount routers, start)
  app.js             (export the app without listening: easy to test)
  routes/            (URL mapping)
  controllers/       (HTTP: read request, call services, send response)
  services/          (business logic)
  repositories/      (database access)
  middleware/        (auth, validation, errors)

Same layering as the Spring Boot course: keep controllers thin. Export the app from one file and call listen in another, so tests can use supertest against the app without opening a port.

Middleware

Middleware are functions (req, res, next) that run in the order you register them. Each one can read or change req and res, end the response, or call next() to pass control onward:

app.use((req, res, next) => {
  req.startedAt = Date.now();
  res.on("finish", () => {
    console.log(`${req.method} ${req.originalUrl} ${res.statusCode} ${Date.now() - req.startedAt}ms`);
  });
  next();                                        // without this the request hangs
});

How a request flows:

request -> logger -> express.json() -> auth -> router -> handler -> response
                                         |
                       (can end here with a 401 and never reach the handler)

Levels of middleware:

  • Application level: app.use(fn) or app.use("/api", fn) for every request or a path prefix.
  • Router level: router.use(fn) for one feature.
  • Route level: passed before the handler: app.get("/admin", requireAdmin, handler) (several can be chained).
  • Error-handling middleware: four arguments (err, req, res, next) (the next lesson).
  • Built-in: express.json(), express.urlencoded({ extended: false }), express.static("public"), express.text(), express.raw().
  • Third-party: from npm.

Order matters. Body parsers must come before routes that read req.body; authentication before protected routes; the error handler last; the 404 handler after all routes.

app.use(helmet());
app.use(cors({ origin: ["https://app.example.com"], credentials: true }));
app.use(express.json({ limit: "100kb" }));
app.use(requestLogger);
app.use("/api", rateLimiter);
app.use("/api/orders", ordersRouter);
app.use((req, res) => res.status(404).json({ error: "Not found" }));     // after all routes
app.use(errorHandler);                                                    // last

Essential middleware

Package Purpose
express.json() parses JSON bodies (set a limit; the default is 100kb)
cors sets CORS headers from an allow-list (see the CORS lesson)
helmet sets security headers (CSP, X-Content-Type-Options, HSTS and more)
morgan or pino-http request logging (prefer structured logs)
compression gzip responses (or do it in the reverse proxy)
express-rate-limit limits requests per client, especially on login
cookie-parser, express-session cookies and server sessions
multer or busboy file uploads
passport authentication strategies
express-validator, zod request validation

Behind a reverse proxy or load balancer, set app.set("trust proxy", 1) so req.ip and req.protocol reflect the real client; otherwise rate limiting and secure cookies misbehave. Disable the X-Powered-By header (app.disable("x-powered-by"), which Helmet also does).

Writing your own middleware

A factory returns a configured middleware:

export function requireRole(role) {
  return (req, res, next) => {
    if (!req.user) return res.status(401).json({ error: "Sign in required" });
    if (req.user.role !== role) return res.status(403).json({ error: "Not allowed" });
    next();
  };
}
app.delete("/api/orders/:id", requireAuth, requireRole("admin"), deleteOrder);

Pass data to later handlers on req (or res.locals): req.user, req.requestId. With TypeScript, extend the Request type. Give each request an id (crypto.randomUUID()), return it in a header, and include it in logs, so you can trace a failing call.

Async middleware and handlers in Express 5: a rejected promise (or an error thrown in an async function) is passed to the error handler automatically, as if you had called next(err). In Express 4 you needed wrappers or .catch(next):

app.get("/orders/:id", async (req, res) => {
  const order = await orderService.get(Number(req.params.id));     // a rejection goes to the error handler
  res.json(order);
});

Static files and templates

app.use(express.static("public", { maxAge: "1d" })) serves files such as a built React app (dist). For a single-page app, serve index.html for unknown non-API paths:

app.use(express.static("dist"));
app.get("/{*splat}", (req, res) => res.sendFile(path.resolve("dist/index.html")));    // Express 5 wildcard syntax

Server-rendered HTML with template engines (EJS, Pug, Handlebars) is also supported; many teams serve the front end from a CDN and keep Express for the API.

Common mistakes

  • Forgetting next() or not sending a response, so requests hang.
  • Registering body parsers or auth after the routes that need them.
  • Sending two responses for one request ("Cannot set headers after they are sent"; use return res...).
  • Using Express 4 path patterns (/*, ?, regex) in Express 5.
  • Business logic in route handlers.
  • No 404 handler or no error handler.
  • Wide-open CORS (origin: "*" with credentials) and no body size limit.
  • Not setting trust proxy behind a load balancer.

Try it yourself

  1. Build an Express 5 server with /health and a router for /api/orders with the five REST routes returning in-memory data.
  2. Add a request-logging middleware that prints method, URL, status and duration.
  3. Add helmet, cors with an allow-list and express.json({ limit }).
  4. Write requireAuth and requireRole middleware and protect a route.
  5. Break the order of middleware on purpose (routes before express.json()) and see req.body be undefined.

Check yourself

What is middleware in Express?

A function (req, res, next) that runs in order for matching requests; it can modify the request or response, end the response, or call next() to continue.

Why does the order of app.use and routes matter?

Requests flow through middleware and routes in registration order, so parsers and authentication must come before the routes that depend on them, and the error handler last.

What happens if a middleware neither calls next() nor sends a response?

The request hangs until the client times out.

How do you structure routes in a larger app?

With express.Router per feature, mounted under a prefix with app.use("/api/orders", router), with controllers and services separated.

Interview questions

Explain the Express request-response cycle.

A request enters the app, passes through the middleware stack in order (parsing, logging, authentication), is matched to a route and handler, which sends a response; errors skip to the error-handling middleware.

What changed in Express 5?

Rejected promises in handlers and middleware are forwarded to error handlers automatically, path-matching syntax is stricter (named wildcards, braces for optional segments), req.query is a getter, several deprecated methods were removed, and Node.js 18 or newer is required.

How do you handle security in an Express app?

Use Helmet, a CORS allow-list, body size limits, rate limiting, input validation, secure cookies and sessions or token auth, HTTPS behind a proxy with trust proxy, and keep dependencies updated.

Summary

  • Define routes with app.METHOD(path, handler); read req.params, req.query, req.body; respond once.
  • Organise by Router, controllers and services; export app for testing.
  • Middleware runs in order and either responds or calls next(); put parsers, security and auth first and the 404 and error handlers last.
  • Express 5 forwards async errors automatically and uses stricter path syntax.

Going deeper

See how much of this you can explain

A free mock interview asks you new questions on Node.js and Express backends for Full Stack Developer and scores every answer, with what to fix.