Learn how to setup your own page not found errors in your Express app.
If you want to setup your own custom 404 for an ExpressJS application then all you need to do is to add a function that is called after all other routes have been loaded.
For example in your app.js file:
app.use((req, res, next) => {
res.status(404).send("That doesn't exist")
});
So when all other routes have been tested by Express and no match has been found, the 404 status code and message will be sent back to the browser.
In order for that to work of course, you need to include your ‘404 handler’ after all other routes have been loaded.
Rendering a 404 Error view
There’s nothing stopping you from sending any kind of response when your ‘404 handler’ is triggered. You might want to send back a different status code (although I would think you’re weird if you did!) or perhaps render a specific view rather than sending a simple message.
There’s nothing stopping you from customising the response any way you like. Normally, it would probably be best practice to render a view, with styling and formatting in line with the rest of your site.
app.use((req, res, next) => {
res.status(404).render(‘404’);
});
The above would still send a 404 status code to the user but would render a view called 404 to make the user experience a bit nicer.
Watch the video on how to create custom 404 pages in Express JS if you want some more detail.