npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

validate-env-vars

v0.4.2

Published

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

Downloads

292

Readme

license latest last commit npm downloads
Coverage Code Quality CodeQL

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 |