The Express framework for Node.js has this concept it calls Route Specific Middleware. It is similar in concept to the Connect framework’s middleware but it is specifically for exposing functionality to your routes.
You can use route specific middleware for all sorts of cool things and here I’ll specifically show you how you can use it to access your MongoDB database in your routes, which are defined in separate modules.
Access to source code for this article is available at
https://github.com/jeffschwartz/express-middleware-routing/tree/
To begin, you define a route specific middleware with a function that takes 3 parameters: a request; a response; and a callback function which by convention is named next. For example, the following is a valid middleware function:
var exposeDb = function(req, resp, next){
req.mongoDb = db;
next();
};
The middleware function above adds a property called mongoDb to the request object and assigns to it the value of db, which is a MongoDb database object. With this function defined, you can now add this middleware to your routes as in the following example:
app.get('/', exposeDb, routes.index);
And here is the code to the main module so you can see everything in context:
/**
* Module dependencies.
*/
var mongo = require("mongodb")
, express = require('express')
, routes = require('./routes')
, http = require('http')
, path = require('path');
// server options
var serverOptions = {
auto_reconnect: true,
poolSize: 10
};
// create mongo server
var server = new mongo.Server("localhost", 27017, serverOptions);
// create mongo database
var db = new mongo.Db("dbname", server, {});
var app = express();
app.configure(function(){
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(path.join(__dirname, 'public')));
});
app.configure('development', function(){
app.use(express.errorHandler());
});
db.open(function(err, db){
if(err){
throw err;
}
// route specific middleware - will expose the database to route
var exposeDb = function(req, resp, next){
req.mongoDb = db;
next();
};
app.get('/', exposeDb, routes.index);
http.createServer(app).listen(app.get('port'), function(){
console.log("Express server listening on port " + app.get('port'));
});
});
The routes/index.js file exports the index function that handles the route for the ‘/’ URL. All it does is render the home page for the Web site. Here’s its complete code:
/*
* GET home page.
*/
exports.index = function(req, res){
var mongoDb = req.mongoDb;
var expose = "";
if(mongoDb){
expose = "index route has access to mongo";
}else{
expose = "index route doesn't have access to mongo";
}
res.render('index', { title: 'Express', expose: expose });
};
As you can see from the above code, the route now has access to the MongoDb database by way of the request. To keep things simple and straightforward this example justs reports the ‘truthyness’ of the req.mongoDb property and passes that on to the index.ejs template which will render the home page to the browser:
<!DOCTYPE html>
<html>
<head>
<title><%= title %></title>
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<h1><%= title %></h1>
<p>Welcome to <%= title %></p>
<p><%= expose %></p>
</body>
</html>
And here’s what the browser actually renders:

Browser reports that route has access to database
Summary
I hope you’ve enjoyed my short demonstration of using Express route specific middleware to easily ‘inject’ services and database access into your routes. Give it a try in your next Node application.
Feel free to leave me your comments and questions.
Until the next time…