Skip to content

Validate and type-check environment variables at startup. Zero dependencies. TypeScript-friendly.

License

Notifications You must be signed in to change notification settings

mariusfit/env-type-check

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

env-type-check

Validate and type-check environment variables at application startup. Zero dependencies. TypeScript-friendly.

npm version License: MIT Node.js >=14

Why

Apps crash in production because process.env.DATABASE_URL was undefined and someone didn't notice. env-type-check validates all your environment variables at startup, collects all errors at once, and gives you typed values — no more parseInt(process.env.PORT || '3000') scattered everywhere.

Install

npm install env-type-check

Quick Start

const { envCheckOrExit } = require('env-type-check');

const env = envCheckOrExit({
  PORT:         { type: 'port', default: 3000 },
  DATABASE_URL: { type: 'url', description: 'PostgreSQL connection string' },
  API_KEY:      { type: 'string', minLength: 32, description: 'Secret API key' },
  DEBUG:        { type: 'boolean', default: false },
  NODE_ENV:     { type: 'string', choices: ['development', 'staging', 'production'] },
  MAX_WORKERS:  { type: 'integer', min: 1, max: 32, default: 4 },
  ADMIN_EMAIL:  { type: 'email', required: false },
});

// env.PORT        → number
// env.DATABASE_URL → string (valid URL)
// env.DEBUG       → boolean
// env.MAX_WORKERS → number (integer, 1-32)
app.listen(env.PORT);

If any validation fails, the process exits with a clear error listing all issues:

Environment validation failed:
  ✗ Missing required env var: DATABASE_URL (PostgreSQL connection string)
  ✗ API_KEY must be at least 32 chars (got 8)
  ✗ NODE_ENV must be one of [development, staging, production] (got "prod")

Types

Type Input Output Notes
string any string Default type
number "3.14" 3.14 Float
integer "42" 42 Rejects floats
port "3000" 3000 Valid: 1-65535
boolean "true"/"1"/"yes"/"on" true/false Case-insensitive
url "https://..." string Must be http/https
email "user@example.com" string Basic email validation
json '{"key":"val"}' object Parsed JSON
array "a,b,c" or '["a","b"]' string[] CSV or JSON

Full Schema Options

envCheck({
  MY_VAR: {
    type: 'string',          // Type (default: 'string')
    required: true,          // Throw if missing (default: true)
    default: 'fallback',     // Value when missing (makes required irrelevant)
    min: 0,                  // Min value (number/integer)
    max: 100,                // Max value (number/integer)
    minLength: 8,            // Min string length
    maxLength: 255,          // Max string length
    pattern: '^[a-z]+$',    // Regex the raw string must match
    choices: ['a', 'b'],     // Allowed values (after coercion)
    description: 'My var',   // Shown in error messages
    example: 'hello',        // Shown in errors + .env.example generator
  }
});

TypeScript

Full type inference — no type casting needed:

import { envCheck } from 'env-type-check';

const env = envCheck({
  PORT:    { type: 'port' as const, default: 3000 },
  DEBUG:   'boolean' as const,
  API_URL: 'url' as const,
});

env.PORT;    // number
env.DEBUG;   // boolean
env.API_URL; // string

Generate .env.example

const { generateEnvExample } = require('env-type-check');

const example = generateEnvExample({
  PORT:     { type: 'port', description: 'Server port', example: 3000 },
  DATABASE_URL: { type: 'url', description: 'PostgreSQL URL', example: 'postgres://user:pass@localhost/db' },
  NODE_ENV: { type: 'string', choices: ['development', 'production'], default: 'development' },
});

require('fs').writeFileSync('.env.example', example);

Output:

# Environment variables — generated by env-type-check

# Server port
# type: port
PORT=3000

# PostgreSQL URL
# type: url
DATABASE_URL=postgres://user:pass@localhost/db

# type: string | choices: development|production
NODE_ENV=development

Test with custom source

// Don't use process.env — useful for testing
const env = envCheck(schema, {
  PORT: '3000',
  NODE_ENV: 'test',
});

API

envCheck(schema, source?)

Validates and returns typed env values. Throws Error with all validation failures listed.

envCheckOrExit(schema, source?)

Same as envCheck but calls process.exit(1) instead of throwing. Use at app startup.

generateEnvExample(schema)

Returns a .env.example file content string.

License

MIT — free for personal and commercial use.

About

Validate and type-check environment variables at startup. Zero dependencies. TypeScript-friendly.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published