Zod 26 🛡️ Vite Environment Variables — Validating import.meta.env at build time
Vite exposes environment variables as strings on import.meta.env, and the VITE_ prefix marks the ones that are bundled into the client code . Without validation, a missing VITE_API_URL becomes undefined at runtime, and the failure surfaces when the first API call fails in the browser—not when the build ran. Zod closes that gap: a schema parses import.meta.env during the Vite config resolution, and the build halts if any variable is missing or malformed. The plugin ecosystem has converged on this pattern, with vite-plugin-validate-env and @julr/vite-plugin-validate-env both hooking into the config phase to validate before the app is served or bundled .
This chapter covers the two approaches to build-time validation: the plugin that validates and injects the parsed values, and the manual loadEnv pattern that validates without a plugin. The sections that follow walk through the plugin setup, the schema definition, and the coercion rules that handle Vite’s string-only environment.
Key point: Vite exposes all env variables as strings, so a Zod schema for import.meta.env must coerce numbers and booleans; validate at build time by parsing the schema inside vite.config.ts or by using a validation plugin that hooks the config resolution phase.
a. The plugin approach
vite-plugin-validate-env is a zero-dependency plugin that validates environment variables at build and dev time, using any Standard Schema library—Zod, Valibot, ArkType—under the hood . The plugin hooks directly into Vite’s config resolution, loads the environment variables for the current mode, and halts the process if the schema fails. The parsed values, including defaults and transformations, are propagated back into import.meta.env, so the application code receives the coerced types rather than the raw strings.
The setup is two files. The first is the schema, in a file that both the plugin and the application can import. The second is the Vite config, where the plugin is registered with the schema.
// src/env.ts
import { z } from "zod";
export const envSchema = z.object({
VITE_API_URL: z.string().url(),
VITE_APP_NAME: z.string().min(1),
VITE_PORT: z.coerce.number().default(3000),
VITE_FEATURE_FLAG: z.string().transform((val) => val === "true"),
});
declare global {
interface ImportMetaEnv extends z.infer<typeof envSchema> {}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
}
The declare global block augments the ImportMetaEnv interface so import.meta.env.VITE_PORT is typed as number, not string. Without this augmentation, the application code would have the correct runtime value but the wrong compile-time type, and the coercion would be invisible to the type system.
// vite.config.ts
import { defineConfig } from "vite";
import { validateEnv } from "vite-plugin-validate-env";
import { envSchema } from "./src/env";
export default defineConfig({
plugins: [validateEnv(envSchema)],
});
The plugin validates only the variables that match Vite’s envPrefix (default VITE_) unless the prefix option is explicitly set to "" . A variable without the prefix is not exposed to the client and is not validated by the plugin by default, which is the correct behavior for server-side secrets.
@julr/vite-plugin-validate-env is the alternative, with a built-in validator for simple cases and a validator: 'standard' mode for Zod . It requires explicit coercion because Vite’s env values are strings: VITE_PORT: z.preprocess((val) => Number(val), z.number()) and VITE_DEBUG: z.preprocess((val) => val === "true" || val === "1", z.boolean()) . The plugin choice is a matter of the API surface; both validate at build time and fail the process before the app runs.
b. The manual loadEnv pattern
A project that does not want a plugin can validate inside the Vite config with loadEnv, which loads the .env files for the current mode. The schema parses the returned object, and a thrown error halts the config resolution.
// vite.config.ts
import { defineConfig, loadEnv } from "vite";
import { z } from "zod";
const envSchema = z.object({
VITE_API_URL: z.string().url(),
VITE_PORT: z.coerce.number().default(3000),
});
export default defineConfig(({ mode }) => {
const env = loadEnv(mode, process.cwd(), "");
envSchema.parse(env);
return {};
});
The loadEnv call returns all variables, including those without the VITE_ prefix. The schema can validate the server-side secrets alongside the client-side variables, which is useful when the build step needs a database URL or an API key that never reaches the client. The parse call throws a ZodError on failure, and Vite reports the error during startup.
The trade-off is that the manual pattern does not propagate the parsed values back into import.meta.env. The application code still reads the raw strings, and the coercion happens only in the config. To get typed values in the application, the schema must be re-parsed at the application boundary, or the plugin must be used. The manual pattern is for validation, not for injection.
The T3 Env library takes a third approach: it provides a createEnv function that validates and types the environment, and it is called both in the config (for build-time validation) and in the application (for runtime access) . The discussion in the T3 Env repository notes that the config call is the part most people miss, and that createEnv does not auto-validate at build time unless it is invoked in vite.config.ts .
c. Coercion and the string-only constraint
Vite exposes every environment variable as a string, regardless of the value in the .env file . A VITE_PORT=3000 is the string "3000", and a VITE_DEBUG=true is the string "true". The schema must coerce the strings to the types the application expects, and the coercion must handle the empty-string case.
// Number: coerce, with a default for absence
VITE_PORT: z.coerce.number().default(3000),
// Boolean: string comparison, not Boolean() coercion
VITE_DEBUG: z.string().transform((val) => val === "true"),
// JSON: parse the string
VITE_CONFIG: z.string().transform((val) => JSON.parse(val)),
z.coerce.boolean() is the wrong choice for a string "false", because Boolean("false") is true . The correct pattern is a string comparison or a .preprocess that maps "true" and "1" to true and everything else to false. The same applies to numbers: z.coerce.number() on an empty string produces 0, which may be a valid number but not the intended default; z.coerce.number().default(3000) applies the default only when the value is undefined, not when it is "".
The emptyStringAsUndefined option in some libraries addresses this by treating "" as absent, so the schema’s .default() or .optional() applies . Vite itself does not have this option; the schema must handle the empty string explicitly if the .env file may contain blank values.
Complete Example Session
// ============================================
// PART 1: THE SCHEMA
// ============================================
// src/env.ts
import { z } from "zod";
export const envSchema = z.object({
VITE_API_URL: z.string().url(),
VITE_APP_NAME: z.string().min(1),
VITE_PORT: z.coerce.number().default(3000),
VITE_DEBUG: z.string().transform((val) => val === "true"),
});
declare global {
interface ImportMetaEnv extends z.infer<typeof envSchema> {}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
}
// ============================================
// PART 2: THE VITE CONFIG WITH THE PLUGIN
// ============================================
// vite.config.ts
import { defineConfig } from "vite";
import { validateEnv } from "vite-plugin-validate-env";
import { envSchema } from "./src/env";
export default defineConfig({
plugins: [validateEnv(envSchema)],
});
// ============================================
// PART 3: THE .env FILE
// ============================================
// .env
// VITE_API_URL=https://api.example.com
// VITE_APP_NAME=My App
// VITE_PORT=8080
// VITE_DEBUG=true
// ============================================
// PART 4: APPLICATION CODE (TYPED)
// ============================================
// src/api.ts
// import.meta.env.VITE_PORT is number
// import.meta.env.VITE_DEBUG is boolean
const baseUrl = import.meta.env.VITE_API_URL;
const port = import.meta.env.VITE_PORT; // number, not string
const debug = import.meta.env.VITE_DEBUG; // boolean, not string
// ============================================
// PART 5: THE FAILURE
// ============================================
// If VITE_API_URL is missing or invalid:
// The build halts with a ZodError before the app is served.
The parts covered the schema with coercion, the plugin registration, the .env file, the typed application code, and the build-time failure.
Quick Reference
Validation Approaches
| Approach | Validates | Injects Parsed Values |
|---|---|---|
vite-plugin-validate-env | Yes | Yes |
@julr/vite-plugin-validate-env | Yes | Yes |
Manual loadEnv + parse | Yes | No |
T3 Env createEnv in config | Yes | Yes |
Coercion Patterns
| Type | Pattern | Wrong Pattern |
|---|---|---|
| Number | z.coerce.number().default(n) | — |
| Boolean | z.string().transform(v => v === "true") | z.coerce.boolean() |
| JSON | z.string().transform(JSON.parse) | — |
| Optional | .optional() or emptyStringAsUndefined | — |
Vite Env Rules
| Rule | Detail |
|---|---|
| All values are strings | Coerce before use |
VITE_ prefix | Exposed to client |
| Non-prefixed | Server-side only |
.env priority | Mode-specific over generic |
Best Practices
✅ Do This:
// Coerce numbers explicitly
VITE_PORT: z.coerce.number().default(3000) // ✅
// Handle booleans with string comparison
VITE_DEBUG: z.string().transform(v => v === "true") // ✅
// Validate at build time
validateEnv(envSchema) // ✅
// Augment ImportMetaEnv for typing
declare global { interface ImportMetaEnv extends ... } // ✅
❌ Don’t Do This:
// Use coerce.boolean on Vite env
VITE_DEBUG: z.coerce.boolean() // "false" → true // ❌
// Read import.meta.env without validation
const url = import.meta.env.VITE_API_URL; // undefined possible // ❌
// Assume the type is number
const port: number = import.meta.env.VITE_PORT; // string // ❌
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
undefined at runtime | Missing variable, no validation | Add schema and validate |
"false" becomes true | z.coerce.boolean() | String transform |
Type is string, expected number | No coercion | z.coerce.number() |
| Validation not running | Plugin not registered | Add to vite.config.ts |
| Server secret exposed | VITE_ prefix on secret | Remove prefix |
Real-World Examples
1. Plugin registration
plugins: [validateEnv(envSchema)]
2. URL validation
VITE_API_URL: z.string().url()
3. Number coercion
VITE_PORT: z.coerce.number().default(3000)
4. Boolean transform
VITE_DEBUG: z.string().transform(v => v === "true")
5. JSON parsing
VITE_CONFIG: z.string().transform(JSON.parse)
6. Manual loadEnv
const env = loadEnv(mode, process.cwd(), "");
envSchema.parse(env);
7. Type augmentation
interface ImportMetaEnv extends z.infer<typeof envSchema> {}
8. Application access
const port = import.meta.env.VITE_PORT; // typed as number
9. Optional variable
VITE_SENTRY_DSN: z.string().optional()
10. Failure output
ZodError: VITE_API_URL: Invalid url
Visual
Build-Time Validation Flow
┌─────────────────────────────────────────────────────────┐
│ vite build │
│ │ │
│ ▼ │
│ loadEnv(mode) → raw strings │
│ │ │
│ ▼ │
│ envSchema.parse() │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ valid invalid │
│ │ │ │
│ ▼ ▼ │
│ build ZodError, │
│ proceeds build halts │
│ │
│ The failure happens before the app is served. │
└─────────────────────────────────────────────────────────┘
Coercion Boundary
┌─────────────────────────────────────────────────────────┐
│ .env file import.meta.env │
│ VITE_PORT=8080 "8080" (string) │
│ │ │
│ ▼ │
│ z.coerce.number() │
│ │ │
│ ▼ │
│ 8080 (number) │
│ │ │
│ ▼ │
│ application code uses number │
└─────────────────────────────────────────────────────────┘
Boolean Trap
┌─────────────────────────────────────────────────────────┐
│ VITE_DEBUG=false │
│ │ │
│ ┌────┴────┐ │
│ ▼ ▼ │
│ coerce string │
│ boolean transform │
│ │ │ │
│ ▼ ▼ │
│ true false │
│ (WRONG) (correct) │
└─────────────────────────────────────────────────────────┘
Type Augmentation
┌─────────────────────────────────────────────────────────┐
│ Without augmentation With augmentation │
│ │
│ import.meta.env.VITE_PORT import.meta.env.VITE_PORT│
│ type: string type: number │
│ runtime: number runtime: number │
│ → type error → type correct │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Env object | import.meta.env |
| All values are strings | Coerce with z.coerce or transform |
VITE_ prefix | Client-exposed |
| Build-time validation | Parse in vite.config.ts |
| Plugin option | vite-plugin-validate-env |
| Boolean coercion | String transform, not z.coerce.boolean |
| Type augmentation | interface ImportMetaEnv extends z.infer<> |
Key takeaways:
- Vite env variables are strings, always. A
VITE_PORT=8080is the string"8080"at runtime, and the schema must coerce it to a number. The type augmentation makes the compile-time type match the runtime type . - Validate at build time, not at runtime. A schema parsed inside
vite.config.tsor a validation plugin halts the build before the app is served. The failure is a missing variable at build, not anundefinedin the browser. - Boolean coercion is a trap.
z.coerce.boolean()turns the string"false"intotrue. Use a string transform that compares the value explicitly . - The plugin injects the parsed values; the manual pattern does not.
vite-plugin-validate-envpropagates defaults and transformations back intoimport.meta.env, so the application receives the coerced types without re-parsing . - The
VITE_prefix is a security boundary. A variable without the prefix is not exposed to the client and should not contain secrets that reach the bundle. Validate both sides, but keep the secrets out of the client-exposed set .
Remember: The environment is a boundary, and Vite’s boundary is string-only. A schema that validates import.meta.env must coerce the strings to the types the application expects, and it must run before the app is served. Use a plugin for injection, use loadEnv for validation-only, and handle booleans with string comparison. The build fails when the environment is wrong; that is the point.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!