0
0
ReactHow-ToBeginner · 4 min read

How to Use .env File in React for Environment Variables

In React, you can use a .env file to store environment variables by prefixing them with REACT_APP_. These variables become accessible in your code via process.env.REACT_APP_YOUR_VARIABLE after restarting the development server.
📐

Syntax

The .env file contains key-value pairs for environment variables. Each variable must start with REACT_APP_ to be accessible in React code. For example:

  • REACT_APP_API_URL=https://api.example.com
  • REACT_APP_FEATURE_FLAG=true

In your React code, access these variables using process.env.REACT_APP_API_URL.

env
REACT_APP_API_URL=https://api.example.com
REACT_APP_FEATURE_FLAG=true
💻

Example

This example shows how to create a .env file and use its variables inside a React component.

javascript
// .env file
REACT_APP_GREETING=Hello from .env file

// src/App.js
import React from 'react';

function App() {
  return (
    <div>
      <h1>{process.env.REACT_APP_GREETING}</h1>
    </div>
  );
}

export default App;
Output
<h1>Hello from .env file</h1>
⚠️

Common Pitfalls

  • Missing REACT_APP_ prefix: Variables without this prefix won't be available in React code.
  • Not restarting the server: Changes in .env require restarting the development server to take effect.
  • Committing secrets: Avoid putting sensitive data like passwords in .env files committed to public repos.
  • Using .env in production: For production, use environment variables configured on the server or build system.
env
/* Wrong: Missing prefix */
API_URL=https://api.example.com

/* Right: With prefix */
REACT_APP_API_URL=https://api.example.com
📊

Quick Reference

StepDescription
Create .env fileAdd variables with REACT_APP_ prefix
Access variablesUse process.env.REACT_APP_VARIABLE_NAME in code
Restart serverRestart React dev server after changes
Avoid secretsDo not commit sensitive info to public repos

Key Takeaways

Always prefix environment variables with REACT_APP_ to use them in React.
Restart the development server after editing the .env file to apply changes.
Access variables in code via process.env.REACT_APP_VARIABLE_NAME.
Never commit sensitive information in .env files to public repositories.
Use server or build system environment variables for production setups.