Run Node with specific env file

Tue Oct 17 2023

In this blog, we'll discuss how to use specific environment files such as .env.trail, .env.test, .env.prod, etc., in your application.

In many projects, it's often required that for each environment, certain Secret Keys, Tokens, or URLs in the environment file differ. By default, some frameworks support files like .env.test, .env.production, and .env.development.
But what if your project has additional environments such as stage, trail, or pre-prod?

For this, we can create our own environment files with suffixes for each environment, such as .env.prod, and then use a package to load the specific .env file at runtime.

.env.test
JWT_TOKEN=qwertyuiop
LOGIN_URL_CALLBACK=test.url.com
.env.development
JWT_TOKEN=abcdefghijk
LOGIN_URL_CALLBACK=dev.url.com

We can use a popular npm package called env-cmd, which helps load specific environment files during runtime.

Install it using:

npm i env-cmd

Once installed, add scripts in your package.json to specify which environment file should be used for each command:

package.json
{
  "scripts": {
    "test-deploy": "env-cmd -f .env.test npm run build && npm run start",
    "dev-start": "env-cmd -f .env.development npm run dev",
    "dev-deploy": "env-cmd -f .env.development npm run build && npm run start"
  }
}

Now, when starting your application in a specific environment, simply run one of the defined scripts:

  • npm run dev-start → uses .env.development
  • npm run test-deploy → uses .env.test

This approach helps manage multiple .env files for different environments efficiently. You can easily extend it by adding more scripts for environments like staging, pre-prod, or production based on your needs.