How to redirect 404 errors to a page in ExpressJS?



I don’t know a function for doing this, does anyone know of one?


I found this example quite helpful:

So, it is actually this part:

// "app.router" positions our routes
// above the middleware defined below,
// this means that Express will attempt
// to match & call routes _before_ continuing
// on, at which point we assume it's a 404 because
// no route has handled the request.


// Since this is the last non-error-handling
// middleware use()d, we assume 404, as nothing else
// responded.

// $ curl http://localhost:3000/notfound
// $ curl http://localhost:3000/notfound -H "Accept: application/json"
// $ curl http://localhost:3000/notfound -H "Accept: text/plain"

app.use(function(req, res, next) {

  // respond with html page
  if (req.accepts('html')) {
    res.render('404', { url: req.url });

  // respond with json
  if (req.accepts('json')) {
    res.json({ error: 'Not found' });

  // default to plain-text. send()
  res.type('txt').send('Not found');

Answered By – Felix

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave A Reply

Your email address will not be published.

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More