TExcelTAD
Home › Vite › Vite Env Variables & Modes

Vite Env Variables & Modes

Apps often need different settings per environment: a local API in development, the real one in production, a feature flag for staging. Vite handles this with .env files, import.meta.env and modes.

Built-in variables

Every module can read import.meta.env. Vite always provides:

Variable Type Meaning
import.meta.env.MODE string The current mode ('development', 'production', or custom)
import.meta.env.DEV boolean true when running the dev server
import.meta.env.PROD boolean true in a production build
import.meta.env.SSR boolean true when code runs on the server
import.meta.env.BASE_URL string The base config value, e.g. '/'
js
if (import.meta.env.DEV) {
  console.log('Debug panel enabled');
}

These are replaced statically at build time. In production, import.meta.env.DEV becomes false, the if block becomes dead code, and the minifier removes it entirely.

.env files

Create files in the project root (next to index.html):

text
.env                  # loaded in every mode
.env.local            # every mode, ignored by git
.env.[mode]           # only in that mode, e.g. .env.production
.env.[mode].local     # that mode, ignored by git
bash
# .env
VITE_APP_TITLE=Course Site
VITE_API_URL=http://localhost:3000/api
DB_PASSWORD=super-secret
bash
# .env.production
VITE_API_URL=https://api.example.com

More specific files win: .env.production.local > .env.production > .env.local > .env. Variables that already exist in the shell environment win over all files.

Only VITE_ variables reach your code

Only variables prefixed with VITE_ are exposed to client code. Everything else stays private to Node (for example your config file). This protects you from accidentally shipping secrets to every visitor.

js
console.log(import.meta.env.VITE_API_URL); // 'https://api.example.com' in a build
console.log(import.meta.env.DB_PASSWORD);  // undefined — not exposed

The playground reproduces the loading rules — merge files by priority, then filter by prefix:

js · try it yourself
function loadEnv(mode, files, prefix = 'VITE_') {
  const order = ['.env', '.env.local', `.env.${mode}`, `.env.${mode}.local`];
  const merged = {};
  for (const name of order) Object.assign(merged, files[name] ?? {});
  const exposed = {};
  for (const [k, v] of Object.entries(merged)) if (k.startsWith(prefix)) exposed[k] = v;
  return { MODE: mode, DEV: mode === 'development', PROD: mode === 'production', ...exposed };
}

const files = {
  '.env': { VITE_APP_TITLE: 'Course Site', VITE_API_URL: 'http://localhost:3000/api', DB_PASSWORD: 'secret' },
  '.env.production': { VITE_API_URL: 'https://api.example.com' },
  '.env.staging': { VITE_API_URL: 'https://staging.example.com', VITE_SHOW_BANNER: 'true' },
};

console.log(loadEnv('development', files));
console.log(loadEnv('production', files));
console.log(loadEnv('staging', files));
{"MODE":"development","DEV":true,"PROD":false,"VITE_APP_TITLE":"Course Site","VITE_API_URL":"http://localhost:3000/api"}
{"MODE":"production","DEV":false,"PROD":true,"VITE_APP_TITLE":"Course Site","VITE_API_URL":"https://api.example.com"}
{"MODE":"staging","DEV":false,"PROD":false,"VITE_APP_TITLE":"Course Site","VITE_API_URL":"https://staging.example.com","VITE_SHOW_BANNER":"true"}

Warning: VITE_ variables end up in the JavaScript bundle, readable by anyone. Never put API secrets in them, even with the prefix. Secrets belong on a server.

Note that all values are strings: VITE_SHOW_BANNER=true gives 'true', not true. Compare explicitly: import.meta.env.VITE_SHOW_BANNER === 'true'.

Modes

A mode decides which .env.[mode] file is loaded and what MODE contains.

Command Default mode
vite / vite dev development
vite build production
vite preview production

Override it with --mode:

bash · try it yourself
npx vite build --mode staging
vite v8.3.4 building client environment for staging...
✓ 6 modules transformed.
dist/index.html                 0.48 kB │ gzip: 0.31 kB
dist/assets/index-Cq1Lr9tV.js   2.84 kB │ gzip: 1.37 kB
✓ built in 87ms

The build still produces optimized output (NODE_ENV stays production), but it reads .env.staging. Add scripts for convenience:

json
{
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "build:staging": "vite build --mode staging"
  }
}

Using env in the config file

import.meta.env is not available inside vite.config.js itself — the config decides how env files are loaded. Use the loadEnv helper there:

js
// vite.config.js
import { defineConfig, loadEnv } from 'vite';

export default defineConfig(({ mode }) => {
  const env = loadEnv(mode, process.cwd(), ''); // '' = load all vars, not only VITE_
  return {
    server: { port: Number(env.PORT) || 5173 },
    define: {
      __APP_VERSION__: JSON.stringify(process.env.npm_package_version),
    },
  };
});

Using env in HTML

Vite also replaces %VITE_*% placeholders (and %MODE%, etc.) inside index.html:

html
<title>%VITE_APP_TITLE%</title>

Static replacement in action

Because replacement is textual, code paths for other modes disappear. Here is a simplified version of what happens to your source:

js · try it yourself
const source = `if (import.meta.env.DEV) { enableDebugPanel(); }
fetch(import.meta.env.VITE_API_URL + '/courses');`;

const env = { DEV: false, VITE_API_URL: 'https://api.example.com' };
const replaced = source.replace(/import\.meta\.env\.(\w+)/g, (_, k) => JSON.stringify(env[k]));
console.log(replaced);
if (false) { enableDebugPanel(); }
fetch("https://api.example.com" + '/courses');

The minifier then deletes if (false) { ... } completely.

Test yourself

Which variable from .env is available as import.meta.env.X in client code?

  1. API_KEY
  2. SECRET_TOKEN
  3. VITE_API_URL
  4. All of them

What mode does vite build use by default?

  1. development
  2. production
  3. staging
  4. test

VITE_FEATURE=true is in .env. What is import.meta.env.VITE_FEATURE?

  1. The boolean true
  2. The string 'true'
  3. 1
  4. undefined