What is Express middleware
the core Express request pipeline.
middleware are functions in a chain with req, res, next, they inspect or modify request and response, then call next to continue or send a response to end.
WHAT THIS TESTS This checks the central abstraction of Express. Everything in Express, including routing and the built-in parsers, is middleware, so understanding it is foundational.
A GOOD ANSWER COVERS Middleware are functions that execute in order during the lifecycle of a request, forming a pipeline between the incoming request and the final response. Each receives three parameters. req is the request object representing the incoming HTTP request; middleware can read it and attach data to it, for example setting req.user after authentication. res is the response object; middleware can set headers, a status, or send the response. next is a function that, when called with no arguments, hands control to the next middleware or route handler in the stack; called with an argument it forwards an error to the error-handling middleware. The essential rule is that each middleware must either terminate the request by sending a response or call next to continue. If it does neither, the request hangs forever because nothing finishes or advances it.
COMMON WRONG ANSWERS Thinking middleware only means third-party plugins, missing that route handlers and parsers are middleware too. Forgetting to call next, so the chain stalls. Believing you should call next after already sending a response, which causes errors.
LIKELY FOLLOW-UPS How does the order of app.use calls affect execution. What is the difference between application-level and router-level middleware. How does next(err) differ from next().
ONE CONCRETE EXAMPLE A logging middleware: app.use((req, res, next) => { console.log(req.method, req.url); next(); });. It reads req to log the method and URL, does not touch res, and calls next so the request proceeds to the actual handler. Drop the next() call and every request would log once then hang with no response.
Read the original → expressjs.com
Get five bites like this every day.
Tezvyn delivers a daily feed of 60-second tech bites with quizzes to lock in what you learn.