You can define multiple functions for a single route.
Each function can act as a middleware and can call next() to move to the next one.
const middleware1 = (req, res, next) => {
console.log("First handler");
next(); // Move to next handler
};
const middleware2 = (req, res, next) => {
console.log("Second handler");
res.send("Done");
};
app.get('/multi', middleware1, middleware2);
π§ Use case: breaking logic into steps like logging, validation, main handler.
next() Functionnext(), the chain stops there.
app.use((req, res, next) => {
console.log("Logger middleware");
next(); // Passes to next matching route/middleware
});
β If next() is not called, remaining handlers are skipped.
next() + Errors + res.send()
app.use((req, res, next) => {
res.send("Response sent");
next(); // β WRONG: next() after res.send() causes error
});
Once res.send() or res.end() is called β the response is already sent.
Calling next() afterwards will raise "Cannot set headers after they are sent" error.
app.use((req, res, next) => {
const err = new Error("Something went wrong");
next(err); // Pass to error handling middleware
});
app.use((err, req, res, next) => {
console.error(err.message);
res.status(500).send("Internal Server Error");
});