Search code examples
node.jsexpressmiddlewareexpress-generator

Node / Express 4 middleware not working


I have an app generated with express-generator, with a bin/www file and a app.js file. In the app.js, I added the following:

app.use(function(req, res, next){
      console.log("--------new middleware");
      next();
    });

But it's not calling the middleware at all. The rest of the app works fine and I've confirmed that the server is running and receiving requests.

Here is the app.js:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var session = require('express-session');
var passport = require('passport');


var routes = require('./routes/index');
var users = require('./routes/users');

//lots of routes

var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'separation anxiety' }));
app.use(passport.initialize());
app.use(passport.session());

app.use('/', routes);
app.use('/users', users);

//lots of paths

app.use(function(req, res, next){
  console.log("--------new middleware");
  next();
});

// app.use(auth.isLoggedIn);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
  app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
      message: err.message,
      error: err
    });
  });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
  res.status(err.status || 500);
  res.render('error', {
    message: err.message,
    error: {}
  });
});

module.exports = app;

Solution

  • An important thing to know about Express middleware is that it's called in order of declaration.

    If any of the declared middleware handles a request (by sending back a response), the request isn't passed to any middleware declared after the one handling the request.

    So if you add a "catch-all" middleware after all the other middleware has been declared, chances are that no request will ever get passed to your middleware, because it got handled somewhere else.

    To fix this, declare your middleware somewhere "high up" in the middleware chain. In your case, try declaring it before express.static:

    app.use(function(req, res, next){
      console.log("--------new middleware");
      next();
    });
    app.use(express.static(path.join(__dirname, 'public')));
    

    It will depend on the ultimate goal of your middleware what the correct place in the middleware chain will be.

    Or, since you added the middleware right above the 404 handler, try requesting a non-existent URL from your server; that should trigger your middleware as well.