gotchajavascriptMajor
Vite environment variables: VITE_ prefix and import.meta.env
Viewed 0 times
vite envVITE_ prefiximport.meta.envdotenv viteenvironment secrets
Problem
Environment variables defined in .env files are not accessible in client-side code, or sensitive server-side variables are accidentally exposed to the browser bundle.
Solution
Only variables prefixed with VITE_ are statically injected into the client bundle via import.meta.env. All other variables remain server/Node only.
# .env
VITE_API_URL=https://api.example.com # exposed to client
DB_PASSWORD=secret # NOT exposed
// In client code:
console.log(import.meta.env.VITE_API_URL); // works
console.log(import.meta.env.DB_PASSWORD); // undefined
console.log(import.meta.env.MODE); // 'development' | 'production'
console.log(import.meta.env.DEV); // true in dev
console.log(import.meta.env.PROD); // true in prod
# .env
VITE_API_URL=https://api.example.com # exposed to client
DB_PASSWORD=secret # NOT exposed
// In client code:
console.log(import.meta.env.VITE_API_URL); // works
console.log(import.meta.env.DB_PASSWORD); // undefined
console.log(import.meta.env.MODE); // 'development' | 'production'
console.log(import.meta.env.DEV); // true in dev
console.log(import.meta.env.PROD); // true in prod
Why
Vite performs static string replacement at build time — VITE_ vars become literal strings in the output bundle. Non-prefixed vars are intentionally excluded to prevent secrets from leaking into the public JS bundle.
Gotchas
- .env.local overrides .env and is git-ignored by default
- .env.[mode] files are loaded for that specific mode (e.g. .env.production)
- Vite types import.meta.env as ImportMetaEnv — add custom vars to a vite-env.d.ts file
- import.meta.env is read-only; you cannot mutate it at runtime
Code Snippets
vite-env.d.ts: typing custom VITE_ env vars for TypeScript
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_URL: string;
readonly VITE_FEATURE_FLAG: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}Context
Any Vite project that needs runtime configuration or API URLs that differ between environments
Revisions (0)
No revisions yet.