How can I get Express.js to 404 only on missing routes?

At the moment I have the following which sits below all my other routes:

app.get('*', function(req, res){

And according to the logs, it is being fired even when the route is being matched above. How can I get it to only fire when nothing is matched?


You just need to put it at the end of all route.

Take a look at the second example of Passing Route Control:

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

var users = [{ name: 'tj' }];

app.all('/user/:id/:op?', function(req, res, next){
  req.user = users[];
  if (req.user) {
  } else {
    next(new Error('cannot find user ' +;

app.get('/user/:id', function(req, res){
  res.send('viewing ' +;

app.get('/user/:id/edit', function(req, res){
  res.send('editing ' +;

app.put('/user/:id', function(req, res){
  res.send('updating ' +;

app.get('*', function(req, res){
  res.send('what???', 404);


Alternatively you can do nothing because all route which does not match will produce a 404. Then you can use this code to display the right template:

app.error(function(err, req, res, next){
    if (err instanceof NotFound) {
    } else {

It's documented in Error Handling.

I bet your browser is following up with a request for the favicon. That is why you are seeing the 404 in your logs after the 200 success for the requested page.

Setup a favicon route.

I wanted a catch all that would render my 404 page only on missing routes and found it here in the error handling docs

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

This worked for me.

Hope it helpful, I used this code in bottom of routes

router.use((req, res, next) => {
        status: 404,
        message: 'Not Found',

router.use((err, req, res, next) => {
    if (err.status === 404) {
        return res.status(400).render('404');

    if (err.status === 500) {
        return res.status(500).render('500');


Need Your Help

Multi-select dropdown list in ASP.NET

c# web-controls

Do any good multi-select dropdownlist with checkboxes (webcontrol) exist for

What is the length maximum for a string data type in MongoDB used with Ruby?

ruby mongodb mongoid

I wasn't able to find any information on the max length for a string data type in MongoDB on the main site. I'm coming from a relational database background and there are usually max l...