Skip to main content

Getting Started

Environment Manager is a type-safe, schema-driven environment variable management library for Node.js. It helps you define, validate, and access environment variables with confidence, using a simple schema API.

Features

  • Dependency free and small size library for env management.
  • Type-safe environment variable access
  • Schema-based validation (string, number, boolean, enum, array)
  • Optional and default values
  • Automatic parsing from .env files
  • Direct property access for environment variables

Installation

yarn add envitron
# or
npm install --save envitron

Basic Usage

import { createEnvSchema } from 'envitron';

const env = createEnvSchema((schema) => ({
PORT: schema.number(),
NODE_ENV: schema.enum(['development', 'production', 'test'] as const),
DEBUG: schema.boolean({ optional: true }),
ALLOWED_HOSTS: schema.array({ optional: true }),
}));

// Access variables using getter method, it gives the possibility to specify a default value if none provided
const port = env.get('PORT');
const nodeEnv = env.get('NODE_ENV', 'development');
const debug = env.get('DEBUG', false);
const allowedHosts = env.get('ALLOWED_HOSTS', ['localhost']);

// Or access variables directly as properties
console.log(env.PORT); // number
console.log(env.NODE_ENV); // 'development' | 'production' | 'test'
console.log(env.DEBUG); // boolean | undefined
console.log(env.ALLOWED_HOSTS); // string[] | undefined

JSON Environment Files

Envitron also supports JSON environment files with native types and nested structures:

// .env.json
{
"PORT": 3000,
"NODE_ENV": "production",
"DEBUG": false,
"database": {
"host": "localhost",
"port": 5432
},
"ALLOWED_HOSTS": ["localhost", "127.0.0.1"]
}
const env = createEnvSchema(
(schema) => ({
PORT: schema.number(),
NODE_ENV: schema.enum(['development', 'production', 'test'] as const),
DEBUG: schema.boolean(),
database: schema.object({
host: schema.string(),
port: schema.number(),
}),
ALLOWED_HOSTS: schema.array(schema.string()),
}),
{ envFile: '.env.json' }
);

// Full type inference for nested objects
const dbHost = env.get('database').host; // string
const dbPort = env.get('database').port; // number
const hosts = env.get('ALLOWED_HOSTS'); // string[]

Benefits of JSON files:

  • Native types: Numbers, booleans, and arrays without string conversion
  • Nested structures: Complex configurations with multiple levels
  • Type safety: Full TypeScript type inference at all nesting levels

See JSON Environment Files for more details.

Next Steps