How to use environment variables in React

Hardcoding API keys, endpoints, and configuration values directly in your React code creates security risks and makes switching between development and production environments difficult. With over 12 years of React development experience since 2014 and as the creator of CoreUI, I’ve configured environment variables for countless production applications. React supports environment variables through .env files that are loaded at build time, with variables prefixed with REACT_APP_ automatically exposed to your application. This approach keeps sensitive data out of version control and allows different configurations per environment.

Create .env files and access variables using process.env.REACT_APP_* in your React components.

Create .env file in project root:

REACT_APP_API_URL=https://api.example.com
REACT_APP_API_KEY=your-api-key-here
REACT_APP_ENVIRONMENT=development

Create environment-specific files:

.env                  # Default
.env.local           # Local overrides (gitignored)
.env.development     # Development environment
.env.production      # Production environment

Access in your React components:

const App = () => {
  const apiUrl = process.env.REACT_APP_API_URL
  const apiKey = process.env.REACT_APP_API_KEY

  const fetchData = async () => {
    const response = await fetch(`${apiUrl}/data`, {
      headers: {
        'Authorization': `Bearer ${apiKey}`
      }
    })
    return response.json()
  }

  return (
    <div>
      <h1>Environment: {process.env.REACT_APP_ENVIRONMENT}</h1>
      <p>API: {apiUrl}</p>
    </div>
  )
}

export default App

Add .env.local to .gitignore:

.env.local

Best Practice Note

Environment variables are embedded at build time, not runtime, so restart your development server after changing .env files. Never commit .env.local or files containing secrets to version control. For Create React App, only variables prefixed with REACT_APP_ are accessible. For Vite, use VITE_ prefix instead. Never expose sensitive keys in client-side code—use backend proxies for API keys. This is how we structure CoreUI React templates—using environment variables for API endpoints, feature flags, and environment-specific configurations across development, staging, and production.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author