0
0
Expressframework~5 mins

Middleware execution flow (req, res, next) in Express

Choose your learning style9 modes available
Introduction

Middleware helps handle requests step-by-step in Express. It lets you add features like logging, authentication, or error handling easily.

You want to log every request to your server.
You need to check if a user is logged in before showing a page.
You want to handle errors in one place.
You want to modify request data before it reaches your route.
You want to serve static files like images or styles.
Syntax
Express
function middleware(req, res, next) {
  // Do something with req or res
  next(); // Pass control to the next middleware
}
Middleware functions always get three arguments: req, res, and next.
Calling next() moves to the next middleware or route handler.
Examples
Logs the URL of every request, then passes control forward.
Express
app.use(function(req, res, next) {
  console.log('Request URL:', req.url);
  next();
});
Checks if user is logged in; stops request if not.
Express
app.use(function(req, res, next) {
  if (!req.user) {
    res.status(401).send('Not logged in');
  } else {
    next();
  }
});
Adds custom data to the request object for later use.
Express
app.use(function(req, res, next) {
  req.customData = 'Hello';
  next();
});
Sample Program

This example shows two middleware functions running in order. The first logs the request method and URL. The second adds a greeting message to the request. Finally, the route handler sends that greeting as the response.

Express
import express from 'express';
const app = express();

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

// Middleware 2: Add a property to req
app.use((req, res, next) => {
  req.greeting = 'Hello from middleware!';
  next();
});

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

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

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

Middleware runs in the order you add them with app.use() or routes.

You can have middleware only for specific routes by passing a path as the first argument.

Summary

Middleware functions run one after another to process requests.

They get req, res, and next to control flow.

Calling next() moves to the next middleware or route.