Skip to main content

API Reference

createEnvSchema

Creates a type-safe environment schema and returns an environment manager instance.

import { createEnvSchema } from 'envitron';

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

// You can also have no schema and only set options
const envWithoutSchema = createEnvSchema({
// you options here
});

Options

  • envFile (string | string[]): Path(s) to .env file(s). Default: .env, if more than one is provided, envs will be merged in file order.
  • rootPath (string): Root directory for env file resolution. Default: process.cwd(), will always try to resolve from the current directly.
  • logs (boolean): Enable logging. Default: true
  • throwErrorOnValidationFail (boolean): Throw on schema validation error. Default: true, the absence of the .env files will not throw error.
  • loadFromProcessEnv (boolean): Merge envs from process.env other than from the env files. Default: false. Envs from process.enc will have the prority over the env files
// Example with loadFromProcessEnv
const env = createEnvSchema(
(schema) => ({
PORT: schema.number(),
NODE_ENV: schema.enum(['development', 'production', 'test'] as const),
DEBUG: schema.boolean({ optional: true }),
}),
{
loadFromProcessEnv: true,
}
);

// .env file content:
// PORT=4000
// NODE_ENV=development
// DEBUG=true

// When running with: PORT=3000 node index.js
console.log(env.PORT); // 3000 (from process.env)
console.log(env.NODE_ENV); // 'development' (from .env file)
console.log(env.DEBUG); // true (from .env file)

Accessing Environment Variables

Direct Property Access

You can access environment variables directly as properties of the environment manager instance:

const port = env.PORT; // number
const nodeEnv = env.NODE_ENV; // 'development' | 'production' | 'test'

Using the Getter Method

For cases where you want to provide default values, use the get() method:

const port = env.get('PORT', 3000); // number
const nodeEnv = env.get('NODE_ENV', 'development'); // 'development' | 'production' | 'test'

env.set(key, value)

Sets the value of an environment variable at runtime (does not persist to file). Default values are not enforced and any can be passed.

env.set('PORT', 8080);

env.all()

Returns an object with all parsed environment variables.

const allEnvs = env.all();

Schema Methods

schema.object(nestedSchema, options?)

Define nested object schemas with full type inference.

Parameters:

  • nestedSchema: Object containing nested validators
  • options: Optional configuration object
    • optional: boolean - Makes the nested object optional

Returns: EnvValidationCallback with nested object type

Example:

const env = createEnvSchema((schema) => ({
database: schema.object({
host: schema.string(),
port: schema.number(),
credentials: schema.object({
username: schema.string(),
password: schema.string(),
}),
}),
}));

// Full type safety
const db = env.get('database');
console.log(db.host); // string
console.log(db.port); // number
console.log(db.credentials.username); // string

Optional nested object:

config: schema.object(
{
host: schema.string(),
port: schema.number(),
},
{ optional: true }
)

schema.array(elementValidator?, options?)

Define arrays with or without element type validation.

Overloads:

  1. Untyped Arrays:

    schema.array()                        // string[] from CSV or JSON
    schema.array({ optional: true }) // string[] | undefined
  2. Typed Arrays:

    schema.array(schema.number())         // number[]
    schema.array(schema.string()) // string[]
    schema.array(schema.boolean()) // boolean[]
  3. Optional Typed Arrays:

    schema.array(schema.number(), { optional: true })  // number[] | undefined

Parameters:

  • elementValidator: (Optional) Validator for array elements
  • options: Optional configuration object
    • optional: boolean - Makes the array optional

Returns: EnvValidationCallback with array type

Examples:

const env = createEnvSchema((schema) => ({
// Untyped arrays (from CSV or JSON)
tags: schema.array(),

// Typed arrays
ports: schema.array(schema.number()), // number[]
hosts: schema.array(schema.string()), // string[]
flags: schema.array(schema.boolean()), // boolean[]

// Arrays of objects
users: schema.array(
schema.object({
name: schema.string(),
age: schema.number(),
})
), // Array<{ name: string; age: number }>

// Optional arrays
optionalPorts: schema.array(schema.number(), { optional: true }),
}));

// Type-safe access
const ports = env.get('ports'); // number[]
const users = env.get('users'); // Array<{ name: string; age: number }>
console.log(users[0].name); // string
console.log(users[0].age); // number

Other Schema Methods

For documentation on other schema methods, see:

Error Handling

  • Throws on missing required or invalid type by default (configurable).
  • Logs errors if logs: true.
  • Use optional: true in schema to allow missing values.

See Also