How do environment variables work in a React app during deployment?
Short answer
Environment variables let you keep configuration values, like an API address, separate from your code, so the same codebase can behave differently in development versus production.
Advertisement
AModel answer
Environment variables let you keep configuration values, like an API address, separate from your code, so the same codebase can behave differently in development versus production. In most React setups, these variables must start with a specific prefix, such as VITE underscore or REACT underscore APP underscore, and they get baked into the build at build time.
// .env.production file
VITE_API_URL=https://api.myrealsite.com
// Used inside your code
const apiUrl = import.meta.env.VITE_API_URL;
fetch(`${apiUrl}/products`);Real-world example
A team uses one API address while developing locally and a different, real API address in production, simply by setting different environment variable files for each environment without changing any actual code.
Likely follow-ups
- Why do these variables need a special prefix before they can be used in the browser?
- Is it safe to put secret keys, like a database password, into a frontend environment variable?
Related topics