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:
# @defaultSensitive=inferFromPrefix('VITE_')
# @generateTsTypes(path='env.d.ts', importMetaEnv=none)
# ---
# @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 API_PORT shows.
.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. varlock is a dependency of your project, which vp dotenv init adds. Vite+ includes varlock's Vite integration and registers it for you, so vite.config.ts needs no plugin.
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:
vp dotenv initinit 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.
When package.json does not list varlock in dependencies, vp dotenv init first adds it there with vp add varlock@^1.25.0, the range that this version of Vite+ supports. A varlock in devDependencies moves to dependencies with its range, because built server code can import it at run time. varlock init then finds it and does not install it again. A project that uses varlock only through the CLI, such as vp dotenv exec in development scripts, can move it back to devDependencies after init, so that production installs leave it out. A later vp dotenv init moves it to dependencies again. vp dev, vp build, and the other vp dotenv commands use the varlock of your project, and print a warning when its version is outside that range.
vp dotenv init then adapts the new schema that varlock init writes:
- The
EXAMPLE_ITEMplaceholder thatvarlock initwrites is removed. @generateTsTypes(path=env.d.ts)getsimportMetaEnv=none, which leavesimport.meta.envto Vite's own types, because Vite exposes onlyVITE_*variables there. The generated file still typesENVfromvarlock/env.- In a project that serves or builds a client app with Vite (a
vp dev,vp build,vp preview, orvitescript, or anindex.html),@defaultSensitive=falsebecomes@defaultSensitive=inferFromPrefix('VITE_'), so that onlyVITE_*variables are public by default, as in Vite. Items for values that Vite or Node.js tools set, such asMODEandNODE_ENV, become@public, because they are not secrets.initlists the items that this makes sensitive. - When the project already has an
env.d.tsthat varlock did not generate, such as the one of create-vue, the types go toenv.varlock.d.tsinstead, so your file stays as it is.
It also writes the generated types file with varlock codegen, which reads the schema without resolving any value, and sets the file up. When varlock codegen writes no file, init skips the setup and prints a warning.
- When
tsconfig.app.json(or elsetsconfig.json) has anincludethat does not cover the file,initadds the file to it, so TypeScript applies theENVtypes. As in TypeScript, a wildcard does not cover a file in a hidden directory such as.varlock/. When the tsconfig inheritsincludethroughextends, lists its files infiles, or has noincludefor a file in a hidden directory,initcannot tell, and asks you to check. initadds the file tofmt.ignorePatternsinvite.config.ts, because varlock rewrites it in its own style on every load, andvp checkwould report its format. In a workspace package, the setting belongs in the root config, which keeps the format settings of every package, soinitprints the pattern to add there, relative to the root. A types file outside the workspace root needs no pattern, because the formatter does not look there. Whenfmtis not an object literal thatinitcan edit, it prints a warning too, and you add the pattern yourself.- The edits keep the quotes, indentation, and comments of each file. When an added entry makes a line too long for the formatter, run
vp fmt.
When the project has env files of an environment, such as .env.production, init points out that varlock does not load them yet (see Vite modes). For a project that already has .env.schema, vp dotenv init runs varlock init without its prompts, leaves the schema as it is, and sets up its types file. When varlock cannot parse the schema, init keeps your file and fails, and vp dotenv check shows the parse error. When the types file is one of your own, such as the env.d.ts of create-vue, init leaves it too, and asks you to point @generateTsTypes(path=...) at another file, because any command that loads the schema, such as vp dev or vp dotenv check, would replace it. In a client app, init also points out a schema that makes items public by default.
A server without a client bundle, such as an Express or egg app, keeps @defaultSensitive=false, so only the variables that you mark @sensitive are secrets. init says so. Run its commands through vp dotenv exec.
The schema stays plain varlock: varlock run, varlock load, and the varlock editor extensions read it without Vite+.
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() and the @varlock/vite-integration dependency, moves an ssrInjectMode option to dotenv.ssrInjectMode, and keeps varlock and .env.schema as they are. It warns when the varlock range allows versions that this version of Vite+ does not support. See varlock Rules. When a config still adds varlockVitePlugin(), the integration runs twice, and vp dev, vp build, vp preview, and vp test print a warning.
vp dotenv init --no-interactive uses the default answers instead of prompts, for example for a coding agent. In CI or without a terminal, init does the same.
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 stops with exit code 1, and vp test fails before any test runs. vp preview serves the existing build output, so it starts with a warning. Add the value to .env.local and try again. In application code, use the typed ENV object:
import { ENV } from 'varlock/env';
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 codeimport.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.
The .env.schema file
A schema is a .env file with JSDoc-style comments. The comment blocks at the top of the file hold root decorators, which apply to the whole file. A blank line or a # --- divider ends such a block. A comment directly above a variable attaches decorators to that variable.
Common root decorators:
| Decorator | Meaning |
|---|---|
@defaultSensitive=inferFromPrefix('VITE_') | The rule of Vite: VITE_* is public, everything else is sensitive. vp dotenv init writes it. |
@defaultSensitive=false | Every variable is public unless marked @sensitive. Use true to make every variable sensitive. |
@currentEnv=$APP_ENV | The variable that selects the environment, and so which .env.[env] files load. |
@generateTsTypes(path='env.d.ts', importMetaEnv=none) | Write a type declaration for ENV from varlock/env on every load. varlock replaces the file, so use a path that no file of yours has, such as env.varlock.d.ts next to the env.d.ts of create-vue. vp dotenv init adds the file to the tsconfig include and to fmt.ignorePatterns. importMetaEnv=none leaves import.meta.env to Vite's own types. |
Common item decorators:
| Decorator | Meaning |
|---|---|
@required | Fail validation when the value is empty. |
@sensitive | Treat as a secret: never inline into client code, redact in logs. |
@public | Treat 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:
.env.schema: the committed schema and default values.env: loaded, but prefer the files below.env.local: your machine-only values, git-ignored.env.[env]: values for one environment, for example.env.production.env.[env].local: machine-only values for one environment, git-ignored- The process environment: a variable already set in the shell always wins
[env] is the value of the variable that @currentEnv names. A schema without @currentEnv, like the one above, loads no .env.[env] file in vp dev, vp build, vp preview, and vp test (see Vite modes). With @currentEnv=$APP_ENV, set the variable for the run:
APP_ENV=staging vp buildTo keep the schema somewhere other than the project root, set varlock.loadPath in package.json. vp dotenv init does not support this layout yet and fails, because varlock init writes .env.schema in the project root, where varlock does not look. Write the schema in that directory yourself, and add the dependency with vp add varlock@^1.25.0. 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, and every test project, including defineProject files and projects with extends: false, gets its values. Each project config looks for the schema in its own root, or else in the directory where you run vp. So vp test at the workspace root does not load the .env.schema of a package whose config sets no root. Set root: import.meta.dirname in that config to load it. When two project configs in one vp test run find 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, so vp build does not load .env.production by itself. Vite still reads .env.[mode] files, but the values that varlock resolves override them, because Vite gives the process environment priority, and varlock does not validate them.
To load the files of one environment, add @currentEnv to the schema header, declare its variable as an item, and set the variable for each run:
# @defaultSensitive=inferFromPrefix('VITE_')
# @currentEnv=$APP_ENV
# @generateTsTypes(path='env.d.ts', importMetaEnv=none)
# ---
# @public @type=enum(development, staging, production, test)
APP_ENV=developmentAPP_ENV=production vp build
APP_ENV=test vp testvp dev, vp build, vp preview, and vp test print a warning when the Vite mode and the varlock environment differ and an env file of either one exists: with @currentEnv, when its variable has another value than the mode; without it, when .env.[mode] exists. The warning names the file that varlock loads and the command that selects the mode's files. A variable that you set in the environment for the run turns the warning off.
Planned
A later release will pass the Vite mode to varlock as the default environment, as varlock's Next.js integration does with the Next.js environment. vp build would then load .env.production and vp test .env.test without @currentEnv, and a schema with @currentEnv would keep full control.
Using ENV in vite.config.ts
To read ENV in vite.config.ts, import varlock/auto-load first, as in the varlock documentation:
import 'varlock/auto-load';
import { ENV } from 'varlock/env';
import { defineConfig } from 'vite-plus';
export default defineConfig({
server: { port: ENV.API_PORT },
});varlock/auto-load loads .env.schema from the directory where you run vp. The varlock integration that Vite+ adds then uses the same result when the schema is in that directory, so the schema loads only one time. Without the import, the config cannot read ENV, and the values reach only application code.
The import has costs. Every command that evaluates vite.config.ts loads the schema, also vp lint, vp fmt, vp run, and vp staged. If the env config is invalid, varlock/auto-load prints the errors and ends the process, so these commands fail too, and vp dev cannot show the errors in the browser. The import also patches the console to mask sensitive values, and runs varlock with its own telemetry setting, which Vite+ does not turn off there. 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 buildinlines only public values. After the build writes the client output, Vite+ runsvp dotenv scanon it. If a sensitive value appears there, for example through a hard-coded copy, the scan lists each match and the build fails. A short value that is not a secret, such asHOST=localhost, can match unrelated text: mark its item@public. Seedotenv.scanBuildOutput. import.meta.env. Vite copies everyVITE_*key from the process environment intoimport.meta.env, which reaches the browser. Vite+ removes the keys that varlock treats as sensitive and prints a warning that names them. With anotherenvPrefix, this applies to the keys with that prefix. Vite's ownMODE,DEV,PROD,SSR, andBASE_URLalways stay. varlock also treats a variable as sensitive when an env file sets it but the schema does not declare it, so declare eachVITE_*variable that client code reads in.env.schema. Read sensitive values in server code throughENV.- Logs. In
vp devand in server-side code,console.logand the other console methods print a masked value instead of the secret. Use the@redactroot 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 varlock/env.
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:
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).
varlock installs its native helper for these stores as an optional dependency, 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 that names the files it loaded, so you can see which environment it checked. On failure varlock prints the errors and the command exits with a non-zero code:
vp dotenv checkcheck, print, and explain take --env <name>, which loads .env.[name] and .env.[name].local for a schema without @currentEnv. With @currentEnv, varlock ignores the flag, so the command fails instead and names the variable to set, for example APP_ENV=production vp dotenv check. This applies to the schemas at varlock.loadPath too: when one of its entries sets @currentEnv, varlock ignores the flag for all of them. check warns when --env loaded neither file, which catches a mistyped name.
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. vp dotenv check also fails when varlock loads no file, as with a varlock.loadPath directory that has no schema. 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:
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 itMasked 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:
vp dotenv explain
vp dotenv explain VITE_API_URLvp 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:
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 directoryvp dotenv exec
Run any command with the resolved environment, for scripts and tools that are not Vite:
vp dotenv exec -- node scripts/seed.ts
APP_ENV=production vp dotenv exec -- prisma migrate deployWhen output is piped or redirected, sensitive values are redacted from stdout and stderr. Output to a terminal is not redacted. Redaction replaces every occurrence of a sensitive value, so a short or common value, such as a database password postgres, also masks the same word elsewhere in the output, as in "dialect":"po▒▒▒▒▒". Use values that do not occur in normal output.
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:
echo "$STRIPE_SECRET_KEY" | vp dotenv encrypt # prints varlock("local:...")
vp dotenv encrypt --file .env.local # encrypts sensitive plaintext values in placeWith --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.
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 accessRun vp dotenv keychain --help for every option.
Other varlock commands
vp dotenv wraps the varlock commands that most projects need. Run any other command, such as audit, codegen, reveal, or printenv, with the varlock of your project through vp exec:
vp exec varlock auditPrefer it over vpx varlock, which would download the latest varlock instead of the version in your lockfile.
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:
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.
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:
vp staged
vp dotenv scan --stagedIn 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, which imports varlock at run time. Keep varlock in dependencies, where vp dotenv init adds it, so that a production install includes it.
By default, the startup code reads the environment that varlock run resolves, so start the server through it:
varlock run -- node dist/server/entry.jsvp dotenv exec -- does the same where Vite+ is installed. To let the server load the schema itself, or to write the resolved values into the server output, set dotenv.ssrInjectMode.
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.