Introduction
You’re building a React app with Vite and decide to store sensitive keys or configuration values in a .env file. You set everything up:
VITE_API_KEY="123456"
And then try to log it in your app:
console.log(import.meta.env.VITE_API_KEY);
But what you get is… undefined.
What gives?
The Common Mistake: .env File in the Wrong Directory
The issue usually isn’t Vite’s config, nor is it your JavaScript. The most common culprit is file placement.
Your .env file must be in the root directory of your Vite project — the same level as vite.config.ts or package.json.
✅ Correct:
VITE_STREAM_KEY="abc123"
❌ Incorrect:
STREAM_KEY="abc123" // Will be undefined . Add "VITE_" at prefix
❌ Wrong:
my-app/
└── src/
└── .env
my-app/
├── .env
├── vite.config.ts
├── package.json
└── src/
How Vite Handles Env Variables
Vite only exposes variables that start with the VITE_ prefix to your client-side code. If your variable doesn't use this prefix, it won't show up at all.
✅ Correct:
VITE_STREAM_KEY="abc123"
❌ Incorrect:
STREAM_KEY="abc123" // Will be undefined . Add "VITE_" at prefix
To use the value:
console.log(import.meta.env.VITE_STREAM_KEY);
Bonus: Reloading the Dev Server
Any time you modify the .env file, you must restart the Vite dev server. Otherwise, changes won’t be picked up.
npm run dev
or
yarn dev
Final Debug Tip
To verify all available env variables:
console.log(import.meta.env);
This will show the full list of available Vite-exposed variables at runtime.
Conclusion
If you’re getting undefined from your Vite env variable:
✅ Make sure it starts with VITE_
✅ Place your .env file at the project root
✅ Restart the dev server
A tiny mistake — but it can cost you hours. Hopefully, this post saved you from that!
Top comments (0)