Delta Kapp
Delta Kapp

Reputation: 1232

Is it necessary to explicitly handle 404s in Express?

Express documentation at https://expressjs.com/en/starter/faq.html shows how to handle 404 by adding the following after all middleware:

app.use(function (req, res, next) {
  res.status(404).send("Sorry can't find that!")
})

But even without adding this, unhandled routes are automatically responding 404. Is there some reason why I need to explicitly handle 404s if I don't need any extra functionality there?

Upvotes: 0

Views: 180

Answers (1)

jfriend00
jfriend00

Reputation: 707328

Express has a default 404 handler built-in so if you're perfectly fine with what it provides, then it is not necessary to provide your own 404 handler. You provide your own 404 handler when you want to control what response is sent for a 404 condition.


I went to look for the default 404 handler in the Express source code and it's a bit hard to find. It is buried in a dependent module called finalHandler which I was only able to find by stepping through the Express code which eventually stepped into this other module and you can see this module in the Express package.json as a dependency.

Here's a link to the relevant function in the finalHandler source.

Basically, if Express handlers/middleware keep calling next() and run out of more matching request handlers, they get to this final function which, if there is no pending error, then it sends a vanilla 404 response.

The relevant lines of code are these:

status = 404
msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req))

// ...

send(req, res, status, headers, msg)

Upvotes: 1

Related Questions