Skip to content

noahtigner/validate-env-vars

Repository files navigation

validate-env-vars

license latest last commit npm downloads
Coverage Code Quality CodeQL

A lightweight utility to check the presence and validity of environment variables, as specified by a Zod schema

Installation

Using npm:

npm install validate-env-vars --save-dev

Usage Examples

Create an executable JS file to check an .env file against a Zod schema:

#!/usr/bin/env node

import validateEnvVars, {
	envEnum,
	envString,
	envNonEmptyString,
} from 'validate-env-vars';

const envSchema = envObject({
	NODE_ENV: envEnum(['development', 'production', 'test']),
	API_BASE: envString().url(),
	GITHUB_USERNAME: envNonEmptyString(),
});

validateEnvVars({ schema: envSchema });

You may use the predefined env* functions, or create your own using Zod


Programmatically check an .env.production file against a Zod schema:

import validateEnvVars, {
    envEnum,
    envString,
    envNonEmptyString,
} from 'validate-env-vars';

const envSchema = envObject({
	NODE_ENV: envEnum(['development', 'production', 'test']),
	API_BASE: envString().url(),
	GITHUB_USERNAME: envNonEmptyString(),
});

const prefilight() => {
    try {
        validateEnvVars({ schema: envSchema, envPath: '.env.production' })
        // ... other code
    }
    catch (error) {
        console.error(error);
        // ... other code
    }
}

Check env vars before Vite startup and build:

  1. Define a Zod schema in a .ts file at the root of your project
import validateEnvVars, {
    envEnum,
    envString,
    envNonEmptyString,
} from 'validate-env-vars';

const envSchema = envObject({
	NODE_ENV: envEnum(['development', 'production', 'test']),
	VITE_API_BASE: envString().url(),
	VITE_GITHUB_USERNAME: envNonEmptyString(),
});

// make the type of the environment variables available globally
declare global {
    type Env = z.infer<typeof envSchema>;
}

export default envSchema;
  1. Import validateEnvVars and your schema and add a plugin to your Vite config to call validateEnvVars on buildStart
import { defineConfig } from 'vitest/config';
import envConfigSchema from './env.config';
import validateEnvVars from 'validate-env-vars';

export default defineConfig({
  plugins: [
    {
      name: 'validate-env-vars',
      buildStart: () => validateEnvVars({ schema: envConfigSchema }),
    },
    // other plugins...
  ],
  // other options...
  1. Enable typehints and intellisense for the environment variables in your vite-env.d.ts
/// <reference types="vite/client" />

interface ImportMetaEnv extends globalThis.Env {}

interface ImportMeta {
	readonly env: ImportMetaEnv;
}
  1. Add your schema configuration file to your tsconfig's include

Tips:

  • If you don't have a .env file, you can pass an empty file. This is useful for testing and CI/CD environments, where environment variables may be set programmatically.

Config Options

Option Type Description Default
schema EnvObject The schema to validate against
envPath (optional) string The path to the .env file .env
exitOnError (optional) boolean Whether to exit the process or throw if validation fails false
logVars (optional) boolean Whether to output successfully parsed variables to the console true

About

A lightweight utility to check an .env file for the presence and validity of environment variables, as specified via a template file or the command line.

Topics

Resources

License

Stars

Watchers

Forks