Skip to content

Why is import.meta.env.VITE_MY_VAR undefined?

Short answer

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

text
console.log(import.meta.env.VITE_API_URL) // undefined
TypeError: Cannot read properties of undefined (reading 'VITE_API_URL')   // when using process.env in Vite

Why it happens

  • The variable is named API_URL instead of VITE_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.
  • .env isn't in the project root (or envDir).

How to fix it

  1. Rename public values to VITE_… and read them via import.meta.env.
  2. Set the variable in the host's build settings and trigger a new build.
  3. Keep secrets (OpenAI, Stripe sk_, Supabase secret) out of VITE_ vars and use them in a server or edge function.
bash
# .env (public)
VITE_API_URL=https://api.example.com
VITE_SUPABASE_PUBLISHABLE_KEY=sb_publishable_...
# NOT here: VITE_OPENAI_API_KEY, VITE_STRIPE_SECRET_KEY

Check 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.

Read-only. No writes or row contents.

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.

Sources

Related

Read as Markdown · Scan methodology