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

dotenvlock

v0.1.5

Published

Type-safe environment variable validation for Node.js applications

Downloads

7

Readme

DotEnvLock

A tiny but powerful Node.js utility to validate, type-check, and manage environment variables. Catch misconfigurations early and prevent runtime errors in production.

Features

  • Prevent crashes due to missing or invalid environment variables
  • Enforce type safety for strings, numbers, and booleans
  • Set defaults for optional variables
  • Fail fast or log warnings — choose how strict you want it to be
  • Works with dotenv or any environment config system
  • Detailed console feedback with color-coded, easy-to-read logs

Installation

npm install dotenvlock

# or

yarn add dotenvlock

Basic Usage

Step 1: Create a configuration file

Create a file named dotenvlock.json in your project root:

{
    "API_KEY": { "type": "string", "required": true },
    "PORT": { "type": "number", "default": 3000 },
    "DEBUG_MODE": { "type": "boolean", "default": false }
}

Step 2: Add the validation script

Add an DotEnvLock script to your package.json:

{
    "scripts": {
        "dotenvlock": "dotenvlock .env"
    }
}

Step 3: Run the validation

npm run dotenvlock

You'll see output like:

✅ All environment variables are valid!

or

❌ Missing required environment variable: API_KEY

Step 4: Use in your code

import { checkEnv } from "dotenvlock"

// Validates environment variables and returns typed values
const env = checkEnv({
    API_KEY: { type: "string", required: true },
    PORT: { type: "number", default: 3000 },
    DEBUG_MODE: { type: "boolean", default: false },
})

// Now use the type-safe variables
console.log(`Server starting on port ${env.PORT}`)

Advanced Configuration

Full Configuration Example

const env = checkEnv({
    // Required string - will throw error if missing
    API_KEY: {
        type: "string",
        required: true,
    },

    // Optional number with default value
    PORT: {
        type: "number",
        default: 3000,
    },

    // Optional boolean with default
    DEBUG_MODE: {
        type: "boolean",
        default: false,
    },

    // Required number
    MAX_CONNECTIONS: {
        type: "number",
        required: true,
    },

    // Optional string with default
    LOG_LEVEL: {
        type: "string",
        default: "info",
    },
})

Runtime Options

DotEnvLock's behavior can be customized at runtime to fit your application's needs:

// Throw errors immediately on validation failure
const env = checkEnv(config, process.env, { throwOnError: true })

The throwOnError Option Explained

By default, DotEnvLock logs validation errors to the console but doesn't throw JavaScript exceptions. This means your application will continue running even with invalid configuration, which can be useful during development but risky in production.

When you set throwOnError: true, DotEnvLock will:

  1. Validate your environment variables as usual
  2. Log validation errors to the console
  3. Throw a JavaScript Error if any validation failures occur

This enables several important patterns:

// Example 1: Fail-fast application startup
try {
    const env = checkEnv(
        {
            DATABASE_URL: { type: "string", required: true },
            API_SECRET: { type: "string", required: true },
        },
        process.env,
        { throwOnError: true }
    )

    // This code only runs if ALL environment variables are valid
    startApplication(env)
} catch (error) {
    console.error("Application startup failed: Invalid configuration")
    process.exit(1) // Exit with error code
}

// Example 2: Different behavior for development vs production
const isDevelopment = process.env.NODE_ENV === "development"

const env = checkEnv(
    {
        DATABASE_URL: { type: "string", required: true },
        API_SECRET: { type: "string", required: true },
    },
    process.env,
    {
        // Only throw errors in production
        throwOnError: !isDevelopment,
    }
)

// Example 3: Custom error handling
try {
    const env = checkEnv(config, process.env, { throwOnError: true })
    startServer(env)
} catch (error) {
    // Send alert to monitoring system
    alertMonitoringSystem("Configuration error detected", error)

    // Log detailed diagnostics
    logger.error("Failed to start due to configuration error", {
        error,
        environmentName: process.env.NODE_ENV,
    })

    // Exit with specific error code for configuration issues
    process.exit(78)
}

This option gives you fine-grained control over how your application responds to environment configuration problems.

Type Conversion

DotEnvLock automatically converts values to the correct type:

  • string: Used as-is
  • number: Converted with Number() and validated
  • boolean: Supports various formats:
    • true, 1, yes, ytrue
    • false, 0, no, nfalse

CLI Usage

When running from the command line:

# Check using default .env file
npx dotenvlock

# Check using a specific .env file
npx dotenvlock .env.production

License

MIT