Environment Variables
Environment variables store configuration settings that may differ between environments (e.g., development, testing, production). Managing these variables properly ensures a secure and flexible application.
Why Use Environment Variables?
- Security: Keep sensitive information like API keys out of your codebase.
- Flexibility: Configure settings for different environments without modifying code.
- Portability: Share configuration with other team members easily.
Creating Environment Variables
Step 1: Add a .env File
Create a .env
file in your project root. This file will store your environment variables.
REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=your_api_key_here
NODE_ENV=development
Step 2: Add .env
to .gitignore
To prevent sensitive data from being committed to version control, add .env
to your .gitignore
file:
Accessing Environment Variables
React Applications
Environment variables in React must start with REACT_APP_
to be accessible within the codebase.
Node.js Applications
In Node.js, you can access environment variables directly using process.env
.
Best Practices
-
Prefix Variables for Clarity
Use prefixes like
REACT_APP_
orAPI_
to categorize variables logically. -
Use a Library for Type Safety
Libraries like dotenv or env-cmd help load and manage environment variables safely.
-
Set Defaults
Provide fallback values in case environment variables are missing:
-
Secure Sensitive Information
Store sensitive variables like API keys in a secure environment, such as cloud provider secrets (e.g., AWS Secrets Manager, Azure Key Vault).
Environment Variable Management Tools
1. dotenv
- Loads variables from a
.env
file intoprocess.env
. - Suitable for local development.
2. env-cmd
- Handles multiple
.env
files for different environments.
3. direnv
- Manages per-directory environment variables.
4. Cloud-Based Solutions
- AWS Secrets Manager, Azure Key Vault, or HashiCorp Vault for production.
Deployment-Specific Configuration
Vercel
In the Vercel dashboard, go to the project settings and add environment variables under the "Environment Variables" section.
Netlify
In the Netlify dashboard, go to "Site Settings" > "Build & Deploy" > "Environment" and add variables there.
Docker
Pass environment variables using the -e
flag:
With proper management of environment variables, you can enhance security, flexibility, and portability in your applications.