How to set up and use environment variables in your react app

Photo by Matthew Smith on Unsplash

When it comes to setting up and using environment variables in a node.js backend environment, like express, you have to install the dotenv library, set it up, and call the variables in the code.

But what about the front end with your react app?

Long story short: dotenv will not work …

But there is a simple way to use them as the react framework natively manages environment variables!

Create a .env file

First, you have to create a .env file at the root level of your project.

Declare your variables

Now here is the key: you have to name your variables starting with REACT APP

REACT_APP_MY_ENV_VAL = value

Use your variable in your react app

Simply call the environment variable as you would do it in a node.js app:

const variable = process.env.REACT_APP_MY_ENV_VAL

Conclusion

The technique is quite simple, but really useful to store backend url, api keys and lot of other stuff for your react app. Simply name your variables the right way and the magic of react will handle the process.

What can you do to help me?

Please don’t hesitate to:

  • Like the article
  • Follow me
  • Leave a comment and express your opinion.

Happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top