Middleware
In a web backend, middleware is code that runs as part of handling a request. It lets multiple routes share work such as logging, checking who the caller is, or setting response headers.
Also known as: мидлвар, промежуточное ПО
What is middleware?
Suppose every endpoint in an API needs to record how long it took to respond. Rather than add timing code to each endpoint, you can put it in middleware and register it once. The route handler can then focus on its own job, such as looking up an order or creating a comment.
Middleware also has a broader meaning in software architecture: it can refer to software that helps separate applications communicate, such as a message broker. In a discussion about an HTTP framework, the term usually means code that runs inside the application's request pipeline.
How the pipeline works
A framework runs the middleware that applies to a request in a defined order. A middleware component can pass control to the next step or end the request itself. For example, a rate limiter can return 429 Too Many Requests without running the route handler. Depending on the framework, you can register middleware for the whole application, a group of routes, or a single route.
Some frameworks let each middleware component wrap the next step. If A wraps B and B wraps the handler, the normal sequence is A before, B before, handler, B after, A after. This is sometimes called the onion model. Don't assume that every next() API works this way: handing off control is not necessarily the same as waiting for a response.
Example: timing requests in Express
app.use((req, res, next) => {
const started = Date.now();
res.once('finish', () => {
console.log(req.method, res.statusCode, Date.now() - started);
});
next();
});
Register this before the routes you want to measure. The callback logs the method, status code, and elapsed milliseconds when the response emits finish. Logging immediately after next() could miss time spent in an asynchronous handler. The finish event describes completion on the server side; it does not prove that the client received the response.
Common mistakes and interview scenarios
If Express middleware neither sends a response nor calls next(), the request can hang. Calling next() after sending a final response is also a mistake: a later handler might try to send another one. Keep business rules in the appropriate application code. For example, checking whether an order is still eligible for a refund belongs with the refund operation, not in middleware shared by unrelated routes.
Interviewers often ask you to trace a request that ends early. If the pipeline runs a logger, then a rate limiter, then a route handler, a 429 skips the handler but can still be logged by a listener the logger registered earlier. If you put the logger after the limiter, it won't see those rejected requests.