βοΈ 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 runnpm run build
β οΈ Do not store private keys or secrets directly in React β frontend code is always exposed to the user.