# 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`.

> **Scan box (use the site's ScanBox component):** Check whether your live app has this problem. Paste your URL for a free outside-in scan covering exposed keys, open database rules, CORS and security headers. [Scan my app free →](https://proofforge.live/#scan)

## 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

- [Vite: Env variables and modes](https://vite.dev/guide/env-and-mode)

## Related

- [Fix: secrets in VITE_ / NEXT_PUBLIC_ vars](/fix/vite-env-secrets)
- [Exposed API key checker](/tools/exposed-api-key-checker)
- [Security check for Lovable apps](/check/lovable)
- [Security check for Bolt apps](/check/bolt)
- [All errors](/errors)
