How to redirect 404 errors to a page in ExpressJS?


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

5/29/2013 3:14:16 AM

Accepted Answer

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.send({ error: 'Not found' });

  // default to plain-text. send()
  res.type('txt').send('Not found');
12/8/2012 7:25:31 PM

I think you should first define all your routes and as the last route add

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){

An example app which does work:


var express = require('express'),
    app = express.createServer();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res){
  res.send('hello world');

//The 404 Route (ALWAYS Keep this as the last route)
app.get('*', function(req, res){
  res.send('what???', 404);

app.listen(3000, '');

alfred@alfred-laptop:~/node/stackoverflow/6528876$ mkdir public
alfred@alfred-laptop:~/node/stackoverflow/6528876$ find .
alfred@alfred-laptop:~/node/stackoverflow/6528876$ echo "I don't find a function for that... Anyone knows?" > public/README.txt
alfred@alfred-laptop:~/node/stackoverflow/6528876$ cat public/README.txt 


alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/
hello world
alfred@alfred-laptop:~/node/stackoverflow/6528876$ curl http://localhost:3000/README.txt
I don't find a function for that... Anyone knows?

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow