What is middleware in Express? What does next() do, why does the order of app.use calls matter, and what is the difference between application-level and route-level middleware?
Show the explanation
Model answer. Middleware is a function (req, res, next) => {} that runs during the request–response cycle. Each one can read or change req/res, end the response, or call `next()` to pass control to the next middleware.
const app = express();
app.use(express.json()); // application-level: every request
app.use((req, res, next) => { // logging
const start = Date.now();
res.on('finish', () => console.log(req.method, req.url, res.statusCode, Date.now() - start, 'ms'));
next();
});
const requireLogin = (req, res, next) => (req.user ? next() : res.status(401).json({ error: 'Sign in' }));
app.get('/account', requireLogin, (req, res) => res.json(req.user)); // route-level- Order matters: middleware runs in the order it is registered. A body parser must come before the routes that read
req.body; a 404 handler goes after all routes. - If a middleware neither responds nor calls
next(), the request hangs. - Application-level middleware (
app.use(fn)) applies to all routes, or to a path prefix (app.use('/api', fn)). Route-level middleware is passed to specific routes, or to anexpress.Router(). - Calling
next(err)skips to the error-handling middleware.
Original UniCircle question. Last reviewed 22 Oct 2026.
