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 🙏

© 2025 – Pkg Stats / Ryan Hefner

@hoangsonw/env-guard

v1.2.2

Published

Protect your .env files from missing or insecure configurations by validating environment variables against a schema and enforcing .env.example.

Downloads

13

Readme

🛡️ EnvGuard – Validate & Secure Your Environment Variables

NPM version License: MIT Node.js TypeScript Jest

EnvGuard is an NPM package that validates your environment variables against a defined schema and enforces consistency with your .env.example file. Protect your application from misconfigurations and insecure defaults when working in teams or deploying to production.

Currently available on NPM: https://www.npmjs.com/package/@hoangsonw/env-guard


Table of Contents


Features

  • Schema Validation: Define required environment variables and insecure default values.
  • .env Enforcement: Compare your actual .env file against a provided .env.example file.
  • Configurable Behavior: Choose whether to warn or throw errors, and control key matching.
  • TypeScript Support: Fully written in TypeScript with complete type definitions.
  • Cross-Platform: Works in Node.js and integrates seamlessly into your deployment workflows.

Installation

Prerequisites

  • Node.js v14 or higher
  • npm v6 or higher

Installing via NPM

npm install @hoangsonw/env-guard

Installing via Yarn

yarn add @hoangsonw/env-guard

Usage

EnvGuard validates your environment variables based on a schema. It loads variables from your .env file and compares them against a reference .env.example.

Basic Usage

Create a schema for your environment variables and validate:

import { validateEnv } from "@hoangsonw/env-guard";

const schema = {
  DB_HOST: { required: true, insecureValues: ["localhost", "127.0.0.1"] },
  DB_PASSWORD: { required: true, insecureValues: ["12345", "password"] },
  DB_USER: { required: false },
};

validateEnv({
  schema,
  envFilePath: "./.env", // Defaults to "./.env"
  exampleFilePath: "./.env.example", // Defaults to "./.env.example"
  allowMissingExampleKeys: false, // Warn if keys mismatch
  throwOnError: false, // Only warn; set to true to throw errors
});

Advanced Usage

You can customize EnvGuard’s behavior by changing options:

  • allowMissingExampleKeys: When false, it warns if there are extra keys in your .env or missing keys compared to .env.example.
  • throwOnError: When true, the function will throw errors instead of just logging warnings.

Example:

import { validateEnv } from "@hoangsonw/env-guard";

const schema = {
  API_KEY: { required: true },
  DB_HOST: { required: true, insecureValues: ["localhost"] },
  DB_PASSWORD: { required: true, insecureValues: ["password", "12345"] },
};

try {
  validateEnv({
    schema,
    envFilePath: "./config/.env",
    exampleFilePath: "./config/.env.example",
    allowMissingExampleKeys: false,
    throwOnError: true,
  });
  console.log("Environment variables validation passed!");
} catch (error) {
  console.error("Environment validation failed:", error);
  process.exit(1);
}

Note: The script might also parse environment variables from outside the .env file if they are already set in the environment of your machine or Node.js process. This can lead to some warnings in the console, if they are not defined in the .env.example file. You can safely ignore them.


API Reference

validateEnv(options: EnvGuardOptions): void

Parameters:

  • schema: EnvSchema
    An object defining each environment variable’s requirements.
    Example:

    {
      DB_HOST: { required: true, insecureValues: ["localhost"] },
      API_KEY: { required: true }
    }
  • envFilePath?: string
    Path to your .env file. Defaults to "./.env".

  • exampleFilePath?: string
    Path to your .env.example file. Defaults to "./.env.example".

  • allowMissingExampleKeys?: boolean
    If set to false, EnvGuard will warn about extra keys or missing keys between .env and .env.example.

  • throwOnError?: boolean
    If true, the function will throw an error when validations fail; otherwise, it will only log warnings.

Returns:
Nothing; it performs validation and logs warnings/errors as configured.


Testing

EnvGuard includes a Jest test suite. To run tests:

  1. Install dependencies:

    npm install
  2. Run tests:

    npm test

Test files in the __tests__ directory demonstrate how EnvGuard validates environment variables and compares .env to .env.example.


Demo Scripts

Run the demo scripts in the __tests__ directory to see EnvGuard in action:

  1. Run the demo script (with no basedir option):
    npm run demoNoBasedir
  2. Run the demo script (with basedir option):
     npm run demoWithBasedir

The demo scripts will show how EnvGuard validates environment variables and compares .env to .env.example. Check the console output for validation results.


Building & Publishing

Building

Compile the TypeScript source:

npm run build

Publishing

  1. Login to npm:
    npm login
  2. Publish the package:
    npm publish --access public

Contributing

Contributions are welcome! Follow these steps:

  1. Fork the Repository
  2. Create a Feature Branch:
    git checkout -b feature/my-new-feature
  3. Commit Your Changes
  4. Submit a Pull Request

For major changes, please open an issue first to discuss your ideas.


License

This project is licensed under the MIT License.


Final Remarks

EnvGuard ensures your environment variables are correctly configured and secure, reducing misconfigurations in team settings and production deployments. With schema validation and .env.example enforcement, it helps maintain consistency and security in your projects.

Happy guarding! 🛡️