JavaScript Answers

How to get Express.js to 404 only on missing routes?

Spread the love

To get Node Express.js to 404 only on missing routes, we can return a 404 response with a middleware.

For instance, we write

router.use((req, res, next) => {
    status: 404,
    message: "Not Found",

router.use((err, req, res, next) => {
  if (err.status === 404) {
    return res.status(400).render("404");

  if (err.status === 500) {
    return res.status(500).render("500");


at the bottom of our code to call next to send the 404 status to the last middleware.

Then we check the err.status for the value and call res.status to return the status we want.

And we call render to render the response body.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.