How to manage environment variables in a React app?

In a React app, you can manage environment variables by creating a .env file at the root of your project. Here is how you can set up and access environment variables in a React app:

  1. Create a .env file at the root of your project:
REACT_APP_API_URL=https://api.example.com REACT_APP_API_KEY=123456789
  1. Install dotenv package:
npm install dotenv
  1. Import and configure dotenv in your project:
require('dotenv').config()
  1. Access environment variables in your React components:
const apiUrl = process.env.REACT_APP_API_URL; const apiKey = process.env.REACT_APP_API_KEY;
  1. Remember to prefix your environment variables with REACT_APP_ in the .env file to ensure they are exposed in the React app.

  2. You can now use these environment variables in your React components to make API requests, configure services, etc.

Note: Remember not to expose sensitive information in your .env file, as it can be accessed by anyone who has access to your project files. It's best to avoid committing your .env file to version control systems like Git.