Simple Environmental Variable Setup in React and Node Applications

kachidk

Nwanguma Victor

Posted on February 28, 2022

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 !

💖 💪 🙅 🚩
kachidk
Nwanguma Victor

Posted on February 28, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related