ArkEnv

Using ArkEnv in Vite config

Vite doesn't automatically load .env* files when evaluating your vite.config.ts - those variables are only available later in your application code via import.meta.env. If you need environment variables in your config (like setting server.port or conditionally enabling plugins), you'll need to load them manually using Vite's loadEnv helper.

Important

You must have the core arkenv package installed as a dependency in your project. See ArkEnv quickstart for instructions.

Here's how to validate those variables with ArkEnv. The key is defining your schema once with ArkEnv'stype() and reusing it for both server-side config variables and client-exposed VITE_* variables:

vite.config.ts
import arkenvVitePlugin from "@arkenv/vite-plugin";
import arkenv, { type } from "arkenv";
import { defineConfig, loadEnv } from "vite";

const Env = type({
	PORT: "number.port",
	VITE_API_URL: "string",
});

export default defineConfig(({ mode }) => {
	const env = arkenv(Env, { env: loadEnv(mode, process.cwd(), "") });

	return {
		plugins: [arkenvVitePlugin(Env)],
		server: {
			port: env.PORT,
		},
	};
});

Note how the schema is defined once but used in two different places:

  1. Environment variables needed for the Vite config (PORT) are available via loadEnv() and validated by ArkEnv. These server-only variables are not exposed to client code.
  2. Public VITE_* variables that should be available in your client code (like VITE_API_URL) are validated by the @arkenv/vite-plugin. The plugin automatically filters the schema to only expose variables matching the Vite prefix (defaults to VITE_), preventing server-only variables from leaking into the client bundle.