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

dotenv-constraint

v1.1.0

Published

A lightweight package to enforce constraints on environment variables in JavaScript, ensuring required variables are defined and match expected types.

Readme

dotenv-constraint

🚀 dotenv-constraint is a lightweight package for validating and enforcing constraints on environment variables in JavaScript. It ensures that required variables are defined and match expected types.

📦 Installation

Install the package via npm:

npm install dotenv-constraint

🛠️ Setup

1️⃣ Create a Schema File

Before using dotenv-constraint, you must create a .env.schema file to define expected environment variables and their types.

Example .env.schema File:

DB_USERNAME=                  # Required
SERVICE=                      # Required
DB_PORT= #number              # Required and must be a number
NB_LICENSE= #optional#number  # Optional and must be a number if provided

📌 Schema Rules:

  • Required variable: Any variable without #optional is mandatory.
  • Optional variable: Add #optional to indicate that a variable is not required.
  • Type constraints: Use #number to enforce numeric values.
  • Optional + Type combination: Use #optional#number for variables that can be omitted but must be numeric if defined.

2️⃣ Create an .env File

Add your environment variables in a .env file:

DB_USERNAME=admin
SERVICE=some_api_key
DB_PORT=5432
NB_LICENSE=50

3️⃣ Validate Environment Variables

Add the following script to your code to validate environment variables:

ESM (ECMAScript Modules)

import { validateEnv } from 'dotenv-constraint'

CommonJS (Traditional Node.js Modules)

const { validateEnv } = require('dotenv-constraint')

Then, call the function:

const { success, errors } = validateEnv({
  dotenvPath: '.env',
  schemaPath: '.env.schema',
})

if (!success) {
  console.error('❌ Environment validation failed:', errors)
}

⚙️ API

validateEnv(config?: { dotenvPath?: string; schemaPath?: string })

  • dotenvPath (optional, default: .env): Path to the .env file containing the environment variables.
  • schemaPath (optional, default: .env.schema): Path to the schema file defining expected variables.

Return Value

If validation fails, the function returns an error object:

{
  success: false,
  errors: [
    {
      variable: "DB_USERNAME"
      code: "empty",
    },
    {
      variable: "DB_PORT",
      code: "invalid_type",
      expected: "number"
    }
  ]
}

Error Codes

dotenv-constraint detects the following types of issues:

| Error Code | Description | Example | |------------|-------------|---------| | missing | A required variable is not defined in .env | Variable exists in schema but not in .env | | empty | A required variable is defined but has no value | DB_USERNAME= (empty value) | | invalid_type | A variable doesn't match the expected type constraint | See details below | | duplicate | A variable is declared multiple times in .env | PORT=3000 and PORT=4000 in the same file | | not_in_schema | A variable exists in .env but is not declared in .env.schema | Variable in .env that doesn't exist in schema | | file_not_found | The .env or .env.schema file cannot be found | Missing configuration files |

invalid_type Error Details

The invalid_type error occurs when a variable's value doesn't match its type constraint defined in the schema. The error includes an expected field indicating the required type.

Currently supported type constraints:

  • #number: The variable must be a valid number

Examples of invalid_type errors:

// ❌ Invalid - not a number
DB_PORT=abc
// Schema: DB_PORT= #number
// Error: { code: "invalid_type", variable: "DB_PORT", expected: "number" }

// ❌ Invalid - text mixed with numbers
MAX_CONNECTIONS=100users
// Schema: MAX_CONNECTIONS= #number
// Error: { code: "invalid_type", variable: "MAX_CONNECTIONS", expected: "number" }

// ✅ Valid
DB_PORT=5432
MAX_CONNECTIONS=100

Note: More type constraints may be added in future versions (e.g., #boolean, #email, #url).

Error Handling

If errors are detected, you can stop your application:

if (!success) {
  console.error(errors)
}

🤝 Contributing

Contributions are welcome! Feel free to submit issues or pull requests. 🛠️

📜 License

MIT