Book Image

Mastering Web Application Development with Express

By : Alexandru Vladutu
Book Image

Mastering Web Application Development with Express

By: Alexandru Vladutu

Overview of this book

Table of Contents (18 chapters)
Mastering Web Application Development with Express
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Environment-based loading of middleware


While developing applications locally, we don't need to use components that enable gzip compression or database-backed sessions. Luckily, it's really simple to detect the current application environment.

In Express 3, there was an app.configure() function to detect the environment, but that was removed for newer versions. Nevertheless, all we have to do is pass the NODE_ENV environment variable (process.env.NODE_ENV) when starting the application; for example, see the following line of code:

NODE_ENV=production node env-middleware.js

Then, in our application, we can check for that variable and default to the development mode if it doesn't exist. Instead of writing the same if logic everywhere, we can create a tiny function to execute a callback if the environment matches the first parameter of the function (which is what app.configure() did). In case we want to set the environment in the code, we can create a closure that takes a single argument and returns...