JSPM

  • ESM via JSPM
  • ES Module Entrypoint
  • Export Map
  • Keywords
  • License
  • Repository URL
  • TypeScript Types
  • README
  • Created
  • Published
  • Downloads 4850
  • Score
    100M100P100Q131379F
  • License MIT

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

Package Exports

  • validate-env-vars

Readme

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 { z } from 'zod';
import validateEnvVars from 'validate-env-vars';

const envSchema = z.object({
    PORT: z.string(),
    NODE_ENV: z.string(),
    API_URL: z.string(),
});

validateEnvVars(envSchema);

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

import { z } from 'zod';
import validateEnvVars from 'validate-env-vars';

const envSchema = z.object({
    PORT: z.string(),
    NODE_ENV: z.string(),
    GITHUB_USERNAME: z.string(),
});

const prefilight() => {
    try {
        validateEnvVars(envSchema, '.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 { z } from 'zod';

// define the schema for the environment variables
const envSchema = z.object({
    PATH_PREFIX: z.string(),
    NODE_ENV: z.enum(['development', 'production', 'test']),
    API_URL: z.string().url(),
});

// 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(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