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.xxxof non-sensitive items (no prefix required) - Within SSR contexts, injecting additional initialization code and enabling additional security features
-
Install varlock and the Vite integration package
Terminal window npm install @varlock/vite-integration varlockTerminal window yarn add @varlock/vite-integration varlockTerminal window pnpm add @varlock/vite-integration varlock -
Run
varlock initto set up your.env.schemafileThis will guide you through setting up your
.env.schemafile, based on your existing.envfile(s). Make sure to review it carefully.Terminal window npm exec -- varlock initTerminal window yarn exec -- varlock initTerminal window pnpm exec -- varlock init -
Enable the Vite config plugin
You must add our
varlockVitePluginto yourvite.config.*file:vite.config.ts import { defineConfig } from 'vite';import { varlockVitePlugin } from '@varlock/vite-integration';export default defineConfig({plugins: [varlockVitePlugin(), otherPlugin()]});
SSR Code Injection
Section titled “SSR Code Injection”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 viavarlock runin this mode.auto-load- injectsimport 'varlock/auto-load';to load your resolved env via the varlock CLIresolved-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.
Accessing environment variables
Section titled “Accessing environment variables”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:
import { ENV } from 'varlock/env';
console.log(import.meta.env.SOMEVAR); // 🆗 still worksconsole.log(ENV.SOMEVAR); // ✨ recommendedWhy use ENV instead of import.meta.env?
Section titled “Why use ENV instead of import.meta.env?”- 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
Within vite.config.*
Section titled “Within vite.config.*”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.
import { defineConfig } from 'vite';import { varlockVitePlugin } from '@varlock/vite-integration';import { ENV } from 'varlock/env';
doSomethingWithEnvVar(ENV.FOO);
export default defineConfig({ /* ... */ });Within HTML templates
Section titled “Within HTML templates”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.
Within other scripts
Section titled “Within other scripts”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.
npm exec -- varlock run -- node ./script.jsyarn exec -- varlock run -- node ./script.jspnpm exec -- varlock run -- node ./script.jsType-safety and IntelliSense
Section titled “Type-safety and IntelliSense”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.
# @generateTypes(lang='ts', path='env.d.ts')# ---# your config items...Managing multiple environments
Section titled “Managing multiple environments”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 @currentEnv root decorator, e.g. APP_ENV. See the environments guide for more information.
Managing sensitive config values
Section titled “Managing sensitive config values”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:
# @defaultSensitive=false# ---NON_SECRET_FOO= # sensitive by default# @sensitiveSECRET_FOO=Or if you’d like to continue using Vite’s prefix behavior:
# @defaultSensitive=inferFromPrefix('VITE_')# ---FOO= # sensitiveVITE_FOO= # non-sensitive, due to prefix