0
0
ExpressHow-ToBeginner · 4 min read

How to Use next Function in Express: Simple Guide

In Express, the next function is used inside middleware to pass control to the next middleware or route handler. Calling next() continues the request-response cycle, while next(error) passes an error to Express's error handler.
📐

Syntax

The next function is a parameter in Express middleware functions. It is called to pass control to the next middleware or route handler.

  • next(): Moves to the next middleware.
  • next(error): Passes an error to Express's error handling middleware.
javascript
app.use(function (req, res, next) {
  // Middleware logic here
  next(); // Pass control to next middleware
});

app.use(function (err, req, res, next) {
  // Error handling middleware
  res.status(500).send('Something broke!');
});
💻

Example

This example shows two middleware functions. The first logs the request and calls next() to continue. The second sends a response. If an error occurs, it is passed to the error handler using next(error).

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

// Middleware to log request method and URL
app.use((req, res, next) => {
  console.log(`${req.method} ${req.url}`);
  next(); // Continue to next middleware
});

// Middleware to handle route
app.get('/', (req, res) => {
  res.send('Hello from Express!');
});

// Error handling middleware
app.use((err, req, res, next) => {
  console.error('Error:', err.message);
  res.status(500).send('Internal Server Error');
});

app.listen(3000, () => {
  console.log('Server running on http://localhost:3000');
});
Output
Server running on http://localhost:3000 GET /
⚠️

Common Pitfalls

Common mistakes when using next include:

  • Forgetting to call next(), which causes the request to hang.
  • Calling next() multiple times in the same middleware.
  • Not handling errors properly by passing them to next(error).

Always ensure next() is called exactly once unless ending the response.

javascript
/* Wrong: Missing next() causes request to hang */
app.use((req, res, next) => {
  console.log('This middleware does not call next()');
  // next() missing here
});

/* Right: Calls next() to continue */
app.use((req, res, next) => {
  console.log('This middleware calls next()');
  next();
});
📊

Quick Reference

  • next(): Pass control to next middleware.
  • next(error): Pass error to error handler.
  • Middleware signature: (req, res, next).
  • Error middleware signature: (err, req, res, next).

Key Takeaways

Always call next() in middleware to continue the request cycle.
Use next(error) to pass errors to Express's error handlers.
Middleware functions receive next as the third parameter.
Error-handling middleware has four parameters: err, req, res, next.
Avoid calling next() multiple times or forgetting to call it.