0
0
Node.jsframework~5 mins

Middleware ordering matters in Node.js

Choose your learning style9 modes available
Introduction

Middleware functions run in the order they are added. This order controls how requests are handled step-by-step.

When you want to log requests before processing them
When you need to check user authentication before allowing access
When you want to parse incoming data before using it
When you want to handle errors after all other middleware
When you want to serve static files before other routes
Syntax
Node.js
app.use(middlewareFunction1);
app.use(middlewareFunction2);
app.use(middlewareFunction3);
Middleware runs in the order you add them with app.use() or route methods.
If a middleware does not call next(), the chain stops there.
Examples
This example shows two middleware functions running one after the other.
Node.js
app.use((req, res, next) => {
  console.log('First middleware');
  next();
});

app.use((req, res, next) => {
  console.log('Second middleware');
  next();
});
Here, JSON parsing middleware runs before the handler that sends back the parsed data.
Node.js
app.use(express.json());
app.use((req, res) => {
  res.send(req.body);
});
Authentication middleware runs before the route handler to protect the profile page.
Node.js
app.use((req, res, next) => {
  if (!req.user) {
    return res.status(401).send('Unauthorized');
  }
  next();
});

app.get('/profile', (req, res) => {
  res.send('User profile');
});
Sample Program

This program shows two middleware functions running in order before the route handler. The first logs the request, the second adds a header, then the route sends a response.

Node.js
import express from 'express';

const app = express();

// Middleware 1: Logs request method and URL
app.use((req, res, next) => {
  console.log(`Request: ${req.method} ${req.url}`);
  next();
});

// Middleware 2: Adds a custom header
app.use((req, res, next) => {
  res.setHeader('X-Custom-Header', 'Hello');
  next();
});

// Route handler
app.get('/', (req, res) => {
  res.send('Home page');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
OutputSuccess
Important Notes

If middleware order is wrong, requests might not be handled as expected.

Always call next() unless you send a response to avoid hanging requests.

Put error-handling middleware last to catch errors from earlier middleware.

Summary

Middleware runs in the order you add it.

Order affects how requests are processed and responses are sent.

Always plan middleware order carefully for correct app behavior.