Skip to content

Env Files ​

Experimental

vp dotenv and the .env.schema support in vp dev, vp build, vp preview, and vp test are experimental. Commands, options, the dotenv config, and the schema setup that vp dotenv init writes may change.

Use vp dotenv to manage .env files with a committed schema. Vite+ validates environment variables, generates types, keeps secrets out of client bundles and logs, and gives coding agents the structure of your config without the values.

Overview ​

A plain .env.example goes stale the moment someone adds a variable. Vite+ replaces it with .env.schema, a .env file that also declares what each variable is:

.env.schema
env-spec
# @defaultSensitive=inferFromPrefix('VITE_')
# @currentEnv=$APP_ENV
# @plugin(vite-plus)
# @generateVitePlusTypes(path='env.d.ts', importMetaEnv=none)
# ---

# @public @type=enum(development, staging, production, test)
APP_ENV=fallback(viteMode(), development)

# @required @type=url
VITE_API_URL=http://localhost:3000

# @public @type=port
API_PORT=3000

# @required @sensitive @type=string(startsWith=sk_)
STRIPE_SECRET_KEY=

@defaultSensitive=inferFromPrefix('VITE_') follows the rule of Vite: VITE_* variables are public, and all other variables are sensitive. Mark a public variable without the prefix with @public, as APP_ENV and API_PORT show. APP_ENV follows the Vite mode through viteMode(), so vp build loads .env.production as in Vite (see Vite modes).

.env.schema is committed to git. Your real values stay in .env.local, which is git-ignored. When the project root has a .env.schema file, vp dev, vp build, vp preview, and vp test load the schema, layer your local values on top, and validate the result before any code runs.

The schema format is @env-spec, and vp dotenv is powered by varlock. Vite+ bundles varlock and its Vite integration, so there is nothing to install or register.

vp env vs vp dotenv

vp env manages Node.js and package-manager versions. vp dotenv manages .env files. They are unrelated.

Quick start ​

Run vp dotenv init in a project that already has .env files:

bash
vp dotenv init

init scans your .env files and your code, writes .env.schema with decorators inferred for each variable, and adds !.env.schema to .gitignore when the file would otherwise be ignored. Review the schema. Make sure that each secret is sensitive, and that each variable for client code is public.

vp dotenv init then adapts the schema that varlock init writes:

  • @generateTsTypes(path=env.d.ts) becomes @plugin(vite-plus) and @generateVitePlusTypes(path=env.d.ts, importMetaEnv=none). The Vite+ generator writes the same types, and also makes them apply to ENV from vite-plus/dotenv. importMetaEnv=none leaves import.meta.env to Vite's own types, because Vite exposes only VITE_* variables there.
  • @defaultSensitive=false becomes @defaultSensitive=inferFromPrefix('VITE_'), so that only VITE_* variables are public by default, as in Vite.
  • A schema without @currentEnv gets @currentEnv=$APP_ENV and an APP_ENV item with fallback(viteMode(), development), so that the environment follows the Vite mode. Its enum lists development, production, test, and the environments of your .env.[env] files.

Your project needs no varlock dependency. Vite+ bundles the CLI and the runtime, and the generated types reach ENV through vite-plus/dotenv. varlock init adds varlock to package.json by default, but vp dotenv init prevents that and leaves package.json unchanged. Add varlock yourself only in these cases:

  • Code imports ENV from varlock/env and you use TypeScript, which must resolve that module from your project.
  • A production server starts with varlock run (see Server-side rendering).

If you add it, use the version that Vite+ bundles (vp --version lists it). The Vite integration runs the varlock CLI that it finds in your project's node_modules/.bin, and another version can change the output that the integration reads. In a project without vite-plus in node_modules, vp dotenv init runs varlock init unchanged.

A project that already uses varlock through @varlock/vite-integration can run vp migrate (vp migrate --full on a project that already uses Vite+). It removes varlockVitePlugin(), switches the schema to @generateVitePlusTypes, and removes the varlock dependencies that nothing else uses. See varlock Rules.

In CI or for a coding agent, run vp dotenv init --no-interactive to use the default answers instead of prompts.

From now on, vp dev validates before it serves the app. When a required value is missing or has the wrong type, the terminal and the browser show varlock's error. vp build and vp preview stop with exit code 1, and vp test fails before any test runs. Add the value to .env.local and try again. In application code, use the typed ENV object:

src/api.ts
ts
import { ENV } from 'vite-plus/dotenv';

fetch(`${ENV.VITE_API_URL}/items`); // string, inlined at build time
ENV.API_PORT; // number, not string
ENV.STRIPE_SECRET_KEY; // sensitive: never inlined into client code

import.meta.env.VITE_* keeps working for the VITE_* variables that the schema declares (see Sensitive values). ENV is the recommended API: it is typed, it coerces numbers and booleans, and a variable marked @public reaches client code without the prefix. Code that imports ENV from varlock/env, as in the varlock documentation, gets the same object. With TypeScript, that import needs a direct varlock dependency.

The .env.schema file ​

A schema is a .env file with JSDoc-style comments. Lines above # --- hold root decorators, which apply to the whole file. A comment directly above a variable attaches decorators to that variable.

Common root decorators:

DecoratorMeaning
@defaultSensitive=inferFromPrefix('VITE_')The rule of Vite: VITE_* is public, everything else is sensitive. vp dotenv init writes it.
@defaultSensitive=falseEvery variable is public unless marked @sensitive. Use true to make every variable sensitive.
@currentEnv=$APP_ENVThe variable that selects the environment, and so which .env.[env] files load.
@plugin(vite-plus) @generateVitePlusTypes(path='env.d.ts', importMetaEnv=none)Write a type declaration for ENV from vite-plus/dotenv and varlock/env on every load. It takes the options of @generateTsTypes. Add the file to tsconfig.json. importMetaEnv=none leaves import.meta.env to Vite's own types.

Common item decorators:

DecoratorMeaning
@requiredFail validation when the value is empty.
@sensitiveTreat as a secret: never inline into client code, redact in logs.
@publicTreat as public: allow in client code. Use it for a variable without the VITE_ prefix.
@type=<type>Validate and coerce, for example url, port, or enum(a, b).
@docs(url)Link to documentation for the variable.

A value can reference another variable: VITE_API_URL=http://localhost:${API_PORT}. See the varlock documentation for every decorator, type, and value function, including loaders for secret managers such as 1Password.

File loading order ​

Vite+ loads these files from the project root. Later entries override earlier ones:

  1. .env.schema: the committed schema and default values
  2. .env: loaded, but prefer the files below
  3. .env.local: your machine-only values, git-ignored
  4. .env.[env]: values for one environment, for example .env.production
  5. .env.[env].local: machine-only values for one environment, git-ignored
  6. The process environment: a variable already set in the shell always wins

[env] is the value of the variable that @currentEnv names. With the schema above, it follows the Vite mode, so vp build --mode staging loads .env.staging. A value that you set wins over the mode:

bash
APP_ENV=staging vp build

To keep the schema somewhere other than the project root, set varlock.loadPath in package.json. Vite's envDir option is not supported while a schema is active.

Vite+ looks for .env.schema in the root set in vite.config.ts, or else in the directory where you run vp. A root given on the command line, as in vp dev ./app, is not part of this check, so a schema there is not loaded. With dotenv.schema: true, the command fails and names that schema. Run vp from the project directory, or use vp -C ./app dev.

One vp process loads one schema. Every test project, including defineProject files and projects with extends: false, uses the root config's schema. When two project configs in one vp test run have different .env.schema files, the command fails instead of mixing their values. Use one schema at the workspace root, which can @import package files, or run vp test in each package.

When you change an env file, vp dev restarts and loads the new values. A restart without an env file change does not load again, so values from a secret manager or an exec() call stay the same. To get new values from them, stop and start vp dev.

Vite modes ​

varlock selects the environment from the @currentEnv variable, not from Vite's mode. Vite still reads .env.[mode] files, but the values that varlock resolves override them, because Vite gives the process environment priority. To make the environment follow the mode, give the variable the default fallback(viteMode(), development), as vp dotenv init does.

viteMode() comes from @plugin(vite-plus). It returns the mode of vp dev, vp build, vp preview, or vp test: the --mode value, or else the default mode of the command.

CommandviteMode()Files that load
vp devdevelopment.env.development[.local]
vp build, vp previewproduction.env.production[.local]
vp testtest.env.test[.local]
vp build --mode stagingstaging.env.staging[.local]

The mode is only a default. A value from the process environment (APP_ENV=staging vp build) or from an env file wins over it, and so does a value that the schema lists before viteMode() in fallback(). Outside these commands, as in varlock run or a script that runs vite build directly, viteMode() returns nothing and the schema uses the next value. To check the values for one mode, pass the same --mode to vp dotenv check, print, explain, scan, or exec.

Vite+ prints a warning when the mode does not select the varlock environment:

  • With a mode that you pass, when the @currentEnv variable has another value.
  • With the default mode, when .env.[mode] or .env.[mode].local exists, because Vite would read it. A variable that you set in the environment for the run turns this warning off.

The warning names what takes priority, or how to make the schema follow the mode. mode in vite.config.ts does not change viteMode(), because Vite+ reads the mode from the command line. Pass --mode instead.

Using ENV in vite.config.ts ​

vite.config.ts can read ENV too:

vite.config.ts
ts
import { defineConfig } from 'vite-plus';
import { ENV } from 'vite-plus/dotenv';

export default defineConfig({
  server: { port: ENV.API_PORT },
});

The first read loads .env.schema from the directory where you run vp, not from a root that the config sets. vp dev, vp build, vp preview, and vp test then use the same result, so the schema loads only one time. After an env file changes, the vp dev restart gives the config the new values. If the env config is invalid, each read returns undefined with a warning, and the Vite commands report the errors as usual.

A command that runs vite.config.ts for other settings, such as vp lint, then loads the schema too. Prefer ENV to Vite's loadEnv(), which reads the .env files without the schema: it does not validate the values, convert their types, or follow @currentEnv.

Sensitive values ​

A variable is sensitive when the schema marks it @sensitive, or when @defaultSensitive makes it sensitive. inferFromPrefix('VITE_') does that for every variable without the prefix that is not marked @public. A sensitive value is protected in these places:

  • Client bundles. vp build inlines only public values. After the build writes the client output, Vite+ runs vp dotenv scan on it. If a sensitive value appears there, for example through a hard-coded copy, the scan lists each match and the build fails. See dotenv.scanBuildOutput.
  • import.meta.env. Vite copies every VITE_* key from the process environment into import.meta.env, which reaches the browser. Vite+ removes the keys that varlock treats as sensitive and prints a warning that names them. varlock also treats a variable as sensitive when an env file sets it but the schema does not declare it, so declare each VITE_* variable that client code reads in .env.schema. Read sensitive values in server code through ENV.
  • Logs. In vp dev and in server-side code, console.log and the other console methods print a masked value instead of the secret. Use the @redact root decorator in the schema to change this.
  • HTTP responses. Server-side code that would send a sensitive value in a response body throws an error instead.

These are guardrails against accidental exposure, not a sandbox. The running process still holds the plaintext. To print a value on purpose, use revealSensitiveConfig() from vite-plus/dotenv.

Local encryption ​

varlock can encrypt a secret with a key that stays on your device. The env file then holds a reference instead of the plaintext:

.env.local
env
STRIPE_SECRET_KEY=varlock("local:AQQG...")

Every command that loads the schema decrypts the value: vp dev, vp build, vp preview, vp test, the vp dotenv commands, and ENV in vite.config.ts. varlock keeps the key in the most secure store that the device has:

  • macOS: the Secure Enclave, with Touch ID or the login password.
  • Windows: the TPM, with Windows Hello.
  • Linux: TPM2 or the Secret Service, with a polkit or PAM prompt.
  • Otherwise: a key file in your user config directory (~/.config/varlock).

Vite+ installs varlock's native helper for these stores, so the project needs no extra package.

Only the device that encrypted a value can decrypt it. Keep encrypted values in git-ignored files such as .env.local, and give CI and other machines their values another way, for example as CI secrets in the process environment.

To set a value, use vp dotenv encrypt, or write KEY=varlock(prompt) and run a command through vp dotenv exec. varlock then asks for the value, encrypts it, and writes the reference back to the file. Commands that do not give varlock a terminal do not ask: vp dev, vp build, vp preview, vp test, vp dotenv check, and vp dotenv print without --reveal fail with "No encrypted value found" instead. On macOS with Touch ID, varlock asks in a system dialog instead of the terminal.

See the varlock local encryption guide for the setup on each platform.

On macOS, a secret can also stay in the macOS Keychain. The env file then holds a reference such as keychain(service="varlock", account="app:local:STRIPE_SECRET_KEY"), which every command that loads the schema reads through the same helper. Store and manage these items with vp dotenv keychain, or pick an existing item with KEY=keychain(prompt). See the varlock macOS Keychain page.

Commands ​

vp dotenv init ​

Create .env.schema from the existing .env files. See Quick start.

vp dotenv check ​

Validate the resolved values against the schema without printing them, which makes it safe in CI logs. On success it prints a pass: line. On failure varlock prints the errors and the command exits with a non-zero code:

bash
vp dotenv check

--mode <name> sets viteMode(), so that the command checks the values that vp build --mode <name> uses. vp dotenv check --mode production checks the values of vp build. --env <name> selects an environment when the schema does not use @currentEnv. With @currentEnv, set its variable instead, for example APP_ENV=production vp dotenv check.

Every vp dotenv command that loads the config fails when the directory has no .env.schema and no varlock.loadPath, so a check that runs in the wrong directory cannot pass without checking anything. init, lock, keychain, and encrypt without --file do not load it.

vp dotenv print ​

Print the resolved values for other tools. Sensitive values are masked unless you pass --reveal:

bash
vp dotenv print                           # KEY=value lines, secrets masked
vp dotenv print --format json             # a JSON object, secrets masked
vp dotenv print --reveal --format shell   # export lines in plaintext, for `eval`
vp dotenv print --reveal --format env     # plaintext, for a deploy step that needs it

Masked output is for reading. Do not eval it: the shell would get the masked placeholders instead of the values. Treat --reveal output like the contents of .env.local: do not send it to a log.

vp dotenv explain ​

Without an argument, list every item with its value, and mark which ones are sensitive. Sensitive values are masked. With a key, show the definitions, sources, and overrides that produce that one value:

bash
vp dotenv explain
vp dotenv explain VITE_API_URL

vp dotenv scan ​

Search files for plaintext copies of sensitive values. It reports each match with its file and line, and exits with a non-zero code on any match:

bash
vp dotenv scan                           # the project, respecting .gitignore
vp dotenv scan --staged                  # only files staged in Git, for a pre-commit hook
vp dotenv scan --include-ignored dist/   # a build output directory

vp dotenv exec ​

Run any command with the resolved environment, for scripts and tools that are not Vite:

bash
vp dotenv exec -- node scripts/seed.ts
vp dotenv exec --mode production -- prisma migrate deploy

When output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted.

vp dotenv exec runs one command in the schema environment. vp run runs a task from vite.config.ts.

vp dotenv encrypt ​

Encrypt a secret with a key that stays on this device, so that an env file can hold the encrypted value. Pipe the value on stdin, or run the command in a terminal to type it:

bash
echo "$STRIPE_SECRET_KEY" | vp dotenv encrypt   # prints varlock("local:...")
vp dotenv encrypt --file .env.local             # encrypts sensitive plaintext values in place

With --file, varlock lists the sensitive plaintext values of the file and encrypts the ones that you confirm. See Local encryption.

vp dotenv lock ​

End the biometric session of local encryption, so that the next decryption asks for Touch ID, Windows Hello, or another biometric check again. Run it before you leave the computer. A key without biometric support has no session to end, and the command says so.

vp dotenv keychain ​

Manage the macOS Keychain items that keychain() reads (see Local encryption). It passes every argument to varlock keychain, so the subcommands and options are varlock's own. It works on macOS only.

bash
vp dotenv keychain set STRIPE_SECRET_KEY --write-to .env.local   # store a secret, write keychain(...)
vp dotenv keychain import .env.local                             # move sensitive plaintext values in place
vp dotenv keychain list                                          # item metadata, never values
vp dotenv keychain fix-access --path .env.local                  # give varlock's helper access

Run vp dotenv keychain --help for every option.

Using env files in tasks ​

A vp run task starts in a clean environment, so .env values do not reach it by default. To give a task the schema environment, run its command through vp dotenv exec:

vite.config.ts
ts
export default defineConfig({
  run: {
    tasks: {
      seed: { command: 'vp dotenv exec -- node scripts/seed.ts' },
    },
  },
});

The task cache already tracks the .env files that the command reads, so a changed value runs the task again. Tasks that run vp dev, vp build, or vp test need no wrapper, because those commands load the schema themselves.

The clean environment also hides variables that come from your shell or from CI, such as the @currentEnv variable (APP_ENV) or secrets that CI injects. Inside a task, varlock cannot see them until you pass them through. Put APP_ENV in cache.env, so that a change runs the task again. Put secrets in cache.untrackedEnv, so that their values stay out of the cache key. A change to an untracked value does not run the task again.

vite.config.ts
ts
export default defineConfig({
  run: {
    tasks: {
      build: {
        command: 'vp build',
        cache: { env: ['APP_ENV'], untrackedEnv: ['STRIPE_SECRET_KEY'] },
      },
    },
  },
});

Commit hooks and CI ​

Add a scan to the project-owned pre-commit hook so a secret pasted into source never reaches a commit:

.vite-hooks/pre-commit
sh
vp staged
vp dotenv scan --staged

In CI, run vp dotenv check before the build. See Commit Hooks and CI.

Server-side rendering ​

The varlock integration adds startup code to server entry points. Vite+ bundles varlock's runtime into server builds, so the server output does not need varlock at run time. The startup code reads the resolved environment that varlock run injects, so start the server with vp dotenv exec --, or install varlock and use varlock run --.

Coding agents ​

The schema holds names, types, and descriptions. The values live in git-ignored files. Tell your coding agent to read .env.schema to learn the configuration, and never to read .env, .env.local, or other value files. The agent can then add a variable, write its type, and use it in code without seeing a secret.

Disabling ​

Delete .env.schema and Vite+ returns to plain Vite .env behavior. To keep the file but skip loading, set dotenv.schema: false in vite.config.ts.