The next() function helps move from one step to the next in Express. It controls how requests flow through different parts of your app.
next() function and flow control in 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.
next() to continue.app.use((req, res, next) => {
console.log('First middleware');
next();
});next().app.use((req, res, next) => {
if (!req.user) {
res.status(401).send('Unauthorized');
} else {
next();
}
});next(err).app.use((err, req, res, next) => {
console.error(err);
res.status(500).send('Server error');
});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.
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'); });
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.
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.