✅ Vite plugin for validating your environment variables

Overview

This Vite plugin allows you to validate your environment variables at build or dev time. This allows your build/dev-server to fail-fast if your setup is misconfigured.

No more CI to restart because you are missing an environment variable, or to realize after 10 minutes of debugging that you forgot a variable 🥲

Features

  • Validate your environment variables at build time. No runtime overhead
  • Totally type-safe
  • Support multiple validation librairies ( Zod, and @poppinss/validator-lite )
  • Parsing, validation, transformation
  • Custom rules and error messages

Installation

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

Usage

vite-plugin-validate-env plugin allows you to validate your env, either with a very simplified builtin validation lib, or with Zod in the most complex cases when you want a very strict validation.

Plugin options

The easiest way to define the options is to directly define the scheme as follows:

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

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

In case you want to change some plugin options, in particular change the validator (for Zod), you have to set your options as follows:

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

Built-in validator

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

export default defineConfig({
  plugins: [
    ValidateEnv({
      // Data types
      VITE_STRING_VARIABLE: Schema.string(),
      VITE_BOOLEAN_VARIABLE: Schema.boolean(),
      VITE_NUMBER_VARIABLE: Schema.number(),
      VITE_ENUM_VARIABLE: Schema.enum(['foo', 'bar'] as const),
      
      // Optional variable
      VITE_OPTIONAL_VARIABLE: Schema.boolean.optional(),

      // Specify string format
      VITE_AUTH_API_URL: Schema.string({ format: 'url', protocol: true }),

      // Specify error message
      VITE_APP_PORT: Schema.number({ message: 'You must set a port !' }),

      // Custom validator
      VITE_CUSTOM_VARIABLE: (key, value) => {
        if (!value) {
          throw new Error(`Missing ${key} env variable`)
        }

        if (value.endsWith('foo')) {
          throw new Error('Value cannot end with "foo"')
        }

        return value
      },
    }),
  ],
})

Zod Validator

To use the Zod validator, you must first install it if you have not already done so

pnpm install zod

Then, you can use it as follows:

// env.ts
export default defineConfig({
  validator: 'zod',
  schema: {
    VITE_MY_STRING: z.string().min(5, 'This is too short !'),
    VITE_ENUM: z.enum(['a', 'b', 'c']),
    VITE_BOOLEAN_VARIABLE: z.boolean(),
  }
})

Beware, there are some limitations if you use Zod. For example, you can't use a boolean or number type directly. Because everything that comes from your .env file is a string by default.

So to validate a boolean you must use preprocess, and transform, like this:

// env.ts
export default defineConfig({
  validator: 'zod',
  schema: {
    VITE_BOOLEAN_VARIABLE: z
      .preprocess((value) => value === 'true' || value === '1', z.boolean())
  }
})

In this case, true and 1 will be transformed to true and your variable will be valid and considered as a boolean.

Dedicated config file

You can also add a env.ts file at the root of your project to define your environment variables.

// vite.config.ts
export default defineConfig({
  plugins: [ValidateEnv()],
})
// env.ts
export default defineConfig({
 VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const),
})

Transforming variables

In addition to the validation of your variables, there is also a parsing that is done. This means that you can modify the value of an environment variable before it is injected.

Let's imagine the following case: you want to expose a variable VITE_AUTH_API_URL in order to use it to call an API. However, you absolutely need a trailing slash at the end of this environment variable. Here's how it can be done :

// Built-in validation
export default defineConfig({
  VITE_AUTH_API_URL: (key, value) => {
    if (!value) {
      throw new Error(`Missing ${key} env variable`)
    }

    if (!value.endsWith('/')) {
      return `${value}/`
    }

    return value
  },
})
// Zod validation
export default defineConfig({
  validator: 'zod',
  schema: {
    VITE_AUTH_API_URL: z
      .string()
      .transform((value) => value.endsWith('/') ? value : `${value}/`),
  },
})

Now, in your client front-end code, when you call import.meta.env.VITE_AUTH_API_URL, you can be sure that it will always end with a slash.

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 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 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
}

License

MIT License © 2022 Julien Ripouteau

You might also like...

Rust dbg! in js powered by rollup/vite plugin system

rollup-plugin-dbg This plugin is also compatible with vite use with rollup import { defineConfig } from "rollup"; import config from "./package.json";

Aug 18, 2022

⚡️🌱 Vite plugin for Twig, transforms twig templates into HTML

⚡️ 🌱 ViteTwig import twig from '@vituum/vite-plugin-twig' export default { plugins: [ twig({ reload: true, root: null, filte

Dec 15, 2022

Some compile-time magic for your Vite project

💛 You can help the author become a full-time open-source maintainer by sponsoring him on GitHub. vite-plugin-compile-time Use this plugin to generate

Dec 15, 2022

Make your Vite projects work in IE11 and other legacy browsers.

vite-plugin-legacy-dev Maybe your Vite project needs work on IE11 or other not support ESM legacy browsers, this plugin can help you! This is only for

Sep 26, 2022

🎉 基于 vite 2.0 + vue 3.0 + vue-router 4.0 + vuex 4.0 + element-plus 的后台管理系统vue3-element-admin

vue3-element-admin 🎉 基于 Vite 2.0 + Vue3.0 + Vue-Router 4.0 + Vuex 4.0 + element-plus 的后台管理系统 简介 vue3-element-admin 是一个后台前端解决方案,它基于 vue3 和 element-plu

Nov 28, 2022

Vite template with TypeScript, Chakra UI, Eslint Airbnb, Prettier

Vite + Typescript + ChakraUI = ❤️ This is a vite template that combines several technologies: Vite React TypeScript ChakraUI Eslint with eslint-config

Mar 26, 2022

Integrate Tauri in a Vite project to build cross-platform apps.

vite-plugin-tauri Integrate Tauri in a Vite project to build cross-platform apps Install Make sure to setup your environment for Tauri development. Th

Dec 15, 2022

A template repository / quick start to build Azure Static Web Apps with a Node.js function. It uses Vue.js v3, Vue Router, Vuex, and Vite.js.

A template repository / quick start to build Azure Static Web Apps with a Node.js function. It uses Vue.js v3, Vue Router, Vuex, and Vite.js.

Azure Static Web App Template with Node.js API This is a template repository for creating Azure Static Web Apps that comes pre-configured with: Vue.js

Jun 25, 2022

⏳ vue3 + electron + ts + vite = mini template

v3-electron 🥳 Electron16 + Vue3 + Vite2 运行项目 # enter the project directory cd v3-electron # install dependency yarn # develop yarn dev # build exe

Nov 11, 2022
Comments
  • collecting all errors, and see

    collecting all errors, and see

    hi @Julien-R44 i'm suggest, collect all errors and display before exit all missing variables.

    My case, the build takes 10 minutes, the plugin reports about missing variable. We add a variable, run the build again, again 10 minutes, and so on...

    similar feature released in znv for backend.

    image

    enhancement 
    opened by reslear 5
  • Allow loading from the `envDir` as specified in Vite config

    Allow loading from the `envDir` as specified in Vite config

    Vite allows specifying an alternate directory for env files with the envDir option, instead of always being the root.

    Can this be implemented here too instead of always looking in the root for the env.ts file and the .env files themselves?

    enhancement 
    opened by BenShelton 2
Releases(v0.2.1)
  • v0.2.1(Nov 19, 2022)

  • v0.2.0(Oct 1, 2022)

  • v0.1.3(Sep 17, 2022)

    What's Changed

    • fix: custom env prefixes by @Julien-R44 in https://github.com/Julien-R44/vite-plugin-validate-env/pull/3

    Full Changelog: https://github.com/Julien-R44/vite-plugin-validate-env/compare/v0.1.2...v0.1.3

    Source code(tar.gz)
    Source code(zip)
  • v0.1.2(Sep 7, 2022)

    Only refactoring here. The builtin validator was extracted into @poppinss/validator-lite

    Full Changelog: https://github.com/Julien-R44/vite-plugin-validate-env/compare/v0.1.0...v0.1.2

    Source code(tar.gz)
    Source code(zip)
  • v0.1.1(Sep 6, 2022)

  • v0.1.0(Sep 5, 2022)

    Zod Validation

    You can now use Zod as a validation library, in cases where you need a stricter validation or if you just prefer it.

    // env.ts
    export default defineConfig({
      validator: 'zod',
      schema: {
        VITE_MY_STRING: z.string().min(5, 'This is too short !').startWith('h').endsWith('/'),
        VITE_ENUM: z.enum(['a', 'b', 'c']),
    	VITE_AUTH_API_URL: z
          .string()
          .transform((value) => value.endsWith('/') ? value : `${value}/`),
      }
    })
    

    Less verbose import.meta.env typing

    Just made a little helper for getting the correct IntelliSense on import.meta.env. Can be used as follows:

    type ImportMetaEnvAugmented = import('@julr/vite-plugin-validate-env').ImportMetaEnvAugmented<typeof import('../env').default>
    
    interface ImportMetaEnv extends ImportMetaEnvAugmented {}
    
    Source code(tar.gz)
    Source code(zip)
  • v0.0.4(Sep 4, 2022)

Owner
Julien Ripouteau
Freelance developer, @adonisjs core member
Julien Ripouteau
A vite plugin that deletes console.log in the production environment

vite-plugin-remove-console A vite plugin that deletes console.log in the production environment English | 中文 Install npm install vite-plugin-remove-co

啝裳 49 Dec 22, 2022
Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse

Vite Vue SSR Starter Vue 3 + Vite + SSR template based on Vite Plugin SSR and inspired by Vitesse Features ⚡️ Vue 3, Vite 2, TypeScript ?? Domain-Driv

Oleg Koval 10 Aug 2, 2022
Vue injects CSS variables

vue-cssvar Vue 注入 CSS 变量控制样式 (兼容 vue2 , vue3) 样例:点击 div。div 以及其 hover伪类会变色。 <template> <div v-css="{a,b}" class="box" @click="changeColor"></div> </t

siluxianren 14 Mar 8, 2022
A Vite plugin for projecting your application onto a remote production page during development.

vite-plugin-proxy-page A Vite plugin for developing an SPA in the context of a deployed production page. What's the Problem? It's an increasingly comm

Alex MacArthur 13 Nov 13, 2022
A Marko plugin for Vite

@marko/vite A Marko plugin for Vite. Installation npm install @marko/vite Example config import { defineConfig } from "vite"; import marko from "@mark

Marko 49 Nov 26, 2022
Vite Svelte plugin to remove console logs in prod.

vite-plugin-svelte-console-remover A Vite plugin that removes all console statements (log, group, dir, error, etc) from Svelte, JS, and TS files durin

Josh Hubbard 29 Oct 13, 2022
A progress bar plugin for Vite.

vite-plugin-progress Display with progress bar when building ?? Install npm i vite-plugin-progress -D # yarn yarn add vite-plugin-progress -D # pn

Jeddy Gong 137 Dec 17, 2022
Laravel plugin for Vite.

Laravel Vite Plugin Introduction Vite is a modern frontend build tool that provides an extremely fast development environment and bundles your code fo

The Laravel Framework 580 Jan 7, 2023
🐝 A vite plugin automatically export files & HMR support

vite-plugin-hot-export Automatically export files with HMR English|简体中文 Why ? When developing, we often need to download some images or svg from the i

Frozen FIsh 54 Nov 12, 2022
Vite plugin for minifying / obfuscating CSS classes in production builds

vite-plugin-class-mangler Vite plugin for minifying / obfuscating classes in production builds. Compatible with Tailwind, inline, or imported styles.

Maxim 28 Dec 22, 2022