βœ… 1. Multiple Route Handlers

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.


πŸ” 2. next() Function


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.


⚠️ 3. next() + Errors + res.send()

❌ Mistake:


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.

βœ… Correct Flow with 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");
});