How to redirect 404 errors to a page in ExpressJS?

  1. First, install the express and http-errors packages by running the following command in your terminal:
npm install express http-errors
  1. Next, create an Express application and set up a route to handle 404 errors. You can do this by adding the following code to your Express application:
const express = require('express');
const createError = require('http-errors');
const app = express();

// Your other routes and middleware

// Catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// Error handler
app.use(function(err, req, res, next) {
  // Set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // Render the error page
  res.status(err.status || 500);
  res.render('error'); // Replace this with your error page template or redirect logic
});

// Start your server
app.listen(3000, () => {
  console.log('Server is running on port 3000');
});
  1. In the code above, we use the createError function from the http-errors package to create a 404 error. This error is then passed to the error handler, which can be customized to render a specific error page or perform a redirect as needed.

  2. Finally, start your Express server and test the 404 error handling by accessing a route that doesn't exist. You should see the error page or the redirect behavior you have implemented.

Remember to replace the res.render('error') line with your own logic for handling 404 errors, whether it's rendering a specific error page or redirecting to a designated page.