I have a simple Express router setup with authentication middleware. I have something like the code below.
If the user navigates to '/authenticate' with improper credentials, I want the middleware to send an error response and all middleware and route processing to cease. To do that, I sent a response, told Express to skip the rest of the route middleware with next('route')
, and included a return to stop processing the authMiddleware
function.
let router = express.Router()
function authMiddleware(req, res) {
//Do some authentication checks
if(!authenticated) {
res.status(403).send("Could not authenticate. :-(")
next('route')
return
}
//Additional authentication checks
}
router.use(authMiddleware)
router.post('/authenticate', (req, res)=> {
res.send("You should not see me if you aren't authenticated!")
}
I would expect the post route not to run; however, it does, giving me the error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
. I have searched Google, Stack Overflow, and the Express docs to no avail, though perhaps my search terms are lacking.
I saw a Scotch article that suggested doing a redirect, but that seems a little hacky and inelegant.
So my question: What is the proper way to terminate a middleware/routing chain?