0
0
Expressframework~5 mins

next() function and flow control in Express

Choose your learning style9 modes available
Introduction

The next() function helps move from one step to the next in Express. It controls how requests flow through different parts of your app.

When you want to pass control from one middleware to another.
When you need to handle errors by moving to error-handling middleware.
When you want to split your app logic into small, manageable pieces.
When you want to skip some middleware under certain conditions.
When you want to make sure your app responds only once per request.
Syntax
Express
function middleware(req, res, next) {
  // your code here
  next(); // pass control to next middleware
}

The next parameter is a function you call to continue the request flow.

If you don't call next() or send a response, the request will hang.

Examples
This middleware logs a message and then calls next() to continue.
Express
app.use((req, res, next) => {
  console.log('First middleware');
  next();
});
This middleware checks if the user is logged in. If not, it sends a response and stops. Otherwise, it calls next().
Express
app.use((req, res, next) => {
  if (!req.user) {
    res.status(401).send('Unauthorized');
  } else {
    next();
  }
});
This is error-handling middleware. It catches errors passed by calling next(err).
Express
app.use((err, req, res, next) => {
  console.error(err);
  res.status(500).send('Server error');
});
Sample Program

This app uses two middleware functions before the final route handler. The first logs the request method. The second checks if the query parameter name exists. If missing, it sends an error response. Otherwise, it calls next() to reach the final handler that greets the user.

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

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

// Middleware 2: Checks for a query param 'name'
app.use((req, res, next) => {
  if (!req.query.name) {
    res.status(400).send('Name query param missing');
  } else {
    next();
  }
});

// Final handler: Sends greeting
app.get('/', (req, res) => {
  res.send(`Hello, ${req.query.name}!`);
});

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

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

Use next(err) to pass errors to error-handling middleware.

Order of middleware matters; Express runs them in the order you add them.

Summary

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

It helps split your app into small steps that run one after another.

Calling next() or sending a response is required to finish handling a request.