Express routing and middleware
Framework lane: Express 5.x (Supertest required for integration test). Exact supported patch, dependency lock, advisory review and execution are NOT RUN. The framework code is a static candidate; do not install dependencies or expose a server automatically. The local companion uses Node.js 22.16.0 and requires no third-party packages.
Framework example — staged
import express from 'express';const app = express();app.use('/catalog', (req, res, next) => { res.set('X-Catalog', 'demo'); next();});app.get('/catalog/:id', (req, res) => { if (req.params.id !== 'p1') return res.sendStatus(404); res.json({ id: 'p1', title: 'Notebook' });});export default app;Expected behavior (not observed): GET /catalog/p1 should return 200, the item JSON and X-Catalog: demo. GET /catalog/p2 should return 404.
How it works
Method and path select a route; query parameters are separate from the path. Register shared middleware before the routes it should affect. A parameter such as :id captures text, not a validated number. Router mounting adds a path prefix. Express 5 changed wildcard and optional path syntax; review migration guidance instead of copying Express 4 patterns.
Practice the underlying idea without dependencies
const url = new URL('/catalog/p1?view=short', 'http://example.test');const [, collection, id] = url.pathname.split('/');console.log(collection, id, url.searchParams.get('view'));Run node main.mjs in a disposable directory. Expected output:
catalog p1 shortThis tests the illustrated JavaScript behavior only, not the framework.
Common mistake
Calling next() after sending a terminal response can trigger another handler. Return after sending, or call next() only when the current middleware is not finishing the response.
Apply it yourself
Predict whether GET /catalog/p1?view=full and POST /catalog/p1 match the GET handler. Then plan a second GET handler for the collection.
Further reading
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Express routing and middleware — knowledge check
Apply the lesson’s contracts and identify common boundary mistakes.
What does :id capture for /catalog/p1?
What happens to the X-Catalog header for a matching GET?
How should a handler continue after sending a final response?