Skip to content
Rohan-ShridharPublic

About

A zero-boilerplate env validator

Topics

Resources

Code of conduct

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Latest commit

Β 

History

67 Commits

Folders and files

Repository files navigation

envguard

npm version

A zero-boilerplate environment variable validator and analysis tool for Node.js.

πŸ›‘οΈ Validate: Coerce types and enforce schemas at startup.
πŸ” Analyze: Detect unused or missing variables in your codebase.
πŸ“Š Dashboard: Visualize your environment health in a local dev UI.


Install

npm install @rohansm14/envguard

⚑ Quick Start

1. Validate & Coerce

Call it at app startup to ensure your environment is safe.

import 'dotenv/config'
import { guard } from '@rohansm14/envguard'

const env = guard({
  PORT:         { type: 'number',  default: 3000 },
  DATABASE_URL: { type: 'string',  required: true },
  JWT_SECRET:   { type: 'string',  required: true, minLength: 32 }
})

app.listen(env.PORT)

Strict Access and Presence Checks

Pass a second options object to guard(). With strict: true, accessing a variable that is not declared in the schema throws an error. Use env.has() to check whether a schema variable has a value before reading it.

const env = guard(
  {
    PORT: { type: 'number', default: 3000 },
    FEATURE_FLAG: { type: 'string' }
  },
  { strict: true }
)

if (env.has('FEATURE_FLAG')) {
  startFeature(env.FEATURE_FLAG)
}

2. Infer Types (Zero-schema)

Don't want to maintain a schema? inferEnv() automatically detects types from environment variable values.

import { inferEnv } from '@rohansm14/envguard'

const env = inferEnv()

// "3000" β†’ 3000 (number)
// "true" β†’ true (boolean)

3. Strict Inference and Per-key Overrides

You can pass a configuration object to inferEnv() to enable strict inference and define validation rules for individual environment variables.

Set strict: true to reject ambiguous boolean values and malformed numeric strings for configured keys.

import { inferEnv } from '@rohansm14/envguard'

const env = inferEnv({
  strict: true,
  PORT: { required: true },
  DEBUG: {},
  API_KEY: { minLength: 6 }
})

In this example:

  • strict: true enables strict inference checks.
  • required: true ensures that PORT is set.
  • minLength: 6 requires API_KEY to contain at least six characters.
  • Values are automatically inferred as strings, numbers, or booleans.

For example, strict inference rejects values such as "TRUE" when an exact lowercase boolean is expected, or "12abc" when a value looks numeric but contains invalid characters.

4. Pass a Custom Environment Object

By default, inferEnv() reads values from process.env. You can pass a custom environment object as the second argument.

import { inferEnv } from '@rohansm14/envguard'

const customEnv = {
  PORT: '3000',
  DEBUG: 'true',
  API_KEY: 'abc123'
}

const env = inferEnv(
  {
    strict: true,
    PORT: { required: true },
    DEBUG: {},
    API_KEY: { minLength: 6 }
  },
  customEnv
)

console.log(env)

// {
//   PORT: 3000,
//   DEBUG: true,
//   API_KEY: 'abc123'
// }

Function signature:

inferEnv(config = {}, env = process.env)
  • config: Optional configuration object containing strict and per-key validation rules.
  • env: Optional environment object. Defaults to process.env.

πŸ” Codebase Analysis (CLI)

envguard scans your entire project to find discrepancies between your .env file and your code usage.

npx envguard

It identifies:

  • Unused: Variables defined in .env but never used in code.
  • Missing: process.env.VAR calls in code that aren't defined in .env.
  • Invalid: Variables set to null, undefined, or empty strings.

πŸ“Š Dev Dashboard (UI)

Launch a local dashboard to visualize your environment health in real-time.

npx envguard dev-ui

Starts a server at http://localhost:3000 with:

  • Real-time Polling: Updates automatically as you edit files.
  • Type Mismatches: Flagged conflicts between your values and an optional env.schema.js.
  • Status Badges: Clear βœ“, ⚠, and βœ— indicators for every variable.

⚠️ Important: How to View the Dashboard

The dashboard is a web application that requires the envguard local server to be running.

  • Do NOT open index.html directly from your browser.
  • If you open the file directly, it will show empty stats because it cannot connect to the backend scanner.
  • Always use: npx envguard dev-ui and navigate to http://localhost:3000.

Requirements

  • Project Root: Run the command from your project's root directory.
  • .env file: Must have a .env file present for comparison.
  • Code Usage: Must have at least one process.env.VAR usage in your code for the scanner to detect.

What it does

  • Deep Scanning: Detects dot notation (process.env.VAR), bracket notation (process.env['VAR']), and destructuring (const { VAR } = process.env).
  • Robust Parsing: Correctly handles comments, quotes, and optional chaining (process.env?.VAR).
  • One Combined Error: Logs all validation failures at once so you can fix them in one go.
  • Zero Dependencies: Lightweight and fast, built on native Node.js logic.

Schema Options

The following options are supported by guard() for validating environment variables.

Option Type Description
type 'string', 'number', 'boolean' Expected type. Values are coerced to the specified type.
required boolean Throws if the variable is not set.
default any Fallback value if the variable is not set.
minLength number Minimum character length for string values.

For inferEnv(), use strict as a configuration-level option and required, default, and minLength as per-key rules. Type inference is automatic.


License

MIT

About

A zero-boilerplate env validator

Topics

Resources

Code of conduct

Contributing

Stars

5 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages