DEV Community

Nwanguma Victor
Nwanguma Victor

Posted on

4 2

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 !

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay