Express should throw an error if `next()` is called without any more middleware in the stack

I’ve spent half an hour trying to debug why the client was getting a 404 response back, and it turns out the cause was because we didn’t have a middleware in place to close the request (e.g. res.end()). In other words, the last middleware in the stack called next() but there wasn’t any more middleware to handle the request, so Express sent a 404 response.

I don’t think this should be the default behaviour, as this is clearly a case of programmer error. As such, I think express should throw an error instead, so that we can be made aware of the issue and add correct middleware in place or otherwise handle the error.

Silently responding with a 404 makes a developer hunt their own middleware stack first to see if and why they are terminating the request with a 404, which they aren’t.

Thoughts?

Author: Fantashit

2 thoughts on “Express should throw an error if `next()` is called without any more middleware in the stack

  1. Isn’t it the responsibility of the app developers to throw a (custom) 404 error if needed?
    I would think that’s not the responsibility of Express, and that Express should warn developers about it instead, or perhaps return the 404 if you’ve configured Express to do so explicitly.

    Currently, this implicit 404 was causing me to scratch my head a lot of times, because we issue manual 404’s in specific cases, and I was spending a lot of time analysing them before realising it was Express sending the 404’s, not our app.

    In your second example app, instead of return next() one could simply do return next(new NotFoundError('I dont handle this')) to be more explicit, which is how we approach it most of the time. I guess I just don’t like auto-magic behaviour as it’s often hard to track.

  2. It is not the responsibility of the developer to 404 themselves; that’s an implicit operation of nothing handling the request. This enables transparent mounting of apps without them needing to be made to be mountable, since a 404 is just a fallthough, so it makes it really easy to compose multiple apps together with before before after after behavior, just like express.static. For example, consider the following:

    var app = express()
    app.use('/api', legacyApi)
    app.use('/api', newApi)
    // ... etc

    That would be impossible if the legacyApi threw an error and didn’t let 404s fall down.

Comments are closed.