Vite
Type-safe environment variables for Vite apps with the VITE_ prefix.
Use the root zod-config export with clientPrefix: "VITE_" and pass import.meta.env as runtimeEnv.
Define the schema
import { loadEnvConfig } from 'zod-config';
import { z } from 'zod';
export const env = loadEnvConfig({
clientPrefix: 'VITE_',
client: {
VITE_API_URL: z.url(),
VITE_SENTRY_DSN: z.string().optional(),
},
runtimeEnv: import.meta.env,
});import { env } from './env';
env.VITE_API_URL; // stringVite exposes only VITE_-prefixed variables to client code, on import.meta.env, and replaces them statically at build time. Vite's envPrefix option changes the prefix; if you change it, pass the same value as clientPrefix.
Validate when Vite starts
In a single-page app, env.ts runs in the browser, so validation happens when the app loads, not at build. To stop vite dev and vite build on a missing or invalid variable instead, add the zodConfigEnv plugin. It finds env.ts in src/ or the project root and runs it with jiti, so install jiti if you don't have it already:
npm install -D jitiimport { } from 'vite';
import { } from 'zod-config/vite';
export default ({
: [()],
});- The command stops before anything is built, with the same
Invalid environment variablesmessage. - While the plugin runs
env.ts,import.meta.envholds the values the way Vite reads them: the.envfiles of the current mode, thenprocess.env, plus Vite'sMODE,DEV,PRODandBASE_URL. - Path aliases come from
resolve.aliasin the Vite config, or thepathsoftsconfig.json. - The dev server restarts when
env.tschanges, and checks it again. - The plugin only validates. It does not change the bundle: Vite still decides which variables reach the browser.
- It does nothing under Vitest or
vite preview, so a test run does not need every variable. - It works with Vite 5 and later, and with frameworks built on Vite, such as TanStack Start and Astro.
- The file is somewhere else? Pass its path, from the Vite root:
zodConfigEnv({ file: 'config/env.ts' }).
With server-side rendering, add a server schema. On the server, server variables are read from runtimeEnv first, then process.env. In the browser they are never read, and accessing one throws.
Types for import.meta.env
loadEnvConfig returns typed values on its own. If you also read import.meta.env directly, declare your variables in src/vite-env.d.ts as the Vite docs describe:
interface ImportMetaEnv {
readonly VITE_API_URL: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}