What Is Dotenv?
Dotenv is a zero-dependency module that loads environment variables from a .env file into process.env. This file typically contains environment-specific variables that you want to keep outside your codebase, enhancing manageability and separation of concerns. By using Dotenv, you maintain a clean, organized way to manage configurations that might differ between development, testing, and production environments.
In the context of a React application, using Dotenv allows you to keep sensitive information such as API keys and database connections out of your source code. This ensures that such information can be easily changed without altering the code. It also reduces the risk of inadvertently exposing sensitive data in version control systems.
In this article:
What Is the react-dotenv
Library?
The react-dotenv
library is a tool that makes environment variable management in React applications easier. It extends the functionality of the standard Dotenv module by allowing you to inject environment variables directly into the client-side of a React app. This integration is crucial for handling runtime environment variables, especially when building single-page applications (SPAs) that rely on client-side configuration.
By using react-dotenv
, you can access environment variables defined in a .env
file within your React components through process.env
. This allows for simplified configuration management directly in your frontend code without exposing these values to external users.
Benefits of Using Dotenv with React
Here are the key benefits of using dotenv with React:
- Simplified configuration management: Dotenv simplifies configuration management by centralizing environment variables in a single file. Instead of hardcoding configuration values throughout your React application, you reference environment variables stored in the
.env
file, especially useful for multiple environments like dev, staging, and production. - Readability and maintainability: Using Dotenv improves the readability and maintainability of your React application’s codebase. Environment variables specified in an .env file provide a clear, human-readable format for managing configuration values. This ensures that developers can quickly understand and update configuration settings without diving deep into the code.
- Improved security: Storing sensitive data such as API keys and secret tokens in the
.env
file reduces the risk of exposing these secrets in your codebase. By not hardcoding these values, you ensure that sensitive information is not accidentally committed to version control systems like Git.
Note: Using a dotenv
library is better than hard coding variables into your code, but it is not completely secure, because dotenv files are stored in plaintext and available to anyone with access to your environment. This makes it important to use dedicated secret management or configuration solutions.
Tips From the Expert
In my experience, here are tips that can help you better manage environment variables in a React project using Dotenv:
- Use multiple .env files for different environments: Create .env.development, .env.production, and .env.test files to manage environment-specific variables. This makes it easier to switch between environments and ensures that sensitive information is not exposed inappropriately.
- Validate environment variables: Implement a validation step using libraries like dotenv-safe or env-schema to ensure all required environment variables are set correctly. This prevents runtime errors due to missing or incorrect configurations.
- Encrypt sensitive .env files: Store sensitive .env files encrypted, and decrypt them at runtime using a secure key management service. This adds an extra layer of security, especially for production environments.
- Automate .env file updates: Use CI/CD pipelines to manage and update .env files. This ensures that the correct environment variables are used in each deployment and reduces manual errors.
- Leverage environment variable fallbacks: Provide default values for environment variables within your application code using ES6 destructuring. This ensures that your app can still run with sensible defaults if certain environment variables are missing.
Tutorial: Setting Up Dotenv in a React Project
This tutorial is adapted from the official react-dotenv
documentation.
Step 1: Installation
To begin using Dotenv in your React project, you need to install the react-dotenv
library. Open your terminal and navigate to your project directory. Run the following command to install react-dotenv
:
npm install react-dotenv
This command will add react-dotenv
to your project’s dependencies, allowing you to utilize environment variables without manual setup.
Step 2: Configuration
After installing the react-dotenv
library, the next step is to configure your project to use it. This involves creating a .env
file and updating your package.json file to include the necessary configurations.
Create an .env
file:
Create a new file named .env
in the root directory of your project. This file will hold all your environment-specific variables. Each variable should be defined on a new line using the format KEY=VALUE
. Here is an example:
API_URL=https://api.example.com
In this example, API_URL
is the key, and https://api.example.com
is the value. You can add as many environment variables as needed for your project.
Update package.json
:
Next, you need to modify your package.json
file to use the react-dotenv
library. Open package.json
and locate the scripts
section. Append the react-dotenv
command to the start
, build
, and serve
scripts. Additionally, specify which environment variables you want to expose using the react-dotenv.whitelist
property.
Here is an example of what your package.json
might look like after these changes:
{
"name": "my-react-app",
"version": "0.1.0",
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1",
"react-dotenv": "^0.1.0",
"react-scripts": "3.4.3",
"serve": "^11.3.2"
},
"scripts": {
"start": "react-dotenv && react-scripts start",
"build": "react-dotenv && react-scripts build",
"serve": "react-dotenv && serve build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [">0.2%", "not dead", "not op_mini all"],
"development": ["last 1 chrome version", "last 1 firefox version", "last 1 safari version"]
},
"react-dotenv": {
"whitelist": ["API_URL"]
}
}
In this configuration:
- The
start
,build
, andserve
scripts are updated to runreact-dotenv
before executing their respective commands. This ensures that environment variables are loaded whenever you start or build your project. - The
react-dotenv
property inpackage.json
includes awhitelist
array specifying which environment variables to expose. In this case, onlyAPI_URL
is exposed.
Step 3: Running Your Project
With the configuration in place, you can now run your project. The react-dotenv
library will automatically load the environment variables defined in your .env
file into the window.env
property when the project starts. Use the following command to start your project:
npm start
This command initializes your project and ensures that all specified environment variables are available globally in the window.env
object.
Step 4: Accessing Environment Variables
After setting up and running your project, you can access the environment variables within your React components. There are two primary methods for accessing these variables: using the react-dotenv
library or directly using the window.env
global variable.
Using the react-dotenv
library:
Import the react-dotenv
library and use it to access your environment variables. Here is an example of a React component that displays the DB_URL
:
import React from "react";
import env from "react-dotenv";
export function ExampleComponent() {
return {env.DB_URL};
}
In this example, the env
object from react-dotenv
is used to access the API_URL
variable defined in your .env
file.
2. Using the window.env
global variable:
Alternatively, you can access the environment variables directly from the window.env
object. Here is an example of how to do this:
import React from "react";
export function ExampleComponent() {
return {window.env.DB_URL};
}
In this approach, the window.env
object provides access to the environment variables loaded by react-dotenv
.
Related content: Read our guide to npm dotenv
Managing and Securely Storing Environment Variables with Configu
In light of the limitations of Dotenv libraries, you should consider a more robust alternative to managing environment variables. Configu is a configuration management platform comprised of two main components, the stand-alone Orchestrator, which is open source, and the Cloud, which is a SaaS solution:
Configu Orchestrator
As applications become more dynamic and distributed in microservices architectures, configurations are getting more fragmented. They are saved as raw text that is spread across multiple stores, databases, files, git repositories, and third-party tools (a typical company will have five to ten different stores).
The Configu Orchestrator, which is open-source software, is a powerful standalone tool designed to address this challenge by providing configuration orchestration along with Configuration-as-Code (CaC) approach.
Configu Cloud
Configu Cloud is the most innovative store purpose-built for configurations, including environment variables, secrets, and feature flags. It is built based on the Configu configuration-as-code (CaC) approach and can model configurations and wrap them with unique layers, providing collaboration capabilities, visibility into configuration workflows, and security and compliance standardization.
Unlike legacy tools, which treat configurations as unstructured data or key-value pairs, Configu is leading the way with a Configuration-as-Code approach. By modeling configurations, they are treated as first-class citizens in the developers’ code. This makes our solution more robust and reliable and also enables Configu to provide more capabilities, such as visualization, a testing framework, and security abilities.