DEV Community

Victor Nwanguma 👨‍🚀
Victor Nwanguma 👨‍🚀

Posted on

Simple Environmental Variable Setup in React and Node Applications

env-cmd provides a simple and efficient method for configuring environmental variables.

Install

npm install env-cmd 
or 
npm install -g env-cmd
Enter fullscreen mode Exit fullscreen mode

Usage

There are two methods of usage.

Method 1

It involves using different .env files e.g .env.development, .env.staging, .env.production.

- For an enviroment file .env at the root directory.

./env

# This is a comment

REACT_APP_APPLICATION_NAME=TodoApp
REACT_APP_API_BASEURL=http://api.test.com
Enter fullscreen mode Exit fullscreen mode

Package.json

{
  "scripts": {
    "start": "env-cmd react-scripts start"
  }
}
Enter fullscreen mode Exit fullscreen mode

- Using custom env file .env.development or file path ./abc/def/.env

./env.development

# This is a comment

REACT_APP_APPLICATION_NAME=TodoApp
REACT_APP_API_BASEURL=http://api.test.com
Enter fullscreen mode Exit fullscreen mode

Package.json

{
  "scripts": {
    "start": "env-cmd -f ./env.development react-scripts start"
  }
}
Enter fullscreen mode Exit fullscreen mode

Method 2

Like me, if you like to put all your environments in one file.
Create .env-cmdrc.json at the root directory.

./env-cmdrc.json

{
  "development": {
    "REACT_APP_APPLICATION_NAME": "TodoApp",
    "REACT_APP_API_BASEURL": "http://api.test.com"
  },
  "staging": {
    "REACT_APP_APPLICATION_NAME": "TodoApp",
    "REACT_APP_API_BASEURL": "http://staging.test.com"
  },
  "production": {
    "REACT_APP_APPLICATION_NAME": "TodoApp",
    "REACT_APP_API_BASEURL": "http://production.test.com"
  }
}
Enter fullscreen mode Exit fullscreen mode

Package.json

{
  "scripts": {
    "start": "env-cmd -e development react-scripts start"
  }
}

or

{
  "scripts": {
    "start": "env-cmd -e production react-scripts start"
  }
}
Enter fullscreen mode Exit fullscreen mode

Hope you find this helpful !

Discussion (0)