Configuration

Typed Config

Validate and type environment variables at startup with AxilJS defineConfig — string, number, boolean and json fields with defaults, enums and ranges.

1 min readUpdated DocumentationEdit this page
On this page2

Usage

TypeScript
TS
1import { loadEnv, defineConfig } from '@axiljs/config'
2
3loadEnv()
4
5const config = defineConfig({
6  PORT:         { type: 'number',  default: 3000 },
7  DATABASE_URL: { type: 'string',  required: true, description: 'Postgres connection string' },
8  DEBUG:        { type: 'boolean', default: false },
9  NODE_ENV:     { type: 'string',  enum: ['development', 'production', 'test'] },
10  RATE_LIMIT:   { type: 'number',  default: 100, min: 1, max: 1000 },
11  FEATURES:     { type: 'json',    default: {} }
12})

Field options

OptionDescription
type'string', 'number', 'boolean' or 'json' (parsed with JSON.parse)
requiredFail when the variable is missing or empty and there is no default
defaultValue used when the variable is missing or empty
descriptionAppended to the missing-variable error message
enumAllowed values
min / maxNumeric range (number fields only)

Booleans accept true/false, 1/0, yes/no and on/off (case-insensitive).

All problems are collected and thrown together as a single ValidationError, so the app fails at startup with one clear list.

defineConfig(schema, source) takes an optional second argument (default process.env), which is handy in tests.

Tip

Always call loadEnv() before defineConfig().

Was this page helpful?

Help improve the documentation

AxilJS is open source and documentation improvements are welcome.

AxilJS DocumentationMIT License · Built by SyntaxilitY