How to set NODE_ENV to production/development in OS X
Set your Node.js app's NODE_ENV on OS X with the following one-liners in the terminal: NODE_ENV=production node app.js for production or NODE_ENV=development node app.js for development. This changes the environment right before your app starts.
Stepping Things Up
"Quick fixes" like the one above are helpful but not always sustainable. Thus, I'll provide more robust solutions for different scenarios.
Making The Environment Variables Stick
For constant NODE_ENV on OS X, add the export line to your shell configuration file (~/.bash_profile or ~/.zshrc):
Don't forget to apply your changes by running source ~/.bash_profile or restarting your terminal.
Using NPM Scripts
Modify your package.json to contain environment-specific start scripts:
To initiate your app in production mode, buzz npm run start:prod.
Cross-Platform Settings with cross-env
With the cross-env npm package, you can set NODE_ENV regardless of the operating system. To install:
In your package.json, your scripts could resemble:
Going the Extra Mile
Using .env Files with dotenv
Use a .env file and the dotenv npm package for a cleaner management:
Then put your environment variables in the .env file:
NODE_ENV=development
Finally, require and configure dotenv at your app's entry point:
System-Wide Variables
To set NODE_ENV system-wide on OS X, use /etc/environment:
Node App Lifecycles with nodemon, forever, and pm2
To instantly restart your app after making changes, use nodemon:
For deployment, forever or pm2 will keep your app alive and kicking:
For the Heroku Fans
If you're deploying to Heroku, set NODE_ENV via their CLI:
Prioritizing Security
To secure your configurations, be sure not to expose sensitive info. Use keychains, vault services or similar tools for storing secrets.
Was this article helpful?