CodePark/ questions / HTTP servers & Express middleware
START PRACTICINGPRACTICE
Backend question · Node.js › HTTP servers & Express middleware

A request to /admin comes in without a token. What happens?

function auth(req, res, next) {
  if (!req.headers.authorization) {
    res.status(401).send("Unauthorized");
  }
  next();
}

app.get("/admin", auth, (req, res) => {
  res.send("secret");
});
The client gets 401, then the handler still runs and fails with ERR_HTTP_HEADERS_SENT

The client gets 401, then the handler still runs and fails with ERR_HTTP_HEADERS_SENT.

Sending a response does not stop the function. Without
return, the code continues and next() still runs. So the route handler runs and tries to send a second response. This throws Cannot set headers after they are sent to the client.

Express does not "ignore the second
send silently". It throws the error above.

Worse, in real code the protected logic runs for a user who is not logged in. The fix: write
return res.status(401).send(...).