The one-line mental model
Express is a thin routing layer over Node's HTTP server: every incoming request walks an ordered list of middleware functions until one of them sends a response, and the order you register them is the order in which your logic runs.
After this lesson you will be able to predict which handler wins for a given URL, write middleware that handles errors uniformly, validate input before it reaches your database, and split a growing API into routers without breaking a single path.
Prerequisites
- !Node.js fundamentals: modules, callbacks and the http module
- !HTTP verbs, status codes and JSON request bodies
What You'll Learn
- 1Trace a request through Express middleware and route layers
- 2Write synchronous and asynchronous error handling correctly
- 3Design REST endpoints with sensible status codes and validation
- 4Organise a project with routers, controllers and error boundaries
What happens between req and res
An Express application is a function. When you call app.listen(3000) you are handing Node's createServer a callback that runs your middleware stack for every request. Express maintains an internal array of layers, each holding either a path pattern and a handler, or a bare function with no path that runs for everything. The library walks that array from index zero, calls each layer, and stops as soon as a layer calls res.end or res.send. If a layer calls next(), walking continues.
This design explains three behaviours that surprise newcomers. A middleware registered after your routes never runs for those routes, because the response already ended. A route registered as app.get('/orders') will not match POST /orders, so method mismatches fall through to your 404 handler rather than producing a 405. And a handler that forgets both res.send and next() leaves the request hanging until a proxy or browser times out, which looks like an outage even though nothing crashed.
Express also distinguishes handler arity: an error handler is any function with four parameters, function (err, req, res, next). Throwing or calling next(err) skips remaining regular layers and jumps straight to the first four-argument function in the stack.
Matching order decides your behaviour
Route patterns are compared in registration order, and the first match wins. That makes specificity less important than position, which is why a catch-all registered too early silently shadows everything after it.
import express from 'express';
const app = express();
app.use(express.json({ limit: '1mb' }));
// Registered first: runs for every request, never terminates
app.use((req, res, next) => {
console.log(`${new Date().toISOString()} ${req.method} ${req.originalUrl}`);
next();
});
// Literal path, matched before the parameterised route below
app.get('/orders/summary', (req, res) => {
res.json({ total: 12840, currency: 'EUR' });
});
// Parameter route: only reached when the literal above did not match
app.get('/orders/:id', (req, res) => {
const id = Number(req.params.id);
if (!Number.isInteger(id)) return res.status(400).json({ error: 'bad id' });
res.json({ id, status: 'shipped' });
});
// Mounting a router keeps resource paths in one place
const reports = express.Router();
reports.get('/', (req, res) => res.json([]));
reports.get('/:slug', (req, res) => res.status(404).json({ error: 'unknown report' }));
app.use('/api/reports', reports);
// Registered last: only reached when nothing above sent a response
app.use((req, res) => res.status(404).json({ error: 'not found' }));
Two patterns are worth memorising. Mounting a router with app.use('/api/reports', router) strips the prefix before the router matches, so inside the router the root path is /. Wildcards such as app.get('/files/*') should sit near the end, or they will intercept more specific routes that you registered later.
Middleware, stack discipline and error paths
Middleware is where Express earns its reputation. Logging, authentication, body parsing, rate limiting and multi-tenancy all plug in as functions with the same signature, which lets you compose them and reuse them across applications.
import express from 'express';
const app = express();
function requireAuth(req, res, next) {
const header = req.headers.authorization || '';
const token = header.startsWith('Bearer ') ? header.slice(7) : null;
if (!token) return res.status(401).json({ error: 'missing token' });
if (token !== process.env.API_TOKEN) return res.status(403).json({ error: 'invalid token' });
req.user = { id: 'svc-1', scope: 'read:orders' };
next();
}
// Async handlers must forward rejections, otherwise the process crashes
const wrap = (fn) => (req, res, next) => Promise.resolve(fn(req, res, next)).catch(next);
app.use(requireAuth);
app.get('/api/orders', wrap(async (req, res) => {
const page = Math.max(1, Number(req.query.page) || 1);
const limit = Math.min(100, Number(req.query.limit) || 20);
res.json({ page, limit, items: [] });
}));
// Four-argument function: Express treats this as the error boundary
app.use((err, req, res, next) => {
if (err.type === 'entity.parse.failed') {
return res.status(400).json({ error: 'malformed json body' });
}
console.error(err);
res.status(err.status || 500).json({ error: 'internal error' });
});
app.listen(3000);
Notice that requireAuth returns early on failure without calling next(), which is what actually stops the pipeline. The wrapper around async handlers solves the ugliest class of Express bugs: an unhandled promise rejection inside an async route used to become an uncaught exception instead of a 500 response.
Reading input without trusting it
Everything a client sends is hostile until validated: query strings arrive as strings, JSON bodies can be arbitrarily deep, and headers are attacker-controlled. Validation belongs as early as possible, before your controllers, because by then the data has usually been through destructuring, defaults and type coercion that hide the original mistake.
Treat each input channel differently. Path parameters define identity, so reject anything that is not the shape you expect, such as an integer id where the client sent a script tag. Query parameters carry pagination and filters, so bound them: a limit of 100000 from an anonymous caller is a denial-of-service request dressed as a feature. Body payloads define mutations, so check required fields, types and value ranges, and reject unknown keys outright rather than silently persisting them. Header values are for transport concerns such as correlation ids and content negotiation, never for business rules, because proxies rewrite them freely.
The most durable approach is a schema in one place: parse with a library, get back typed and trimmed values, and pass only that object downstream. Controllers that receive already-validated input stay short, and a single schema doubles as documentation of the API contract. Pair it with a body size limit at the Express level so oversized payloads never reach your parser at all.
Status codes and shapes clients can rely on
REST APIs fail in two ways: the client sent something wrong, or the server could not fulfil a valid request. Mapping that distinction onto status codes costs nothing and saves your consumers hours of debugging.
| Situation | Status | Body shape to return |
|---|---|---|
| Resource created by a POST | 201 | The created object plus a Location header |
| DELETE that succeeded with no body | 204 | Empty body, no content-type |
| Unknown route or missing record | 404 | {"error": "..."} with a stable machine code |
| Validation failure with field details | 400 | {"error": "invalid", "fields": {...}} |
| Authenticated but not permitted | 403 | {"error": "forbidden"} |
| Transient upstream or database failure | 500 | Generic message; details go to your logs only |
Pick one JSON envelope and never deviate. Consumers that must distinguish "field X is wrong" from "server exploded" can then branch on HTTP status alone, and your error middleware becomes the single place where the envelope is produced.
Structuring an app that will not collapse
Small examples put everything in one file; production services need seams. A practical layout separates routing declarations, request handling, domain logic and infrastructure access, so each can be tested in isolation.
src/
āāā server.js # reads config, builds the app, starts listening
āāā app.js # assembles middleware and routers, no listen()
āāā routes/
ā āāā orders.js # path patterns and status codes only
ā āāā reports.js
āāā controllers/
ā āāā orders.js # parse input, call services, shape responses
āāā services/
ā āāā orders.js # business rules, no Express types in signatures
āāā repositories/
ā āāā orders.js # SQL or ORM calls, returns plain objects
āāā middleware/
āāā request-log.js
āāā require-auth.js
āāā error-handler.js
The dependency direction runs downward: routes know controllers, controllers know services, services know repositories. Nothing below the controller layer should ever see req or res, which is what makes business logic testable without spinning up a server. Keep app.js free of listen() so integration tests can mount the app with supertest on an ephemeral port.
Graceful shutdown is part of structure too. When the process receives a termination signal, stop accepting new connections, wait for in-flight requests to finish with a deadline, then close the database pool and exit. Without that sequence an orchestrator rolling your deployment will cut long-running requests in half and turn a routine deploy into user-visible errors. Bind the handler in server.js, keep the timeout shorter than the platform's kill grace period, and make sure your health endpoint flips to unhealthy the moment draining starts so load balancers stop routing to that instance.
Common Mistakes
Registering a global 404 handler before your API routes
Fix: Mount routes first and place the not-found middleware immediately before the error handler
Forgetting to forward rejections from async handlers
Fix: Wrap every async handler so Promise rejections call next(err)
Reading req.body without express.json, producing undefined fields
Fix: Register body parsing middleware at app level before any router
Returning 200 with an error field for validation failures
Fix: Return 400 with a machine-readable error code so clients and gateways can react
Best Practices
- Use Express Router per resource and mount each with a clear prefix
- Centralise error formatting in one four-argument middleware
- Validate and sanitise input in middleware or a schema layer before controllers run
- Log request id, method, path and duration on every response
- Keep framework types out of services so domain tests run without a server
Interview Questions
Q1: How does Express decide which route handles a request?
It walks layers in registration order and uses the first one whose path pattern and HTTP method match, which is why ordering matters more than pattern specificity.
Q2: What makes a function an error-handling middleware?
It declares exactly four parameters: err, req, res, next. Express only invokes it when next(err) is called or a synchronous throw occurs inside a layer.
Q3: Why do async route handlers need a wrapper?
A rejected promise inside an async function is not seen by Express, so the wrapper catches it and forwards to next(err) instead of crashing the process.
Q4: Where should authentication middleware be registered?
On the router or path prefix it protects, not globally with exceptions, so protected and public routes are declared explicitly and reviewable at a glance.
Key Takeaways
- Express is an ordered layer stack; the first matching route wins and everything else falls through
- Middleware stops a pipeline by not calling next, and redirects it by calling next(err)
- Four-parameter functions are the error boundary; async handlers need explicit rejection forwarding
- A single response envelope plus correct status codes is most of a usable API contract
- Separate routes, controllers, services and repositories so logic is testable without HTTP