Vite Plugin
dotenv-gad ships a Vite plugin that validates your environment variables at dev/build time and exposes the safe, typed subset to your browser code via a virtual module.
Installation
npm install dotenv-gad
No extra packages needed — the plugin is included in the main package.
Setup
1. Create a schema (env.schema.ts):
import { defineSchema } from 'dotenv-gad';
export default defineSchema({
VITE_APP_TITLE: {
type: 'string',
default: 'My App',
docs: 'Application title displayed in the browser',
},
VITE_API_URL: {
type: 'url',
required: true,
docs: 'Backend API base URL',
},
VITE_DEBUG: {
type: 'boolean',
default: false,
docs: 'Enable debug logging in the browser console',
},
DATABASE_URL: {
type: 'string',
sensitive: true,
docs: 'Database connection string (server-only)',
},
});
2. Register the plugin (vite.config.ts):
import { defineConfig } from 'vite';
import dotenvGad from 'dotenv-gad/vite';
export default defineConfig({
plugins: [
dotenvGad({
schemaPath: './env.schema.ts',
}),
],
});
3. Import the validated env in your app:
import { env } from 'dotenv-gad/client';
console.log(env.VITE_APP_TITLE);
console.log(env.VITE_API_URL);
How it works
- During
configureServer(dev) orbuildStart(build), the plugin loads your schema and validates all env vars using Vite's ownloadEnv(respects.env,.env.local,.env.[mode],.env.[mode].local). - The validated env is filtered — only keys matching
clientPrefix(defaultVITE_) and explicitly listedpublicKeysare exposed. Keys markedsensitiveare always excluded. - When you
import { env } from 'dotenv-gad/client', the plugin intercepts the import and returns the filtered object as a virtual module. - A
.d.tsfile is auto-generated so you get full IntelliSense on theenvobject.
Plugin Options
| Option | Type | Default | Description |
|---|---|---|---|
schemaPath | string | './env.schema.ts' | Path to the schema file (relative to project root) |
clientPrefix | string | 'VITE_' | Prefix identifying client-safe env vars |
publicKeys | string[] | [] | Extra keys to expose (even without the prefix) |
envFiles | string[] | [] | Additional .env files to watch for changes |
generatedTypes | boolean | true | Write a .d.ts file for IntelliSense |
typesOutput | string | './dotenv-gad.d.ts' | Where to write the generated .d.ts |
SSR Safety
The plugin only intercepts dotenv-gad/client imports in client bundles. In SSR/server code, the import falls through to the stub module — use loadEnv or EnvValidator directly for server-side env access.
HMR
When you edit .env files or the schema file, the plugin automatically re-validates and hot-reloads the virtual module. If validation fails, you'll see a clear error in both the terminal and browser console.
Error Handling
- Dev server: Validation errors are logged to the terminal. The virtual module throws at import time so the browser shows the error.
- Build: Validation errors abort the build with a clear message.
Example
A complete working example is available at examples/vite-app/.