Env variables in development
About 341 wordsAbout 1 min
Envvariables
2025-02-08
In React development, using .env files to manage environment variables is common and officially recommended, especially in Vite, Create React App (CRA), and Next.js.
However, .env is not the only option. Many developers prefer more flexible and scalable approaches to manage environment variables.
Using .env Files
Traditional Approach, Suitable for Small Projects.
Suitable for most React projects and useful for replacing variables during CI/CD builds.
📌 Drawback: Values are statically replaced at build time and cannot be dynamically updated.
# .env file
VITE_API_URL=https://api.example.com
//in Vite scenario, variables prefixed with VITE_
console.log(import.meta.env.VITE_API_URL);
//in CRA scenario, variables prefixed with REACT_APP_
console.log(process.env.REACT_APP_API_URL);
Using window Variables
For Frontend Dynamic Configuration. Useful when you need to change configurations dynamically (e.g., switch API URLs at runtime). Not hardcoded at build time, can be updated on CDN or server without rebuilding the app.
📌 Drawback: Requires manual global variable management and can introduce security risks.
<script>
window.APP_CONFIG = {
API_URL: "https://api.example.com",
FEATURE_FLAG: true
};
</script>
console.log(window.APP_CONFIG.API_URL);
Using JSON Configuration Files
When you need to fetch external configuration dynamically, e.g., in micro frontends or third-party services.It can modify JSON files without rebuilding frontend code.
📌 Drawback: Requires asynchronous loading, which can slow down the initial app load.
{
"API_URL": "https://api.example.com",
"ENABLE_FEATURE_X": true
}
async function loadConfig() {
const response = await fetch("/config.json");
const config = await response.json();
console.log(config.API_URL);
}
useEffect(() => {
loadConfig();
}, []);
Injecting Environment Variables via CI/CD
Useful for production when you don’t want to store sensitive variables in .env files. More secure, works well with Docker, Kubernetes, and CI/CD pipelines.
📌 Drawback: Local development may require .env files or additional setup.
export REACT_APP_API_URL=https://api.example.com
npm run build
console.log(process.env.REACT_APP_API_URL);
Using Environment Variable Management Services (For Enterprise Applications)
Suitable for large-scale applications where multiple projects share environment variables.
Popular tools include:
- Vault (by HashiCorp) – Enterprise security and secrets management.
- AWS Parameter Store – Ideal for AWS-based applications.
- EnvKey – A dedicated environment variable management tool.