Node.js › Express & Middleware

What is middleware in Express, and what is the significance of the order in which middleware is registered?

Intermediate

Answer

Middleware functions receive the request, response, and a 'next' callback, executed in the exact order they're registered via app.use() or as route-specific handlers -- order matters critically because each middleware can modify the request/response objects or short-circuit the chain entirely before it reaches later middleware or the final route handler, meaning something like an authentication check must be registered before any route it's meant to protect.
app.use(express.json()); // must come before routes that read req.body
app.use(loggingMiddleware); // logs every request
app.use('/admin', requireAuth); // only applies to routes starting with /admin
app.get('/admin/dashboard', (req, res) => res.json(dashboardData)); // protected by the above
Real-world example A team accidentally registered their authentication middleware after their protected routes instead of before, meaning every request reached the protected route handler without ever being checked, illustrating exactly why middleware order is a common and consequential mistake.

Common follow-ups: What happens if a middleware function never calls next() and never sends a response?;How does route-specific middleware (passed as an extra argument to app.get()) differ from application-level middleware registered via app.use()?