Julien-R44 / vite-plugin-validate-env

✅ Vite plugin for validating your environment variables
MIT License
164 stars 6 forks source link

Allow validating env vars without prefix #25

Open biesbjerg opened 4 months ago

biesbjerg commented 4 months ago

I'd like to validate env vars coming from .env as well as from the system.

System environment:

EXPORT SENTRY_AUTH_TOKEN=sensitivevalue

.env:

VITE_APP_VAR=publicvalue

vite.config.ts:

export default defineConfig(({ mode, command }) => {
  process.env = {
    ...process.env,
    ...loadEnv(mode, process.cwd(), "VITE_APP_")
  };

  return {
    envPrefix: "VITE_APP_", // Default env prefix
    plugins: [
      // Validate environment variables from .env file prefixed with VITE_APP_
      // that are used in the application and will end up in the bundle
      ValidateEnv({
        validator: "builtin",
        schema: {
          VITE_APP_VAR: Schema.string()
        }
      }),
      [
        // Validate sensitive environment variables from system that doesn't have prefix
        // and should never end up in the bundle
        {
          ...ValidateEnv({
            validator: "builtin",
            schema: {
              SENTRY_AUTH_TOKEN: Schema.string()
            }
          }),
          apply: "build"
        },
        {
          ...sentryVitePlugin({
            authToken: process.env.SENTRY_AUTH_TOKEN // Use sensitive env variable here
          }),
          apply: "build"
        }
      ]
    ]
  };
});

Above won't work because we're only able to validate vars prefixed with envPrefix (VITE_APP_), hence SENTRY_AUTH_TOKEN will always report as missing.

Do you think there's a way to achieve this? Would you accept a PR, and if so, any pointers how you'd like it done?

biesbjerg commented 4 months ago

What do you think of https://github.com/Julien-R44/vite-plugin-validate-env/pull/26 ?

It loads all environment variables, enabling validation, but only exposes variables (through define) if their keys begin with the configured envPrefix.