Bootstrap Your Express.js App: Conditional Middleware
Adding a middleware to Express is easy, but it gets tricky when you have to load them conditionally. For instance, having a request logger is very handy during development, but you do not want it in production. Or you might want to turn off the ACL locally to ease testing. In our case, we wanted to add extra administration functionality only to a specific installation, not on all instances.
We organise our middleware into groups like core, cors, session, database, acl and so forth. These groups consist of configurations of one or more middleware. For instance the core:
Bootstrap.js
The Bootstrap class holds all the middleware groups and their configurations. The constructor simply receives the Express app, then takes the pre-defined middleware list from the config file and executes the matching functions in the right order.
Configuration
node-config is pretty standard. It allows you to create configuration files for every instance you have: development, staging, production.
In these config files you can define the middleware groups you want to load and their order.
"bootstrap": [
"core",
"cors",
"session",
"geoIP",
"requestQueryParser",
"requestLogger",
"acl",
"database",
"routes",
"admin"
]
Adding Bootstrap
Then you just pass your Express app to the Bootstrap logic.