Passing environment variables in npm-scripts Passing environment variables in npm-scripts shell shell

Passing environment variables in npm-scripts


You have a few options:

  • better-npm-run,which can define an env for each command separately
  • Instead of a poststart script, you can concatenate commands for npm like so: "start": "NODE_ENV=${NODE_ENV:=production} node start-app.js && echo $NODE_ENV"
  • Use a process manager in production like pm2. pm2 lets you define environment specific json files with settings such as NODE_ENV. At our company, we successfully run all of our apps in different environments with pm2 (all the while having the same start command)


this is how I did it, first you need to install two dev-dependencies

https://www.npmjs.com/package/env-cmdthis load your env var from your file

https://www.npmjs.com/package/cross-envthis use environment variable in script

example scripts:

"env-cmd ./.config/prod.env cross-env-shell \"docker volume create $DOCKER_VOLUME\""

this load $DOCKER_VOLUME env var from prod.env

update:starting from env-cmd version 10, you need specify -f flag if you want to use a custom env file path

"env-cmd -f ./.config/prod.env cross-env-shell \"docker volume create $DOCKER_VOLUME\""


If you have small use cased, use better-npm-run. For small cases, it works fine. Somehow if you have a lot of commands and it hard manage. Try, batman-cli. Work well and handle lot of environment-dependent issues

npm i -g batman-cli