1

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?

1 Answer 1

3

To terminate the middelware and route chain, simply do not calling the next().

function authMiddleware(req, res, next) {
    let authenticated = false;

    if(!authenticated) {
        res.status(403).send("Could not authenticate. :-(");

        // do not call next(), and simply return

        return;
    }

    //Additional authentication checks

    // all passed, let's pass it to next()
    next();
}
1
  • That is so simple... Hadn't thought of it! Thanks so much. Commented Jul 24, 2019 at 4:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.