SmartCodingTips

โš™๏ธ Environment Variables in React

Environment variables allow you to configure your React app for different environments (development, testing, production) without changing the source code.


๐Ÿ“ 1. Declaring Environment Variables

In Create React App, you can declare variables in a file named .env:


REACT_APP_API_URL=https://api.example.com
REACT_APP_VERSION=1.0.0

All environment variables **must** start with REACT_APP_ to be exposed in the frontend.

๐Ÿ“ฆ 2. Accessing Variables in Code


const apiUrl = process.env.REACT_APP_API_URL;

console.log('Backend API URL:', apiUrl);

๐ŸŒ 3. Using with Fetch or Axios

Use environment variables to dynamically set base URLs for APIs:


fetch(`${process.env.REACT_APP_API_URL}/users`)
  .then(res => res.json())
  .then(data => console.log(data));

๐Ÿงช 4. Environment-Specific Files

Create separate env files for different modes:

  • .env โ€“ shared across all
  • .env.development โ€“ for dev mode
  • .env.production โ€“ for production
  • .env.test โ€“ for test environments

โ™ป๏ธ 5. Rebuild After Changes

React injects environment variables at build time. So if you change a variable, you need to restart your dev server:


npm start

๐Ÿ”’ 6. Security Warning

Never store secrets like API keys or tokens directly in frontend code or env files. Use a secure backend to keep secrets private.

๐Ÿ“‹ Summary

  • Use REACT_APP_* to define frontend env variables
  • Access using process.env
  • Restart dev server after changes
  • Keep secrets on the server, not in React env