What Is Middleware? Ordering and Error Handling in an Express Request Pipeline
Middleware is a component that inspects or changes a request or response during web request processing, passes control to the next step, or ends the response. In Express, middleware runs in registration order. Put functions such as JSON parsing or authentication before the routes that need them, and put error-handling middleware after them. The code and behavior in this article are scoped to Express 5.
Middleware is a component that inspects or changes a request or response during web request processing, passes control to the next step, or ends the response. In Express, middleware runs in registration order. Put functions such as JSON parsing or authentication before the routes that need them, and put error-handling middleware after them. The code and behavior in this article are scoped to Express 5.
What does middleware do in request processing?
An Express middleware function receives the request object req, response object res, and next, which passes control to the next middleware. It can log, inspect or modify the request and response, finish the response, or continue to the next step. Application-level middleware is attached with app.use() or an HTTP method handler; an optional path can limit which requests use it. (Express: Using middleware)
Middleware functions form a chain. If the current function does not finish the response, it must call next() to continue. Doing neither can leave the request waiting. Calling next() after sending the response can cause a later step to try to write to an already completed response, so make the decision to finish or continue explicit on each path. (Express: Writing middleware)
Why does registration order matter?
Express runs middleware in the order it is registered. If an earlier step ends the response, later steps do not run. For example, register express.json() before a route that reads the parsed req.body. Authentication middleware must also precede the protected routes; registering it afterward means those routes will not pass through that check. (Express: Using middleware, Express: Writing middleware)
Order also matters for errors. In Express 5, error-handling middleware is generally registered after routes and regular middleware. It must have four parameters, (err, req, res, next), so Express recognizes it as an error handler. If it cannot handle the error, or response headers have already been sent, it can pass the error to the default handler with next(err). (Express: Error handling)
How do you build a minimal Express 5 middleware chain?
This example logs a request, registers the JSON body parser, then defines a sample route and a final error handler. Order is the key point. In a real service, design logging of private or secret data, input validation, authentication and authorization, and error responses for the application's requirements.
const express = require('express');
const app = express();
app.use((req, res, next) => {
console.log('Request:', req.method, req.path);
next();
});
app.use(express.json());
app.post('/items', (req, res) => {
res.status(201).json({ accepted: true });
});
app.use((err, req, res, next) => {
if (res.headersSent) {
return next(err);
}
res.status(500).json({ error: 'Internal server error' });
});
app.listen(3000);This is an illustrative Express 5 syntax example, not code that was run or verified. The project that starts the server must have Express 5 installed. After starting with app.listen(3000), a POST /items request with a Content-Type: application/json header and a JSON body is written to return 201 and {"accepted":true}. That is the expected behavior from the code, not an observed result. This route does not handle other paths; add suitable routes or a 404 handler.
In Express 5, a rejected Promise or thrown error from middleware or a route that returns a Promise is forwarded to the error flow through next(error). Callback-based asynchronous APIs may deliver errors through their own callback, so they may need explicit forwarding. Do not assume asynchronous work is handled automatically if its Promise is not returned. (Express: Error handling)
How should errors and response completion be handled?
Calling next(error) in regular middleware skips the normal handling steps and sends control to error-handling middleware. The handler must use (err, req, res, next) and is placed after routes. Do not expose internal stack traces or sensitive details to users; use a safe response and server-side records according to the service's requirements. (Express: Error handling)
If an error occurs after response headers have been sent, do not try to send a new status or body; pass it to the default handler with next(err). For paths such as streaming, where a failure can happen after part of the response was sent, account for connection closure or partial output. Avoid forwarding the same error multiple times, and make sure only one path finishes the response. (Express: Error handling)
What should you check when adding or debugging middleware?
Check whether middleware applies to the whole app or only to a mounted path.
Review the order of body parsing, authentication, authorization, routes, 404 handling, and error handling.
Confirm that each regular middleware either finishes the response or calls `next()`, and that one request is not completed through two paths.
If a request hangs, check whether an earlier middleware forgot `next()` or failed to finish the response.
If an error continues through regular routes, check the use of `next(err)` and the four-argument error-handler signature.
Check the error-handling rules for the installed Express major version. Promise error forwarding differs by version.
Make sure logs and error responses do not contain authentication tokens, passwords, or personal information.