Passing Vite Environment Variables Into Your React App
Here are my sample .env
files for my React app:
.env
MY_FLAG=some dev value
.env.production
MY_FLAG=some prod value
I don’t know if the documentation just isn’t up-to-date, but none of the suggestions for modifying vite.config.ts
worked for me. [EDIT: according to this StackOverflow answer I was looking at the wrong documentation, I needed this]
This is the unhelpful situation I found myself in before guessing desperately:
import react from '@vitejs/plugin-react';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';
// https://vitejs.dev/config/
export default defineConfig(({command, mode} : ConfigEnv) => {
console.log(`configuring vite with command: ${command}, mode: ${mode}`); // command: serve, mode: development
// suppress eslint warning that process isn't defined
// eslint-disable-next-line
const cwd = process.cwd();
console.log(`loading env from ${cwd}`);
// load all entries in the .env files that are prefixed with VITE_
const env = {...loadEnv(mode, cwd, 'MY_')};
console.log(`env: ${JSON.stringify(env)}`);
return {
base: './',
build: {
...
},
define: {
// this is supposed to make the env vars available to the react app
'process.env': env,
// or maybe this?
__APP_ENV__: JSON.stringify(env),
},
plugins: [react()],
server: {
...
},
};
});
When building or running the server, the desired values were printed in the terminal, but when I printed out the contents of the injected environment variables in the app’s console with the following:
console.log(`env`, import.meta.env);
Only the default environment variables were found:
{
"BASE_URL": "/",
"MODE": "development",
"DEV": true,
"PROD": false,
"SSR": false
}
It turns out that the loadEnv
works nicely for loading environment variable values that you want to use in the config file itself, but if you want to pass them through to the app you *have* to prefix them with VITE_
.
When the environment variables are prefixed with VITE_
, they’re automatically loaded and passed through to the app.
.env
VITE_MY_FLAG=some dev value
.env.production
VITE_MY_FLAG=some prod value
Now, when running in dev mode I’m seeing:
{
"VITE_MY_FLAG": "some dev value",
"BASE_URL": "/",
"MODE": "development",
"DEV": true,
"PROD": false,
"SSR": false
}
And unless you need those VITE_
-prefixed variables in your configuration file itself, you can just drop them entirely:
import react from '@vitejs/plugin-react';
import { ConfigEnv, defineConfig, loadEnv } from 'vite';
// https://vitejs.dev/config/
export default defineConfig(({command, mode} : ConfigEnv) => {
console.log(`configuring vite with command: ${command}, mode: ${mode}`); // command: serve, mode: development
return {
base: './',
build: {
...
},
plugins: [react()],
server: {
...
},
};
});