Explain Codes LogoExplain Codes Logo

How to set NODE_ENV to production/development in OS X

javascript
environment-variables
nodejs
npm-scripts
Anton ShumikhinbyAnton Shumikhin·Aug 30, 2024
TLDR

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):

echo 'export NODE_ENV=production' >> ~/.bash_profile # A command cooler than a polar bear's toenails. 😎

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:

"scripts": { "start": "node app.js", "start:dev": "NODE_ENV=development npm start", "start:prod": "NODE_ENV=production npm start" }

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:

npm install --save-dev cross-env

In your package.json, your scripts could resemble:

"scripts": { "start:dev": "cross-env NODE_ENV=development node app.js", "start:prod": "cross-env NODE_ENV=production node app.js" }

Going the Extra Mile

Using .env Files with dotenv

Use a .env file and the dotenv npm package for a cleaner management:

npm install dotenv

Then put your environment variables in the .env file:

NODE_ENV=development

Finally, require and configure dotenv at your app's entry point:

require('dotenv').config();

System-Wide Variables

To set NODE_ENV system-wide on OS X, use /etc/environment:

sudo echo 'NODE_ENV=production' >> /etc/environment # Handle with care! This is not a toy.

Node App Lifecycles with nodemon, forever, and pm2

To instantly restart your app after making changes, use nodemon:

npm install --save-dev nodemon

For deployment, forever or pm2 will keep your app alive and kicking:

npm install -g pm2 pm2 start app.js --env production

For the Heroku Fans

If you're deploying to Heroku, set NODE_ENV via their CLI:

heroku config:set NODE_ENV=production

Prioritizing Security

To secure your configurations, be sure not to expose sensitive info. Use keychains, vault services or similar tools for storing secrets.