Search code examples
javascriptnode.jsexpresshttp-status-code-404

How to setup a 404 route in Node/Express


How do I set up a 404 route in Node/Express? If the URL is not valid, I want to render an HTML or Handlebars file to the client


Solution

  • lets say you have an express app like this:

    const app = express()
    

    then put all your routes and at the end of all your routes put 404 route like:

    app.use((req, res) => {
      res.status(404).json({
        success: false,
        message: "Page not found",
      });
    });

    if you are using handlbars or any other template engine, you can do it like:

    app.use((req, res) => {
      res.render('404.html')
    });