source code screenshot

When building a React app, there may come a time when you need to tweak the behavior of your application based on different environments. This might be in relation to API endpoints, feature toggles, or other configuration data. Here’s how to use Environment Variables to manage such configuration in a flexible and reliable manner.

Firstly, let’s understand what environment variables are: They are dynamic-named values that can affect the way running processes behave on a computer. For a React application, these can be set up in a .env file at the root of your project.

Start by creating a .env file at the root of your React project:

1
2
3
REACT_APP_NAME=My React App
REACT_APP_VERSION=1.0
REACT_APP_API_URL=https://myapi.com

Important: The REACT_APP_ prefix is mandatory for our Create React App to recognize our custom environment variables. Without this prefix, our variables would be ignored.

Next, you can access these environment variables anywhere in your React code using process.env. For instance, you might want to display the app name on your homepage component:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import React from 'react';

function HomePage() {
  return (
    <div>
      <h1>Welcome to {process.env.REACT_APP_NAME}</h1>
    </div>
  );
}

export default HomePage;

Or, perhaps you need to use the API URL in a service to fetch some data:

1
2
3
4
5
6
import axios from 'axios';

export async function fetchData() {
  const response = await axios.get(`${process.env.REACT_APP_API_URL}/data-endpoint`);
  return response.data;
}

This method makes it easy to maintain different sets of configurations for different environments (development, staging, production, etc.) by simply switching out the .env file. For instance, you might have a .env.development for local development and a .env.production for your live site.

Just remember not to commit these .env files to your git repository, especially if they contain sensitive data. Instead, add .env to your .gitignore file and provide means for other developers or systems to create their own, such as a .env.example file with dummy data.

This way, environment variables provide a flexible and secure way to manage configuration across different environments for your React apps. It’s a simple and efficient solution, and I’m all ears for any other approaches that come to mind.