Order of Middleware
One of the most important concepts in Express is that **order matters**. Middleware and routes execute in the sequence they're defined. Understanding this order is crucial for building correct and secure applications.
The Execution Flow
When a request comes in, Express goes through middleware/route handlers in the order they were registered. The first one that matches the path and doesn't call `next()` sends the response.
Think of middleware order like a line at a ticket counter. The first person in line gets served first. If they can't handle your request, they pass you to the next person.
Example: Order Matters
const express = require('express');const app = express();
<!-- Middleware 1: Logger -->app.use((req, res, next) => { console.log('Logger: Request received'); next();});
<!-- Middleware 2: Authentication -->app.use((req, res, next) => { console.log('Auth: Checking token'); if (!req.headers.token) { return res.status(401).send('Unauthorized'); } next();});
<!-- Route -->app.get('/', (req, res) => { console.log('Route: Sending response'); res.send('Hello World');});
<!-- This will run in order: Logger → Auth → Route (if Auth passes) -->Common Ordering Mistakes
Mistake 1: Body parser after route
<!-- ❌ WRONG: Route runs before body-parser -->app.post('/api/users', (req, res) => { console.log(req.body); <!-- undefined! -->});
app.use(express.json()); <!-- Too late! -->Mistake 2: Specific route after catch-all
<!-- ❌ WRONG: This catches /users/* before specific routes -->app.use('/users', (req, res, next) => { console.log('Catch-all users middleware'); next();});
app.get('/users/profile', (req, res) => { <!-- This will still work if catch-all calls next() --> <!-- But if catch-all sends response, this never runs -->});Error Middleware
Error-handling middleware is special – it takes **four** parameters: `(err, req, res, next)`. It must be defined **after** all other middleware and routes.
<!-- Regular middleware and routes -->app.use(express.json());
app.get('/', (req, res) => { throw new Error('Something went wrong');});
<!-- Error handling middleware (AFTER all routes) -->app.use((err, req, res, next) => { console.error(err.stack); res.status(500).json({ error: 'Internal Server Error', message: err.message });});404 Handler
A common pattern is to have a 404 handler at the end – if no routes match, this runs.
<!-- All routes go here -->
<!-- 404 handler - must be LAST -->app.use((req, res) => { res.status(404).send('Page not found');});Two Minute Drill
- Middleware and routes execute in the order they're defined.
- Place body-parsing middleware (`express.json()`) before routes that need it.
- Error-handling middleware must have 4 parameters and be defined last.
- 404 handlers should be the final middleware.
- Always define specific routes before generic/catch-all routes.
Need more clarification?
Drop us an email at career@quipoinfotech.com
