Gathering detailed insights and metrics for @julr/vite-plugin-validate-env
Gathering detailed insights and metrics for @julr/vite-plugin-validate-env
Gathering detailed insights and metrics for @julr/vite-plugin-validate-env
Gathering detailed insights and metrics for @julr/vite-plugin-validate-env
✅ Vite plugin for validating your environment variables
npm install @julr/vite-plugin-validate-env
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
172 Stars
89 Commits
7 Forks
2 Watching
1 Branches
6 Contributors
Updated on 27 Nov 2024
TypeScript (98.63%)
HTML (1.05%)
JavaScript (0.32%)
Cumulative downloads
Total Downloads
Last day
20.5%
2,430
Compared to previous day
Last week
9.8%
10,945
Compared to previous week
Last month
2%
41,618
Compared to previous month
Last year
455.9%
346,846
Compared to previous year
3
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 🥲
1pnpm add -D @julr/vite-plugin-validate-env
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.
The easiest way to define the options is to directly define the scheme as follows:
1// vite.config.ts 2import { defineConfig } from "vite"; 3import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env"; 4 5export default defineConfig({ 6 plugins: [ 7 ValidateEnv({ 8 VITE_MY_VAR: Schema.string() 9 }), 10 ], 11})
In case you want to change some plugin options, in particular change the validator (for Zod), you have to set your options as follows:
1import { defineConfig } from "vite"; 2import { z } from 'zod' 3import { ValidateEnv } from "@julr/vite-plugin-validate-env"; 4 5export default defineConfig({ 6 plugins: [ 7 ValidateEnv({ 8 validator: 'zod', 9 schema: { 10 VITE_MY_VAR: z.string() 11 } 12 }), 13 ], 14})
If you want to see what values are being evaluated for the build, for example when running in CI. You can pass the debug
option as follows:
1import { defineConfig } from "vite"; 2import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env"; 3 4export default defineConfig({ 5 plugins: [ 6 ValidateEnv({ 7 debug: true, 8 schema: { 9 VITE_MY_VAR: Schema.string() 10 } 11 }), 12 ], 13})
1import { Schema, ValidateEnv } from "@julr/vite-plugin-validate-env"
2import { defineConfig } from "vite";
3
4export default defineConfig({
5 plugins: [
6 ValidateEnv({
7 // Data types
8 VITE_STRING_VARIABLE: Schema.string(),
9 VITE_BOOLEAN_VARIABLE: Schema.boolean(),
10 VITE_NUMBER_VARIABLE: Schema.number(),
11 VITE_ENUM_VARIABLE: Schema.enum(['foo', 'bar'] as const),
12
13 // Optional variable
14 VITE_OPTIONAL_VARIABLE: Schema.boolean.optional(),
15
16 // Specify string format
17 VITE_AUTH_API_URL: Schema.string({ format: 'url', protocol: true }),
18
19 // Specify error message
20 VITE_APP_PORT: Schema.number({ message: 'You must set a port !' }),
21
22 // Custom validator
23 VITE_CUSTOM_VARIABLE: (key, value) => {
24 if (!value) {
25 throw new Error(`Missing ${key} env variable`)
26 }
27
28 if (value.endsWith('foo')) {
29 throw new Error('Value cannot end with "foo"')
30 }
31
32 return value
33 },
34 }),
35 ],
36})
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:
1// env.ts 2import { defineConfig } from '@julr/vite-plugin-validate-env' 3import { z } from 'zod' 4 5export default defineConfig({ 6 validator: 'zod', 7 schema: { 8 VITE_MY_STRING: z.string().min(5, 'This is too short !'), 9 VITE_ENUM: z.enum(['a', 'b', 'c']), 10 VITE_BOOLEAN_VARIABLE: z.boolean(), 11 } 12})
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 other types than string you must use preprocess
, and transform
, like this:
1// env.ts
2import { defineConfig } from '@julr/vite-plugin-validate-env'
3import { z } from 'zod'
4
5export default defineConfig({
6 validator: 'zod',
7 schema: {
8 // This will transform the string 'true' or '1' to a boolean
9 VITE_BOOLEAN_VARIABLE: z
10 .preprocess((value) => value === 'true' || value === '1', z.boolean()),
11
12 // Will convert the string to a number
13 VITE_NUMBER: z.preprocess((value) => Number(value), z.number()),
14
15 // Will parse the string to an object
16 VITE_OBJECT: z.preprocess(
17 (value) => JSON.parse(value as string),
18 z.object({
19 a: z.string(),
20 b: z.number(),
21 }),
22 ),
23 }
24})
In this case, true
and 1
will be transformed to true
and your variable will be valid and considered as a boolean.
You can also add a env.ts
file at the root of your project to define your environment variables.
1// vite.config.ts 2import { defineConfig } from 'vite' 3import { ValidateEnv } from "@julr/vite-plugin-validate-env"; 4 5export default defineConfig({ 6 plugins: [ValidateEnv()], 7})
1// env.ts 2import { defineConfig, Schema } from '@julr/vite-plugin-validate-env' 3 4export default defineConfig({ 5 VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const), 6})
By default, the plugin is looking for a file named env.ts
at the root of your project. If you want to use a different file, you can specify the path to your file in the plugin options.
1// vite.config.ts 2import { defineConfig } from 'vite' 3import { ValidateEnv } from "@julr/vite-plugin-validate-env"; 4 5export default defineConfig({ 6 plugins: [ValidateEnv({ configFile: 'config/env' })], 7})
This will look for a file named env.ts
in the config
folder at the root of your project. Make sure to not include the file extension in the path as the plugin will automatically search for .js
, .ts
and other valid file extensions.
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 :
1// Built-in validation 2import { defineConfig, Schema } from '@julr/vite-plugin-validate-env' 3 4export default defineConfig({ 5 VITE_AUTH_API_URL: (key, value) => { 6 if (!value) { 7 throw new Error(`Missing ${key} env variable`) 8 } 9 10 if (!value.endsWith('/')) { 11 return `${value}/` 12 } 13 14 return value 15 }, 16})
1// Zod validation 2import { defineConfig } from '@julr/vite-plugin-validate-env' 3import { z } from 'zod' 4 5export default defineConfig({ 6 validator: 'zod', 7 schema: { 8 VITE_AUTH_API_URL: z 9 .string() 10 .transform((value) => value.endsWith('/') ? value : `${value}/`), 11 }, 12})
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.
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:
1/// <reference types="vite/client" /> 2 3type ImportMetaEnvAugmented = import('@julr/vite-plugin-validate-env').ImportMetaEnvAugmented< 4 typeof import('../env').default 5> 6 7interface ImportMetaEnv extends ImportMetaEnvAugmented { 8 // Now import.meta.env is totally type-safe and based on your `env.ts` schema definition 9 // You can also add custom variables that are not defined in your schema 10} 11
If you like this project, please consider supporting it by sponsoring it. It will help a lot to maintain and improve it. Thanks a lot !
MIT License © 2022 Julien Ripouteau
No vulnerabilities found.
No security vulnerabilities found.