skip to content

Why can't a Vite config file read `.env` values through `import.meta.env`, and how does `loadEnv` let those values shape the config?

level: middleimportance: should knowfreq 12%

answer

  1. config runs before env files load
  2. Node code, not app code
  3. loadEnv(mode, envDir, prefixes)
  4. empty prefix returns every key
  5. process.env beats the files

basics

~20 s

The config runs in Node before Vite loads any .env file, and Vite fills import.meta.env only for application code. Calling loadEnv(mode, dir, prefixes) inside a function config reads those .env files and returns their values, merged with matching process.env variables.

solid answer

~40 s

Vite evaluates `vite.config.ts` as Node code, and it deliberately loads `.env*` files only after the config is resolved, because which files to read depends on `root`, `envDir` and the final `mode`. While the config runs, `process.env` holds only what the shell or CI already exported, and `import.meta.env` carries none of those values - with the default config loader it is not defined at all; Vite replaces it only in application modules. To let a file value steer the config, export a function, take `mode` and call `loadEnv(mode, process.cwd(), '')`. It reads `.env`, `.env.local`, `.env.[mode]` and `.env.[mode].local`, keeps keys that match the prefixes (default `'VITE_'`, `''` for all), lets variables already in `process.env` win, and returns strings. It does not write them into `process.env`.

code

typescript · 18 lines
typescript
// vite.config.ts - read the job board's API origin from .env.staging / .env.production
import { defineConfig, loadEnv } from 'vite'

export default defineConfig(({ mode }) => {
  // '' keeps every key, not only VITE_ ones; this runs in Node, never in the browser
  const env = loadEnv(mode, process.cwd(), '')

  if (!env.JOBS_API_ORIGIN) {
    throw new Error(`JOBS_API_ORIGIN is missing for mode "${mode}"`)
  }

  return {
    define: {
      // expose exactly one value, never the whole env object
      __JOBS_API_ORIGIN__: JSON.stringify(env.JOBS_API_ORIGIN),
    },
  }
})

go deeper

for a junior

Recall that the config file cannot use import.meta.env and that loadEnv is the helper Vite exports for reading .env files inside it.

for a middle

Explain why Vite loads .env files only after the config, what each loadEnv argument does, and that variables already in process.env win over the files.

for a senior

Show you keep envDir and loadEnv in sync, validate required values at config time, and never forward an unfiltered env object into define.

for a principal

Weigh build-time configuration read from .env files against values injected at deploy time, and set a team rule for which values a config may read and expose.

## Two different moments A Vite command runs your config **before** it knows which `.env` files to load. The order is: 1. Vite finds `vite.config.ts` and loads it as Node code. By default (`--configLoader bundle`) it bundles the file and its local imports into a temporary file under `node_modules/.vite-temp`, leaving packages external, and imports that; `--configLoader native` imports the original file with the runtime directly, and the experimental `runner` processes it on the fly. 2. Vite calls your exported function with `command` and `mode` and resolves the options it returns. 3. Only then does it read `.env` files, because the set of files depends on `root`, `envDir` and the final `mode` - all things the config itself may change. 4. While it transforms **application** modules, it replaces `import.meta.env.*` with the values that pass the `envPrefix` filter. So during step 2, `process.env` contains only what the shell, the package script or CI exported, and with the default loader `import.meta.env` is not defined at all: reading `import.meta.env.VITE_JOBS_API` inside the config throws. No loader hands the config your `.env` values. ## `loadEnv`, argument by argument `loadEnv(mode, envDir, prefixes = 'VITE_')` reads the files on demand and returns a plain object: | Argument | Meaning | Pitfall | |---|---|---| | `mode` | which `.env.[mode]` and `.env.[mode].local` to read, besides `.env` and `.env.local` | take it from the config function; `'local'` throws because it collides with the `.local` suffix | | `envDir` | the directory to read from | it does not read your config - if the config sets `envDir`, pass that same path, not `process.cwd()` | | `prefixes` | keep only keys that start with one of these | defaults to `'VITE_'`; pass `''` to get every key | Two more rules come from the implementation: - After reading the files, `loadEnv` copies in every **matching variable already in `process.env`**, so a value exported by the shell or CI beats the same key in any file. With `''`, every process variable matches, so the result holds the whole environment. - It **returns** the values and does not write them to `process.env`. Every value is a string. The prefix argument is not `envPrefix`. The argument filters what `loadEnv` hands back to Node code; `envPrefix` decides which variables application code sees through `import.meta.env`, and Vite throws if `envPrefix` is `''`. ## A worked config ```ts import { defineConfig, loadEnv } from 'vite' export default defineConfig(({ mode }) => { const env = loadEnv(mode, process.cwd(), '') if (!env.JOBS_API_ORIGIN) { throw new Error(`JOBS_API_ORIGIN is missing for mode "${mode}"`) } return { define: { __JOBS_API_ORIGIN__: JSON.stringify(env.JOBS_API_ORIGIN) }, } }) ``` `JOBS_API_ORIGIN` has no `VITE_` prefix, so application code never sees it through `import.meta.env`. The config reads it with `''` and exposes exactly one value through `define`. A `define` value must be a string holding a JSON-serializable value or a single identifier, which is why it goes through `JSON.stringify`. ## Rules worth keeping - **Use the function form.** An object config has no `mode` to pass to `loadEnv`. - **Fail loudly.** A missing value is better as a config error at startup than as `undefined` in a shipped bundle. - **Never pass the whole result on.** With `''` it holds every secret in the environment; putting it in `define` would inline them. Which values may be public is a separate subject. - **Call nothing if the app is the only reader.** Vite loads `VITE_` values for application code by itself after the config resolves. - **Restart after editing `.env`.** Vite reads the files when it starts. ## Common shapes - **Toggling a plugin.** Vite ignores falsy entries in `plugins`, so `env.JOBS_ANALYTICS === 'on' && analyticsPlugin()` adds the plugin only when the file says so. - **Comparing booleans.** Every value is a string, so compare `env.JOBS_MOCK_API === 'true'`; a bare `if (env.JOBS_MOCK_API)` is also true for `'false'`. - **Choosing a value per mode.** Put `JOBS_API_ORIGIN` in `.env.staging` and `.env.production` and let `mode` pick the file, instead of a chain of `if (mode === ...)` branches in the config. - **Keeping secrets server-side.** A token the config needs, for example to fetch build metadata, stays in the config's own scope and never goes into `define`. ## What interviewers listen for - The ordering: config first, `.env` files afterwards. - That `loadEnv` is explicit and returns values instead of mutating `process.env`. - That an exported variable outranks the files, and that the prefix argument and `envPrefix` are different controls.

  • A Vite config sets `envDir: 'config/env'`; what goes wrong if it still calls `loadEnv(mode, process.cwd(), '')`?
    `loadEnv` does not read your config; it reads whatever directory you pass. Vite will load the app's `.env` files from `config/env`, while the config reads the project root's files, so the two can see different values or none. Pass the same path you gave `envDir`, resolved the same way.
  • How does Vite load `vite.config.ts` itself, and what does `--configLoader` change?
    With the default `bundle` loader, Vite bundles the config and its local imports into a temporary file under `node_modules/.vite-temp`, leaving packages external, and imports it. `native` imports the original file with the runtime, which needs one that understands its syntax, such as Node.js 22.18+ for TypeScript, and gives the most reliable breakpoints. `runner`, experimental, processes it on the fly. None of them gives the config your `.env` values; those still need `loadEnv`.

  • Vite loads .env files into process.env before the config runs
  • import.meta.env.VITE_ values can be read inside vite.config.ts
  • loadEnv returns only VITE_ keys even when the prefix is empty
  • A value in .env.production overrides one exported by the CI shell
  • loadEnv also writes the values it loads into process.env
  • Spreading the whole loadEnv result into define is a safe shortcut