nodejs middleware is skipped when called externally

I'm relatively new to Express and Node but this seems like a VERY basic demand and I am struggling to understand how it could be happening. Any help in solving the problem or identifying how I'd troubleshoot it would be VERY appreciated.

Problem

var 
    express = require('express'),
    bodyParser = require('body-parser'),
    logger = require('morgan'),
    express = require('express'),
    app = express();

app.get('/heartbeat', function(req,res) {
    res.status(200).json(req.header('host'));
});

// my simple middleware component
app.use(function (req, res, next) {
    console.log('made it');
    next();
});
// standard middleware components
app.use(logger('dev'));
app.use(bodyParser.urlencoded({ extended: true })); 

// Start listener
app.listen(4400);

This simple program does output my "made it" console message but yet when I wrap all the code (minus the variable definitions) in a function called start:

var 
    express = require('express'),
    bodyParser = require('body-parser'),
    logger = require('morgan'),
    express = require('express'),
    app = express();

var start = function(config) { ... }
exports.start = start;

and then call start from a separate module I find that the logging and bodyParser modules seem to execute but my middleware component is ignored. I'm pulling my hair out trying to figure why.

I see 2 issues with your code:

  1. You must call app.use() before calling app.get(...) Otherwise, none of the middlewares are called.

  2. In your custom middleware, you need to call next() or next(error) so that the request is moved to the next middleware. Otherwise, your server hangs forever.

If you post your whole code after separating module, I can help you find more issues :)