Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript User Authentication With Express and Mongo Improving the App with Custom Middleware Understanding Express Middleware

Keenan Wells
Keenan Wells
1,594 Points

Why 404 error handler is last middleware to run when applied first

Hey!

Great course, as always I love the Treehouse content.

One head scratching moment I had was how the 404 middleware error is being handled though, not sure if I missed this in the notes, but it wasn't apparent how it is being applied as middleware and not being called when next is called in the router, since it is applied before the last app.use middleware.

I found this in the express docs to be helpful:

How do I handle 404 responses? In Express, 404 responses are not the result of an error, so the error-handler middleware will not capture them. This behavior is because a 404 response simply indicates the absence of additional work to do; in other words, Express has executed all middleware functions and routes, and found that none of them responded. All you need to do is add a middleware function at the very bottom of the stack (below all other functions) to handle a 404 response:

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