Environment Variables, Modes, and What Is Public

Environment Variables, Modes, and What Is Public in Vite: A neighborhood print shop is split into two zones that must never be confused.

The Analogy: The Newsletter Press and the Back-Office Safe

A neighborhood print shop is split into two zones that must never be confused. Out front stands a newsletter press: whatever you place on its composing tray is printed onto thousands of identical copies and delivered to every doorstep in the district, where anyone can read it and keep it forever. In the back office sits a locked safe holding the shop's own bank details, vendor contracts, and door codes, none of which is ever meant to leave the building. Your shipped client bundle is the press run on every doorstep, while the server, your CI system, and that back-office safe hold everything the public must never see.

The shop enforces the split with one bright green stamp reading VITE_. A clerk carries a form to the composing tray only if it bears the green stamp, and every unstamped form stays in the back office by default. That stamp is the VITE_ prefix: Vite exposes an environment variable to client code only when its name begins with VITE_, and keeps every other variable server-side. The gate is the prefix and nothing else, so naming is not cosmetic here, it is the whole security boundary.

The press also runs a fill-in-the-blanks pass before printing. Where a form has a named blank the compositor recognizes exactly, such as the API address, the value is pasted in so the printed copy shows the literal text rather than the placeholder. But the compositor matches labels by sight only, so a blank whose name is assembled from a handwritten note, paste whichever key the clerk names today, is left as an empty box, because there is no fixed label to match. That is build-time inlining: Vite replaces a literal import.meta.env.VITE_API_URL with its value, but a computed import.meta.env["VITE_" + key] has no literal to match and is left alone, reading as undefined in the shipped copy.

The failure mode is the one that ends careers: someone clips the back-office safe combination onto a green-stamped form. The press does its job without judgment, pastes the combination in, and prints it onto every doorstep copy in the district. The secret is now public and permanent, because you cannot recall thousands of delivered newsletters, mailing a correction changes nothing, and the only real remedy is to change the lock itself. That is what a real secret behind a VITE_ name becomes: it is inlined into JavaScript that users have already downloaded, so deleting the variable later does not help and the secret must be rotated.


Syntax or Core Structure

Environment variables live in .env files at the project root. Vite loads a fixed set of them per mode, and later files override earlier ones. Only keys beginning with VITE_ are exposed to client code through import.meta.env.

# .env               loaded in every mode
VITE_API_URL=https://api.example.com
VITE_TITLE=Store
LOG_LEVEL=info          # no VITE_ prefix: server-only, never shipped

# .env.production      loaded only for a production build
VITE_API_URL=https://api.prod.example.com
STRIPE_SECRET=set-in-ci # no VITE_ prefix: stays server-side

In client code you read the stamped values off import.meta.env, which also carries the built-in MODE, DEV, and PROD flags.

// only VITE_-prefixed keys exist here; LOG_LEVEL and STRIPE_SECRET are undefined
const api = import.meta.env.VITE_API_URL
if (import.meta.env.DEV) console.log('dev build, api is', api)

Modes are selected by the command: vite runs in development, vite build runs in production, and --mode overrides the name without changing whether it is a build.

vite                       # mode development
vite build                 # mode production
vite build --mode staging  # mode staging, still a production build

Technical Depth: What Ships and What Stays

The load order and the VITE_ gate

Vite layers several .env files: a base .env for every mode, a git-ignored .env.local for machine-specific overrides, and a per-mode file such as .env.production. Later files win. Then a single gate runs, copying only VITE_-prefixed keys into the client-visible set. The model below layers three files for a production build and then applies the gate.

// Vite loads several .env files in a fixed order; later files win.
// Only keys beginning with VITE_ are exposed to client code.
const files = {
  '.env':            { VITE_API_URL: 'https://api.example.com', VITE_TITLE: 'Store', LOG_LEVEL: 'info' },
  '.env.local':      { DATABASE_URL: 'postgres://localhost/dev' },
  '.env.production': { VITE_API_URL: 'https://api.prod.example.com', STRIPE_SECRET: 'set-in-ci' },
};

// Load order for a production build (later overrides earlier).
const order = ['.env', '.env.local', '.env.production'];

const server = {};
for (const name of order) {
  Object.assign(server, files[name]);
}

// The client only ever sees VITE_-prefixed keys.
const client = {};
for (const key of Object.keys(server)) {
  if (key.startsWith('VITE_')) client[key] = server[key];
}

console.log('load order: ' + order.join(' -> '));
console.log('server sees ' + Object.keys(server).length + ' keys');
console.log('client sees ' + Object.keys(client).length + ' keys');
console.log('VITE_API_URL -> ' + client.VITE_API_URL);
console.log('DATABASE_URL on client? ' + (client.DATABASE_URL !== undefined));
console.log('STRIPE_SECRET on client? ' + (client.STRIPE_SECRET !== undefined));

Output:

load order: .env -> .env.local -> .env.production
server sees 5 keys
client sees 2 keys
VITE_API_URL -> https://api.prod.example.com
DATABASE_URL on client? false
STRIPE_SECRET on client? false

The server side accumulates all five keys across the three files, and the production VITE_API_URL correctly overrides the base one because .env.production loads last. The gate then keeps only the two VITE_ keys, so DATABASE_URL and STRIPE_SECRET never reach the client set. That single startsWith('VITE_') check is the entire public and private boundary.

MODE names one thing, DEV and PROD name another

MODE is a label that comes from --mode, defaulting to development for vite and production for vite build. The booleans DEV and PROD are not derived from that label, they come from NODE_ENV, which the command itself sets, because serving is a development process and building is a production process. The consequence trips everyone eventually: a --mode staging build is still a production build, so PROD is true even though MODE is the string staging. The model resolves all three scenarios.

// MODE comes from --mode (default: development for vite, production for vite build).
// DEV and PROD come from NODE_ENV, which the command sets (serve=development, build=production),
// NOT from the mode name. A --mode staging build is still a production build.
function resolve(command, modeFlag) {
  const mode = modeFlag || (command === 'build' ? 'production' : 'development');
  const nodeEnv = command === 'build' ? 'production' : 'development';
  const files = ['.env', '.env.local', '.env.' + mode, '.env.' + mode + '.local'];
  return {
    mode,
    files,
    DEV: nodeEnv !== 'production',
    PROD: nodeEnv === 'production',
  };
}

const scenarios = [
  ['serve', undefined],
  ['build', undefined],
  ['build', 'staging'],
];

for (const [command, modeFlag] of scenarios) {
  const r = resolve(command, modeFlag);
  const label = 'vite' + (command === 'build' ? ' build' : '') + (modeFlag ? ' --mode ' + modeFlag : '');
  console.log(label + ':');
  console.log('  MODE=' + r.mode + '  DEV=' + r.DEV + '  PROD=' + r.PROD);
  console.log('  loads: ' + r.files.join(', '));
}

Output:

vite:
  MODE=development  DEV=true  PROD=false
  loads: .env, .env.local, .env.development, .env.development.local
vite build:
  MODE=production  DEV=false  PROD=true
  loads: .env, .env.local, .env.production, .env.production.local
vite build --mode staging:
  MODE=staging  DEV=false  PROD=true
  loads: .env, .env.local, .env.staging, .env.staging.local

The third scenario is the teaching point. MODE is the string staging, which selects the .env.staging files, but PROD is still true because the command was vite build. Code that gates production behavior on import.meta.env.MODE === 'production' will silently misbehave in a staging build, so gate on import.meta.env.PROD instead whenever you mean is this a build.

CommandMODEDEVPRODPer-mode file loaded
vitedevelopmenttruefalse.env.development
vite buildproductionfalsetrue.env.production
vite build --mode stagingstagingfalsetrue.env.staging

Inlining is exact textual substitution

At build time Vite does not hand your app a live environment object, it rewrites the source text, replacing each literal import.meta.env.VITE_* access with the value as a string constant, exactly the way esbuild's define feature works. Because it is textual and literal-only, a dynamically built key has nothing to match and survives into the output unchanged, where it evaluates to undefined. The model applies a define map to three lines of source.

// Vite inlines import.meta.env.VITE_* by exact textual substitution at build time,
// the same way esbuild's define works: only literal static member access is replaced.
const defines = {
  'import.meta.env.VITE_API_URL': JSON.stringify('https://api.prod.example.com'),
  'import.meta.env.MODE': JSON.stringify('production'),
};

function applyDefines(src) {
  let out = src;
  for (const [from, to] of Object.entries(defines)) {
    out = out.split(from).join(to);
  }
  return out;
}

const source = [
  'const a = import.meta.env.VITE_API_URL;',
  'const key = "API_URL";',
  'const b = import.meta.env["VITE_" + key];',
].join('\n');

console.log('--- source ---');
console.log(source);
console.log('--- after build-time define ---');
console.log(applyDefines(source));

Output:

--- source ---
const a = import.meta.env.VITE_API_URL;
const key = "API_URL";
const b = import.meta.env["VITE_" + key];
--- after build-time define ---
const a = "https://api.prod.example.com";
const key = "API_URL";
const b = import.meta.env["VITE_" + key];

The static access on the first line becomes a plain string literal. The computed access on the last line is untouched, because import.meta.env["VITE_" + key] is not the literal text the define looks for, and at runtime there is no environment object to index, so it reads as undefined. This is why the report I read my variable through a computed key and it is undefined in production is so common: the value was never inlined, because the substitution is textual, not dynamic.


Real World Example: The Postbuild Secret Scan

Because a leaked secret in the client bundle is permanent, teams add a guard that runs after vite build and scans the emitted JavaScript for values that look like secrets, failing the build if it finds one. The model below is that guard: a bundle string that unfortunately contains an inlined Stripe secret and a database URL, and a scanner that checks it against a list of known secret shapes.

// A postbuild guard: scan the emitted client bundle for values that look like secrets.
// If a VITE_-prefixed secret was inlined, it is now a literal string in this file.
const bundle = [
  'const API="https://api.prod.example.com";',
  'const KEY="pk_live_51H8xPUBLISHABLEkeyOK";',
  'const S="sk_live_51H8xSECRETdonotship";',
  'const DB="postgres://admin:hunter2@db.internal:5432/app";',
  'fetch(API+"/checkout",{headers:{Authorization:"Bearer "+KEY}});',
].join('\n');

// Known secret shapes to reject.
const patterns = [
  { name: 'stripe secret key', re: /sk_live_[A-Za-z0-9]+/ },
  { name: 'aws access key id', re: /AKIA[A-Z0-9]{16}/ },
];

const findings = [];
for (const p of patterns) {
  const m = bundle.match(p.re);
  if (m) findings.push(p.name + ' -> ' + m[0]);
}

console.log('bundle bytes scanned: ' + bundle.length);
console.log('patterns checked: ' + patterns.length);
console.log('findings: ' + findings.length);
for (const f of findings) console.log('  LEAK ' + f);
console.log(findings.length ? 'RESULT: fail build' : 'RESULT: ok');

Output:

bundle bytes scanned: 246
patterns checked: 2
findings: 1
  LEAK stripe secret key -> sk_live_51H8xSECRETdonotship
RESULT: fail build

The scan works as designed on the case it knows. It finds the sk_live_ Stripe secret that was inlined because someone named it VITE_STRIPE_SECRET, reports it, and fails the build so that leak never ships. The publishable pk_live_ key is correctly left alone, because publishable keys are designed to be public. On its own terms the guard succeeds and stops a real disaster.

But look at the fourth line of the bundle. The database URL postgres://admin:hunter2@db.internal:5432/app embeds a password and an internal host, and it sails through untouched. Nothing in the pattern list describes its shape, so findings stays at one and the build fails only for the Stripe key.

That gap is worse than a plain miss, because it hides behind a success. Fix the Stripe leak, re-run, and the guard now reports a clean bundle and a passing build while a live database credential is still baked into the JavaScript you ship. The green check becomes evidence for exactly the wrong conclusion.

That is the design flaw, and it is a general one: the scanner is an allowlist of shapes, so it can only ever catch the secret formats someone already thought to encode, and it runs reactively, after the value has already been inlined into the shipped file. A guard like this earns its place as a backstop, but treating its pass as proof of safety is the trap. The durable control is upstream at the VITE_ gate, where never giving a real secret a VITE_ name means it is never a candidate for inlining and there is nothing in the bundle for a scanner to miss.


Common Mistakes

  1. Prefixing a real secret with VITE_ to make it reachable. The prefix is the publish switch, so a VITE_-named secret is inlined into shipped JavaScript. Keep secrets unprefixed and server-side.
  2. Deleting a leaked VITE_ secret and assuming you are safe. The value is baked into bundles users already downloaded, so rotate the secret, because deletion alone does nothing.
  3. Reading a variable through a computed key such as import.meta.env["VITE_" + name]. Inlining is literal-only, so it is never substituted and reads as undefined. Use a static, fully written access.
  4. Gating build behavior on MODE === 'production'. A --mode staging build is still a production build, so use import.meta.env.PROD when you mean is this a build.
  5. Expecting process.env.VITE_X to work in client code. The client sees import.meta.env, not process.env, and process does not exist in the browser build.
  6. Committing .env.local or a populated .env.production. Local and secret-bearing env files belong in .gitignore; commit a .env.example with blank values instead.
  7. Assuming later-loaded files merge key by key with earlier ones. They override whole keys rather than deep-merging, so a partial .env.production still replaces only the keys it names.
  8. Putting a secret in vite.config.js and thinking it is therefore safe. Config runs in Node, but any value you pass into define or hand to client code is shipped, so the Node boundary is not the client boundary.
  9. Believing a passing secret scan means no secrets shipped. A shape-based scan misses formats it does not encode, so it is a backstop, not a guarantee, and the real control is the VITE_ gate.

Best Practices

  • Treat the VITE_ prefix as a publish button. Add it only to values you are comfortable printing on every user's machine, and never to anything sensitive.
  • Keep secrets on the server or in CI. Real credentials belong in unprefixed variables read by server code or injected by the deploy platform, never in the client bundle.
  • Gate environment behavior on PROD and DEV, not MODE. Reserve MODE for choosing which .env file loads, and use the booleans to ask whether this is a build.
  • Commit a .env.example and git-ignore the rest. Document the required keys with blank values so teammates know what to set without ever seeing real ones.
  • Read env values through static, literal accesses. Write import.meta.env.VITE_API_URL directly so inlining can find and replace it, and avoid building the key at runtime.
  • Rotate immediately on any suspected client leak. Because inlined values are permanent in shipped bundles, treat exposure as compromise and change the secret, not just the config.
  • Add a postbuild secret scan as a backstop. Let it fail the build on known secret shapes, while remembering it catches only what it has been taught to recognize.
  • Keep the public surface small and deliberate. Fewer VITE_ keys mean a smaller boundary to reason about, so review every new one as a conscious decision to publish.

Practice Exercises

  1. Predict the gate. Add VITE_ANALYTICS_ID to the base file and SESSION_SECRET to .env.local in the load-order model. Predict the client sees N keys line and which of the two names appears on the client, then run it to check.
  2. Break on staging. Using the mode model, write a check that shows a debug banner only outside production. Show why gating on MODE !== 'production' behaves differently from !import.meta.env.PROD for a --mode staging build.
  3. Explain the undefined. A teammate reads a feature flag through import.meta.env["VITE_" + flagName] and finds it undefined in the production build but working in dev. Using the inlining model, explain the difference and give the one-line fix.
  4. Widen the scan, then question it. Extend the secret-scan model with a pattern that catches the postgres:// URL. Then explain why passing the widened scan still does not prove the bundle is free of secrets, and name the upstream control that does.