React JS being a front end language, its common you might not have realised using environment variable is the solution for your problem to declare different API url’s or any other parameter depending on environment (local, staging build and production build). So before I being let me explain the concept of environment variables.
Environmental variables are variables who's value depends on the environment its being executed in, this is used to isolate the applications between Local , Staging and Production environments. In React JS app typical use case is to define the back end URL the build should use.
If you have used Create React App for your ReactJS application its straight forward, support for custom environment variables is packed in the build system.
firstname.lastname@example.org and higher required
Just change the way you start your project or build your project to
REACT_APP_MY_VAR=test npm start // In case of build REACT_APP_MY_VAR=test npm build
Now anywhere in your app you can access the variable using
It should print out
Note : Only the variables that start with
REACT_APP_ are embedded in your app. All the other environment variables are ignored. To use other names for environment variable refer second method.
If you don't use Create React App, want to specify environmental variables in a file or have any other use case you can use Dotenv. Dotenv is a zero-dependency module that loads environment variables from a
.env file into process.env
# with npm npm install dotenv # or with Yarn yarn add dotenv
Install the package using yarn or npm. Require and configure dotenv as early as possible in your application.
.env file in the root directory of your project. Add environment variables on new lines in the form of
process.env will have the keys and values you defined in your .env file.
It should print out
Last 5 Articles
All Articles >
9 Ways to Boost the Design of Your Sports Team Website
The Best Marketing Apps to Use with Shopify
Tips to Increase Software Development Speed
Mitigating Risks In Custom Software Development
Subscribe to our email newsletter for useful tips and valuable resources, sent out every new article release.
Wow ! you have someting to tell us. That's great! Please keep in mind that comments are moderated, we employ
rel="nofollow"for links, avoid using a spammy word or a domain in name field, it might end up as a Spam. Thanks for reading.