{"id":17743108,"url":"https://github.com/julien-r44/vite-plugin-validate-env","last_synced_at":"2025-04-04T20:12:44.133Z","repository":{"id":58572194,"uuid":"532411182","full_name":"Julien-R44/vite-plugin-validate-env","owner":"Julien-R44","description":"✅ Vite plugin for validating your environment variables","archived":false,"fork":false,"pushed_at":"2024-05-03T06:47:15.000Z","size":321,"stargazers_count":167,"open_issues_count":6,"forks_count":6,"subscribers_count":2,"default_branch":"main","last_synced_at":"2024-10-23T10:36:26.463Z","etag":null,"topics":["env-vars","validation","vite-plugin"],"latest_commit_sha":null,"homepage":"","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Julien-R44.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE.md","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":["julien-r44"],"polar":"Julien-R44"}},"created_at":"2022-09-04T01:27:15.000Z","updated_at":"2024-10-10T11:00:20.000Z","dependencies_parsed_at":"2023-11-28T19:28:09.124Z","dependency_job_id":"fef23c2e-226c-4521-9cbf-f4e67d1f7764","html_url":"https://github.com/Julien-R44/vite-plugin-validate-env","commit_stats":null,"previous_names":[],"tags_count":17,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Julien-R44%2Fvite-plugin-validate-env","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Julien-R44%2Fvite-plugin-validate-env/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Julien-R44%2Fvite-plugin-validate-env/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Julien-R44%2Fvite-plugin-validate-env/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Julien-R44","download_url":"https://codeload.github.com/Julien-R44/vite-plugin-validate-env/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247242681,"owners_count":20907134,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["env-vars","validation","vite-plugin"],"created_at":"2024-10-26T05:42:38.921Z","updated_at":"2025-04-04T20:12:44.116Z","avatar_url":"https://github.com/Julien-R44.png","language":"TypeScript","funding_links":["https://github.com/sponsors/julien-r44","https://polar.sh/Julien-R44","https://github.com/sponsors/Julien-R44/"],"categories":[],"sub_categories":[],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://user-images.githubusercontent.com/8337858/188329992-e74b3393-5bec-48b3-bba9-a8c45d279866.png\"\u003e\n\u003c/p\u003e\n\nThis Vite plugin allows you to validate your environment variables at build or dev time. This allows your build/dev-server to [fail-fast](https://en.wikipedia.org/wiki/Fail-fast) if your setup is misconfigured.\n\nNo more CI to restart because you are missing an environment variable, or to realize after 10 minutes of debugging that you forgot a variable 🥲\n\n## Features\n- Validate your environment variables at **build time only**. No runtime overhead\n- Totally type-safe\n- Support [standard-schema](https://github.com/standard-schema/standard-schema), meaning you can use every libraries compatible with it ( Zod, Valibot, ArkType )\n- Parsing, validation and transformation of your variables\n- Custom rules and error messages\n\n## Installation\n\n```sh\npnpm add -D @julr/vite-plugin-validate-env\n```\n\n## Usage\n`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.\n\n### Plugin options \nThe easiest way to define the options is to directly define the scheme as follows: \n```ts\n// vite.config.ts\nimport { defineConfig } from \"vite\";\nimport { Schema, ValidateEnv } from \"@julr/vite-plugin-validate-env\";\n\nexport default defineConfig({\n  plugins: [\n    ValidateEnv({\n      VITE_MY_VAR: Schema.string()\n    }),\n  ],\n})\n```\n\nIn case you want to change some plugin options, in particular change the validator (for Zod), you have to set your options as follows: \n```ts\nimport { defineConfig } from \"vite\";\nimport { z } from 'zod'\nimport { ValidateEnv } from \"@julr/vite-plugin-validate-env\";\n\nexport default defineConfig({\n  plugins: [\n    ValidateEnv({\n      validator: 'zod',\n      schema: {\n        VITE_MY_VAR: z.string()\n      }\n    }),\n  ],\n})\n```\n\nIf 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:\n```ts\nimport { defineConfig } from \"vite\";\nimport { Schema, ValidateEnv } from \"@julr/vite-plugin-validate-env\";\n\nexport default defineConfig({\n  plugins: [\n    ValidateEnv({\n      debug: true,\n      schema: {\n        VITE_MY_VAR: Schema.string()\n      }\n    }),\n  ],\n})\n```\n\n### Built-in validator\n\n```ts\nimport { Schema, ValidateEnv } from \"@julr/vite-plugin-validate-env\"\nimport { defineConfig } from \"vite\";\n\nexport default defineConfig({\n  plugins: [\n    ValidateEnv({\n      // Data types\n      VITE_STRING_VARIABLE: Schema.string(),\n      VITE_BOOLEAN_VARIABLE: Schema.boolean(),\n      VITE_NUMBER_VARIABLE: Schema.number(),\n      VITE_ENUM_VARIABLE: Schema.enum(['foo', 'bar'] as const),\n      \n      // Optional variable\n      VITE_OPTIONAL_VARIABLE: Schema.boolean.optional(),\n\n      // Specify string format\n      VITE_AUTH_API_URL: Schema.string({ format: 'url', protocol: true }),\n\n      // Specify error message\n      VITE_APP_PORT: Schema.number({ message: 'You must set a port !' }),\n\n      // Custom validator\n      VITE_CUSTOM_VARIABLE: (key, value) =\u003e {\n        if (!value) {\n          throw new Error(`Missing ${key} env variable`)\n        }\n\n        if (value.endsWith('foo')) {\n          throw new Error('Value cannot end with \"foo\"')\n        }\n\n        return value\n      },\n    }),\n  ],\n})\n```\n\n### Zod Validator\nTo use the Zod validator, you must first install it if you have not already done so\n```\npnpm install zod\n```\n\nThen, you can use it as follows: \n```ts\n// env.ts\nimport { defineConfig } from '@julr/vite-plugin-validate-env'\nimport { z } from 'zod'\n\nexport default defineConfig({\n  validator: 'zod',\n  schema: {\n    VITE_MY_STRING: z.string().min(5, 'This is too short !'),\n    VITE_ENUM: z.enum(['a', 'b', 'c']),\n    VITE_BOOLEAN_VARIABLE: z.boolean(),\n  }\n})\n```\n\nBeware, 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.\n\nSo to validate other types than string you must use `preprocess`, and `transform`, like this:\n```ts\n// env.ts\nimport { defineConfig } from '@julr/vite-plugin-validate-env'\nimport { z } from 'zod'\n\nexport default defineConfig({\n  validator: 'zod',\n  schema: {\n    // This will transform the string 'true' or '1' to a boolean\n    VITE_BOOLEAN_VARIABLE: z\n      .preprocess((value) =\u003e value === 'true' || value === '1', z.boolean()),\n\n    // Will convert the string to a number\n    VITE_NUMBER: z.preprocess((value) =\u003e Number(value), z.number()),\n\n    // Will parse the string to an object\n    VITE_OBJECT: z.preprocess(\n      (value) =\u003e JSON.parse(value as string),\n      z.object({\n        a: z.string(),\n        b: z.number(),\n      }),\n    ),\n  }\n})\n```\n\nIn this case, `true` and `1` will be transformed to `true` and your variable will be valid and considered as a boolean. \n\n## Dedicated config file\n\nYou can also add a `env.ts` file at the root of your project to define your environment variables.\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport { ValidateEnv } from \"@julr/vite-plugin-validate-env\";\n\nexport default defineConfig({\n  plugins: [ValidateEnv()],\n})\n```\n\n```ts\n// env.ts\nimport { defineConfig, Schema } from '@julr/vite-plugin-validate-env'\n\nexport default defineConfig({\n VITE_MY_VAR: Schema.enum(['foo', 'bar'] as const),\n})\n```\n\n### Custom config file path\n\nBy 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.\n\n```ts\n// vite.config.ts\nimport { defineConfig } from 'vite'\nimport { ValidateEnv } from \"@julr/vite-plugin-validate-env\";\n\nexport default defineConfig({\n  plugins: [ValidateEnv({ configFile: 'config/env' })],\n})\n```\n\nThis 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.\n\n## Transforming variables\nIn 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. \n\nLet'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 :\n\n```ts\n// Built-in validation\nimport { defineConfig, Schema } from '@julr/vite-plugin-validate-env'\n\nexport default defineConfig({\n  VITE_AUTH_API_URL: (key, value) =\u003e {\n    if (!value) {\n      throw new Error(`Missing ${key} env variable`)\n    }\n\n    if (!value.endsWith('/')) {\n      return `${value}/`\n    }\n\n    return value\n  },\n})\n```\n\n```ts\n// Zod validation\nimport { defineConfig } from '@julr/vite-plugin-validate-env'\nimport { z } from 'zod'\n\nexport default defineConfig({\n  validator: 'zod',\n  schema: {\n    VITE_AUTH_API_URL: z\n      .string()\n      .transform((value) =\u003e value.endsWith('/') ? value : `${value}/`),\n  },\n})\n```\n\nNow, 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.\n\n## Typing `import.meta.env`\nIn order to have a type-safe `import.meta.env`, the ideal is to use the dedicated configuration file `env.ts`.\nOnce this is done, you would only need to add an `env.d.ts` in `src/` folder to augment `ImportMetaEnv` (as [suggested here](https://vitejs.dev/guide/env-and-mode.html#env-files) ) with the following content:\n\n```ts\n/// \u003creference types=\"vite/client\" /\u003e\n\ntype ImportMetaEnvAugmented = import('@julr/vite-plugin-validate-env').ImportMetaEnvAugmented\u003c\n  typeof import('../env').default\n\u003e\n\ninterface ImportMetaEnv extends ImportMetaEnvAugmented {\n  // Now import.meta.env is totally type-safe and based on your `env.ts` schema definition\n  // You can also add custom variables that are not defined in your schema\n}\n```\n\n## Standard Schema\n\n\u003e [!WARNING]  \n\u003e As long as standard-schema has not been published in 1.0.0, I will possibly make breaking changes to the API without major release.\n\n[standard-schema](https://github.com/standard-schema/standard-schema) is basically an attempt to standardize the way we can use validation librairies. It means that you can use any library that is compatible with it. As the date of writing, Zod, Valibot, Arktype, ArriSchema are compatible.\n\nHere is an example of how to use it with the plugin:\n\n```ts\nimport { defineConfig } from '@julr/vite-plugin-validate-env'\nimport { z } from 'zod'\nimport * as v from 'valibot'\nimport { type } from 'arktype'\n\nexport default defineConfig({\n  validator: 'standard', // Make sure to use 'standard' validator\n  schema: {\n    // Zod\n    VITE_ZOD_VARIABLE: z.string(),\n\n    // Valibot\n    VITE_VALIBOT_VARIABLE: v.string(),\n\n    // Arktype\n    VITE_ARKTYPE_VARIABLE: type.string(),\n  },\n})\n```\n\nMake sure to upgrade your validation library to the latest version to ensure using a compatible version with standard-schema. For example, Zod minimum version is `3.24.0`.\n\n## Forbid unknown variables\n\nSince we rely on module augmentation to type `import.meta.env`, using unknown variables won’t trigger errors because the `ImportMetaEnv` interface from Vite includes a `[key: string]: string` signature.\n\nTo enforce stricter typing and prevent the use of unknown variables, you can set up the following:\n\n```ts\n// lib/env.ts or wherever you want\nimport { ImportMetaEnvAugmented } from '@julr/vite-plugin-validate-env';\n\nexport const env: ImportMetaEnvAugmented = import.meta.env;\n```\n\nBy using `env` instead of `import.meta.env` in your code, TypeScript will now throw an error if you try to access an unknown variable.\n\n## Sponsors\n\nIf you like this project, [please consider supporting it by sponsoring it](https://github.com/sponsors/Julien-R44/). It will help a lot to maintain and improve it. Thanks a lot !\n\n![](https://github.com/julien-r44/static/blob/main/sponsorkit/sponsors.png?raw=true)\n\n## License\n\n[MIT](./LICENSE.md) License © 2022 [Julien Ripouteau](https://github.com/Julien-R44)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjulien-r44%2Fvite-plugin-validate-env","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjulien-r44%2Fvite-plugin-validate-env","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjulien-r44%2Fvite-plugin-validate-env/lists"}