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 🙏

© 2026 – Pkg Stats / Ryan Hefner

@d3vtool/strict-env

v6.0.0

Published

A utility to automatically load and validate environment variables from `.env` files, ensuring they're properly configured before your system starts.

Downloads

60

Readme

strict-env

strict-env is a simple utility that automatically loads environment variables from pre-defined .env files when imported or required in your project. It ensures strict syntax checks and validation of your environment variables before your system starts, preventing potential issues from missing or misconfigured variables.

Why Choose strict-env?

Unlike other solutions, strict-env provides strict syntax checks and validation of your .env files, ensuring that your environment variables are correctly set up. If any environment variables are missing or have invalid values, strict-env throws clear, explicit errors. This helps you catch potential misconfigurations before your application runs, avoiding runtime issues.

With strict-env, you can be confident that your environment variables are loaded correctly, and your application is running with the proper configuration from the start.


Table of Contents


Installation

You can install strict-env via npm or yarn:

npm install @d3vtool/strict-env

or

yarn add @d3vtool/strict-env

Usage

Auto Loading of Environment Variables

To automatically load environment variables from the predefined .env files, simply import the setup file like so:

ESM (ES6 Modules)

import "@d3vtool/strict-env/js";

CommonJS (CJS)

require("@d3vtool/strict-env/js");

Once @d3vtool/strict-env/js is imported, it will automatically load the environment variables from the following .env.

Custom Setup (Optional)

If you want more control over which .env file to load or other configurations, you can import and use the setup function directly:

ESM (ES6 Modules)

import { setup } from "@d3vtool/strict-env";

CommonJS (CJS)

const { setup } = require("@d3vtool/strict-env");

The setup function accepts an options object, which allows for customization. Here's what you can specify:

  • file: The specific .env file to load. If not provided, strict-env will try the default list of .env files.
  • encoding: The encoding to use when reading the file (defaults to utf8).
  • validators: Custom validation rules for your environment variables (see the Validator section below).

Example usage:


const setupOptions = {
  file: ".env.custom",  // Load a custom env file [ optional ]
  encoding: "utf8",     // Set the encoding [ optional ]
  validators: {         // Add custom validators (see below) [ optional ]
    MY_VAR: Validator.string().minLength(10)
  }
}
setup(setupOptions); // although passing 'setupOptions' is also optional.

The setup function will load the .env file(s) and validate the environment variables as defined in the validators option.

Custom Validators

The validators object allows you to specify rules for environment variables. You can define rules for various data types such as string, number, boolean, and object. You can also create custom validation logic or use regular expressions.

Example Usage:

const { setup, Validator } = require("@d3vtool/strict-env");

// Define validators
const validators = Validator.object({
  MY_ENV_VAR: Validator.string().minLength(10),  // A string with a minimum length of 10
  API_KEY: Validator.string().regex(/^[A-Za-z0-9]{32}$/),  // Regex for a 32-character API key
  IS_PROD: Validator.boolean()  // A boolean value (true/false)
});

setup({
  validators
});

You can also use custom validation functions:

const validators = {
  MY_ENV_VAR: Validator.string().custom(value => {
    return (value !== "expected_value");
  })
};

setup({
  validators
});

How Validation Works

Each validator type supports a variety of methods, such as minLength(), maxLength(), regex(), custom(), and others for different data types:

  • Validator.string(): Use for strings, can chain methods like .minLength() and .regex().
  • Validator.number(): Use for numbers, can chain methods like .minLength(), .maxLength(), and .integer().
  • Validator.boolean(): Use for boolean values (true or false).
  • Validator.object(): Use for nested objects.

Example: Defining Multiple Validators

const { setup, Validator } = require("@d3vtool/strict-env");

const validators = Validator.object({
  USERNAME: Validator.string().minLength(5),  // Username must be at least 5 characters long
  API_KEY: Validator.string().regex(/^[A-Za-z0-9]{32}$/),  // A 32-character API key
  PORT: Validator.number().minLength(1024).maxLength(65535),  // Port must be between 1024 and 65535
  ENABLE_FEATURE: Validator.boolean().strict(),  // Must be a boolean value (true or false)
  EMAIL: Validator.string().custom(value => {
    return (!/^[\w-]+(\.[\w-]+)*@([\w-]+\.)+[a-zA-Z]{2,7}$/.test(value));
  })  // Custom email validation
});

setup({
  validators // optional to pass.
});

Example: Referencing Environment Variables

# 1. Standard Variable Reference
POSTGRES_USER=user
POSTGRES_PASS=pass
DATABASE_URL=postgres://${POSTGRES_USER}:${POSTGRES_PASS}@localhost/db_your_db

# 2. Circular References (This will result in an error)
A=${B}
B=${A}

# 3. Multiple References within a Single Variable
PREFIX=pre_
SUFFIX=_post
COMBO=${PREFIX}middle${SUFFIX}

# 4. Single Variable Reference
FOO=bar
VAR_WITH_FOO=prefix_${FOO}_suffix

# 5. Nested / Late References
OUTER_VAR=outer_${INNER_VAR}
INNER_VAR=inner

# 6. Variables without References
SIMPLE_VAR=value

# 7. Empty Variables (This will result in an error)
EMPTY_VAR=

# 9. Handling Leading and Trailing Whitespace in Variables (Whitespace will be trimmed from both ends)
WITH_WHITESPACE =   value   with spaces  _

# 10. Special Characters in Variables (Note: The '#' character is reserved for comments)
SPECIAL_VAR=!@$%^&*()

TypeScript Environment Variable Auto-Completion

Enable auto-completion for environment variables in your TypeScript projects.

Note:

Please remember to include the 'strict-env.d.ts' file name in your '.ignore' files, such as '.gitignore'.

When using the TypeScript environment version, it will update your package.json by adding a "strict-env" key to monitor modifications to your 'env' file, and it will automatically update the key-value pairs to support auto-completion.

Automatic Environment Variable Loading:

import "@d3vtool/strict-env/ts";

Custom tsconfig.json Path Configuration:

import { tsetup } from "@d3vtool/strict-env/tindex";

// Uses the current working directory by default for 'tsconfig.json'
tsetup();

// Or specify a custom path to your 'tsconfig.json' file
tsetup("src"); // Indicates that 'tsconfig.json' is located in the 'src' directory.

Note: If the file 'strict-env.d.ts' already exists, the process will exit early and skip parsing your environment variables.

Therefore, if you have made changes to your .env file, you need to manually delete 'strict-env.d.ts' to force a re-parse of the environment variables.