Skip to content

Vite

Some frameworks use Vite under the hood, and some projects use Vite directly. Either way, often there is some automatic loading of .env files happening, but it is fairly limited. To integrate varlock into a Vite-powered application, you must use our @varlock/vite-integration package, which is a Vite plugin.

This plugin does a few things:

  • Loading and validating your .env files using varlock, injecting resolved env into process.env at build/dev time
  • Simplifies using env vars within your vite.config.* file
  • Build time replacements of ENV.xxx of non-sensitive items (no prefix required)
  • Within SSR contexts, injecting additional initialization code and enabling additional security features
  1. Install varlock and the Vite integration package

    Terminal window
    npm install @varlock/vite-integration varlock
  2. Run varlock init to set up your .env.schema file

    This will guide you through setting up your .env.schema file, based on your existing .env file(s). Make sure to review it carefully.

    Terminal window
    npm exec -- varlock init
  3. Enable the Vite config plugin

    You must add our varlockVitePlugin to your vite.config.* file:

    vite.config.ts
    import { defineConfig } from 'vite';
    import { varlockVitePlugin } from '@varlock/vite-integration';
    export default defineConfig({
    plugins: [varlockVitePlugin(), otherPlugin()]
    });

Within SSR builds, this plugin will automatically inject varlock initialization code into your entry points. There are 3 modes to choose from and specify during plugin initialization. For example:

varlockVitePlugin({ ssrInjectMode: 'auto-load' })
  • init-only - injects varlock initialization code, but does not load the env vars. You must still boot your app via varlock run in this mode.
  • auto-load - injects import 'varlock/auto-load'; to load your resolved env via the varlock CLI
  • resolved-env - injects the fully resolved env data into your built code. This is useful in environments like Vercel/Cloudflare/etc where you have no control over your build command, and limited access to use CLI commands or the filesystem

If not specified, we will attempt to infer the correct mode based on the presence of other vite plugins and environment variables, which give us hints about how your application will be run. Otherwise defaulting to init-only.

You can continue to use import.meta.env.SOMEVAR as usual, but we recommend using varlock’s imported ENV object for better type-safety and improved developer experience:

example.ts
import { ENV } from 'varlock/env';
console.log(import.meta.env.SOMEVAR); // 🆗 still works
console.log(ENV.SOMEVAR); // ✨ recommended
  • Non-string values (e.g., number, boolean) are properly typed and coerced
  • All non-sensitive items are replaced at build time (not just VITE_ prefixed ones)
  • Better error messages for invalid or unavailable keys
  • Enables future DX improvements and tighter control over what is bundled

It’s often useful to be able to access env vars in your Vite config. Without varlock, it’s a bit awkward, but varlock makes it dead simple - in fact it’s already available! Just import varlock’s ENV object and reference env vars via ENV.SOME_ITEM like you do everywhere else.

vite.config.ts
import { defineConfig } from 'vite';
import { varlockVitePlugin } from '@varlock/vite-integration';
import { ENV } from 'varlock/env';
doSomethingWithEnvVar(ENV.FOO);
export default defineConfig({ /* ... */ });

Vite natively supports injecting env vars into HTML files using a special syntax like %SOME_VAR%.

This plugin injects additional replacements for strings like %ENV.SOME_VAR%.

Note that unlike the native functionality which does not replace missing/non-existant items, we will try to replace all items, and will throw helpful errors if something goes wrong.

Even in a static front-end project, you may have other scripts in your project that rely on sensitive config.

You can use varlock run to inject resolved config into other scripts as regular environment vars.

Terminal window
npm exec -- varlock run -- node ./script.js

To enable type-safety and IntelliSense for your env vars, enable the @generateTypes root decorator in your .env.schema. Note that if your schema was created using varlock init, it will include this by default.

.env.schema
# @generateTypes(lang='ts', path='env.d.ts')
# ---
# your config items...

Varlock can load multiple environment-specific .env files (e.g., .env.development, .env.preview, .env.production).

By default, vite uses its MODE flag to determine which env file(s) to load.

With varlock, instead you set your own environment flag using the @envFlag root decorator, e.g. APP_ENV. See the environments guide for more information.

Vite uses the VITE_ prefix to determine which env vars are public (bundled for the browser). Varlock decouples the concept of being sensitive from key names, and instead you control this with the @defaultSensitive root decorator and the @sensitive item decorator. See the secrets guide for more information.

Set a default and explicitly mark items:

.env.schema
# @defaultSensitive=false
# ---
NON_SECRET_FOO= # sensitive by default
# @sensitive
SECRET_FOO=

Or if you’d like to continue using Vite’s prefix behavior:

.env.schema
# @defaultSensitive=inferFromPrefix('VITE_')
# ---
FOO= # sensitive
VITE_FOO= # non-sensitive, due to prefix