Using environment variables with React

Felipe Oliveira
Share! por Ateliê de Software
2 min readOct 31, 2023

--

Environment variables can be really useful to store sensitive data like Api Urls that will be used in our projects.

In this short tutorial we’ll learn how to use environment variables in our projects and how to distinguish those variables in multiple environments. We’ll use a React project as an example.

Configuring

To start, let’s create a file named .env in our root path. In this file we’ll create our keys and values to our environment variables:

We can see some things in this example:

  • The keys must be in upper case;
  • Keys can not contain spaces;
  • The values from the keys can be any type of data, but will always be returned as a string;

Reading

Once we’ve configured our .env file, we can read the values from the keys.

It’s also possible to read those values in html files.

Multiple environments

It’s also possible to create multiple .env files for different environments:

  • .env: Default;
  • .env.local: Overwrite all the environments, except test;
  • .env.development, .env.test, .env.production: Specific envs for different environments;
  • .env.development.local, .env.test.local, .env.production.local: Overwrite specific environments;

Warning

It’s not recommended to store sensitive data like db passwords or access keys in environment variables. As it is a client-side framework, it may be possible to access this information.

Follow our blog on Medium and stay inside everything that happens in Ateliê.

Say hello to us! And join us on social networks:
E-mail: contato@atelie.software
Site
Facebook
Instagram
LinkedIn

--

--