Opinionated Vite plugin for runtime-env
npm install @runtime-env/vite-pluginZero-config Vite plugin for runtime-env.
``sh`
npm install --save-dev @runtime-env/vite-plugin
Before using the plugin, ensure you have the following prerequisites in your project:
1. Define your environment schema
Create a .runtimeenvschema.json file in your project root to define the structure and validation of your environment variables:`
json`
{
"type": "object",
"properties": {
"VITE_API_URL": { "type": "string" }
},
"required": ["VITE_API_URL"]
}
.env
2. Provide local environment variables
Create a (or .env.local, .env.development, etc.) file to provide values for development:`
env`
VITE_API_URL=http://localhost:3000
3. Load the runtime environment
Add a
`/runtime-env.js
> [!IMPORTANT]
> In production, you are responsible for generating and (optionally) interpolating files at startup (e.g., in your Docker entrypoint) using the @runtime-env/cli.
Add the plugin to your vite.config.ts:
`ts
import { defineConfig } from "vite";
import runtimeEnv from "@runtime-env/vite-plugin";
export default defineConfig({
plugins: [runtimeEnv()],
});
`
In JavaScript/TypeScript:
`ts`
// Variables are available globally
const apiUrl = runtimeEnv.VITE_API_URL;
In index.html (Template Interpolation):
`html`
That's it! The plugin automatically handles the following:
- Development: Dynamically serves /runtime-env.js and watches for changes in .env files or your schema.gen-ts
- Build: Only runs to ensure your type definitions are up-to-date. It does not generate runtime-env.js or interpolate index.html, ensuring your build artifacts remain generic and environment-agnostic./runtime-env.js
- Preview: Hooks into the Vite preview server to generate and perform HTML interpolation on the fly, allowing you to test your production build locally.runtime-env.js
- Testing (Vitest): Automatically generates a temporary and injects it into Vitest's setupFiles, providing globalThis.runtimeEnv during your tests.
Vite's built-in import.meta.env is build-time. This means environment variables are "baked into" your JavaScript bundles during the build process, requiring a full rebuild for every environment (e.g., staging, production, or per-customer deployments).
@runtime-env enables the "Build once, deploy anywhere" philosophy. By loading environment variables from a separate /runtime-env.js` file at runtime, you can:
- Use the exact same Docker image or build artifact across all environments.
- Update configuration in seconds without a CI/CD rebuild.
- Ensure strict validation of environment variables via JSON Schema.
For more details on the underlying mechanics and CLI options, refer to the main documentation.