next() is the function middleware calls to hand control to the next middleware or route
handler in the chain. Skip it, and the request simply hangs — nothing else runs.
Syntax
app.use(path, (req, res, next) => { ... })
Without next()
const express = require("express");
const app = express();
app.use("/", (req, res, next) => {
console.log("First middleware");
// next() is never called
});
app.get("/", (req, res, next) => {
console.log("Second middleware / route handler");
});
app.listen(5100, () => console.log("Server is Running"));
Visiting / only logs First middleware — the request never reaches the second function,
and the browser waits forever for a response.
With next()
const express = require("express");
const app = express();
app.use("/", (req, res, next) => {
console.log("First middleware");
next();
});
app.get("/", (req, res) => {
console.log("Second middleware / route handler");
res.send("Done");
});
app.listen(5100, () => console.log("Server is Running"));
Now both log lines print, and the client gets a response.
Things to remember
- Forgetting
next()in non-terminal middleware leaves requests hanging. - Calling
next(err)passes control to error-handling middleware. - A middleware that sends a response (
res.send(),res.json(), etc.) doesn't need to callnext()afterward.