Why is import.meta.env.VITE_MY_VAR undefined?
Vite only exposes variables that start with VITE_, and it bakes them into the bundle at build time. If the name lacks the prefix, the .env file isn't in the project root, or production built without the variable, you get undefined. Fix the name, set it on the host, and rebuild. Anything VITE_ is public, so never put secrets in it.
Last updated 2026-11-25 · Reviewed by ProofForge
The exact error
console.log(import.meta.env.VITE_API_URL) // undefined
TypeError: Cannot read properties of undefined (reading 'VITE_API_URL') // when using process.env in ViteWhy it happens
- The variable is named
API_URLinstead ofVITE_API_URL. - Code uses
process.env.X, which doesn't exist in Vite browser code. - The host didn't have the variable at build time. Changing it later needs a rebuild.
.envisn't in the project root (orenvDir).
How to fix it
- Rename public values to
VITE_…and read them viaimport.meta.env. - Set the variable in the host's build settings and trigger a new build.
- Keep secrets (OpenAI, Stripe
sk_, Supabase secret) out ofVITE_vars and use them in a server or edge function.
# .env (public)
VITE_API_URL=https://api.example.com
VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...
# NOT here: VITE_OPENAI_API_KEY, VITE_STRIPE_SECRET_KEYCheck it's fixed
grep -rn "sk-\|sk_live_\|sb_secret_" dist/ returns nothing after vite build.
Check your live app
A free, read-only public-surface scan. It cannot diagnose private sessions or every cause described above.
FAQ
Can I add my OpenAI key as VITE_OPENAI_API_KEY?
No. Vite inlines it into public JavaScript and anyone can copy it.
Why does it work locally but not in production?
Your local .env isn't deployed. The host needs the variable at build time.
Can I change the prefix?
Yes, with envPrefix, but whatever it matches is still public.