SmartCodingTips

βš™οΈ Environment Variables in React

Environment variables allow you to safely manage secrets, API endpoints, and config values in different environments (development, production, staging, etc.).


πŸ“ 1. Create a .env File


REACT_APP_API_URL=https://api.example.com
REACT_APP_FIREBASE_KEY=your-firebase-api-key

All environment variables must start with REACT_APP_ or they won’t be accessible in your app.

🧠 2. Use in Your Code


const apiUrl = process.env.REACT_APP_API_URL;

fetch(`${apiUrl}/posts`)
  .then(res => res.json())
  .then(data => console.log(data));

πŸ§ͺ 3. Restart After Changes

After editing .env, restart the dev server:


npm start
# or
yarn start

πŸ” 4. Don’t Commit .env

Add your .env file to .gitignore to prevent accidental leaks of secrets:


# .gitignore
.env

🌍 5. Environment-Specific Files

  • .env – default
  • .env.development – used in dev mode
  • .env.production – used when you run npm run build
⚠️ Do not store private keys or secrets directly in React β€” frontend code is always exposed to the user.