npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@togglecorp/vite-plugin-validate-env

v2.2.1

Published

✅ Vite plugin for validating your environment variables

Readme

vite-plugin-validate-env

A Vite plugin that validates your environment variables at build or dev time. This helps you catch misconfigurations early by failing fast. No more broken builds or 10 minutes of debugging just to realize you forgot a variable 🥲


✅ Features

  • Validate environment variables at build time only, zero runtime overhead
  • Fully type-safe
  • Supports standard-schema — works with Zod, Valibot, ArkType, and more
  • Built-in parsing, validation, and transformation
  • Custom rules and error messages

Installation

pnpm add -D @julr/vite-plugin-validate-env

Basic Usage

You can use the plugin with the built-in validator for simple use cases, or with libraries like Zod for more advanced schemas.

[!TIP] I would recommend using a dedicated env.ts file to keep your Vite config clean and separate from your environment variable definitions. See the Using a Dedicated env.ts Config File section for more details.

Built-in Validator

// vite.config.ts
import { defineConfig } from 'vite'
import { Schema, ValidateEnv } from '@julr/vite-plugin-validate-env'

export default defineConfig({
  plugins: [
    ValidateEnv({
      validator: 'builtin',
      schema: {
        VITE_MY_VAR: Schema.string()
      }
    }),
  ],
})

Standard Schema Validators

If you want to use Zod or another validator compatible with standard-schema, pass the validator and schema manually:

import { defineConfig } from 'vite'
import { z } from 'zod'
import { ValidateEnv } from '@julr/vite-plugin-validate-env'

export default defineConfig({
  plugins: [
    ValidateEnv({
      validator: 'standard', // 👈
      schema: {
        VITE_MY_VAR: z.string()
      }
    }),
  ],
})

Built-in Validator Examples

ValidateEnv({
  VITE_STRING: Schema.string(),
  VITE_NUMBER: Schema.number(),
  VITE_BOOLEAN: Schema.boolean(),
  VITE_ENUM: Schema.enum(['foo', 'bar'] as const),

  // Optional
  VITE_OPTIONAL: Schema.boolean.optional(),

  // With format and protocol checks
  VITE_API_URL: Schema.string({ format: 'url', protocol: true }),

  // With custom error message
  VITE_PORT: Schema.number({ message: 'You must set a port!' }),

  // Custom validator + transform function
  VITE_URL_SUFFIXED_WITH_SLASH: (key, value) => {
    if (!value) throw new Error(`Missing ${key}`)

    return value.endsWith('/')
      ? value
      : `${value}/`
  },
})

Using Standard Schema

standard-schema provides a common interface for multiple validation libraries.

Here’s how to use it with Zod, Valibot, or ArkType, or any other library that supports it.

import { defineConfig } from '@julr/vite-plugin-validate-env'
import { z } from 'zod'
import * as v from 'valibot'
import { type } from 'arktype'

export default defineConfig({
  validator: 'standard',
  schema: {
    VITE_ZOD_VAR: z.string(),
    VITE_VALIBOT_VAR: v.string(),
    VITE_ARKTYPE_VAR: type.string(),
  },
})

Using a Dedicated env.ts Config File

You can move your env definitions to a separate file like this:

// vite.config.ts
import { defineConfig } from 'vite'
import { ValidateEnv } from '@julr/vite-plugin-validate-env'

export default defineConfig({
  plugins: [ValidateEnv({
    // Optional: you can specify a custom path for the config file
    configFile: 'config/env'
  })],
})
// env.ts
import { defineConfig, Schema } from '@julr/vite-plugin-validate-env'

export default defineConfig({
  validator: "builtin",
  schema: {
    VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const),
  },
})

Typing import.meta.env

In order to have a type-safe import.meta.env, the ideal is to use the dedicated configuration file env.ts. Once this is done, you would only need to add an vite-env.d.ts in src/ folder to augment ImportMetaEnv (as suggested here ) with the following content:

/// <reference types="vite/client" />

type ImportMetaEnvAugmented = import('@julr/vite-plugin-validate-env').ImportMetaEnvAugmented<
  typeof import('../env').default
>

interface ViteTypeOptions {
  // Avoid adding an index type to `ImportMetaDev` so
  // there's an error when accessing unknown properties.
  // ⚠️ This option requires Vite 6.3.x or higher
  strictImportMetaEnv: unknown
}

interface ImportMetaEnv extends ImportMetaEnvAugmented {
  // Now import.meta.env is totally type-safe and based on your `env.ts` schema definition
  // You can also add custom variables that are not defined in your schema
}

Validation without Vite

In some cases, you might want to validate environment variables outside of Vite and reuse the same schema. You can do so by using the loadAndValidateEnv function directly. This function will validate and also load the environment variables inside the process.env object.

[!WARNING] process.env only accept string values, so don't be surprised if a number or boolean variable comes back as a string when accessing it after validation.

import { loadAndValidateEnv } from '@julr/vite-plugin-validate-env';

const env = await loadAndValidateEnv(
  {
    mode: 'development', // required
    root: import.meta.dirname, // optional
  },
  { 
    // Plugin options. Also optional if you 
    // are using a dedicated `env.ts` file
    validator: 'builtin',
    schema: { VITE_MY_VAR: Schema.string() },
  },
);

console.log(env.VITE_MY_VAR);
console.log(process.env.VITE_MY_VAR)

💖 Sponsors

If you find this useful, consider sponsoring me! It helps support and maintain the project 🙏


License

MIT © Julien Ripouteau