Skip to content

Read configuration from environment variables Core

EnvVarBind maps environment variables to config elements. It translates element paths to uppercase environment variable names: section.element becomes SECTION_ELEMENT. With a prefix, section.element becomes PREFIX_SECTION_ELEMENT.

Steps

1. Create the bind and pass it to ConfigBound.createConfig:

typescript
import { 
ConfigBound
,
configItem
,
configSection
} from "@config-bound/config-bound";
import {
EnvVarBind
} from "@config-bound/config-bound";
import {
z
} from "zod";
const
config
= await
ConfigBound
.
createConfig
(
{
port
:
configItem
<number>({
default
: 3000,
validator
:
z
.
number
().
int
().
min
(1).
max
(65535)
}),
database
:
configSection
({
host
:
configItem
<string>({
default
: "localhost",
validator
:
z
.
hostname
()
}) }) }, {
binds
: [new
EnvVarBind
()]
} );

With this config, PORT sets port and DATABASE_HOST sets database.host.

2. To avoid collisions with other applications' environment variables, use a prefix:

typescript
const 
binds
= [new
EnvVarBind
({
prefix
: "MYAPP" })];

With the prefix MYAPP, MYAPP_PORT sets port and MYAPP_DATABASE_HOST sets database.host. The prefix is stripped before lookup - your code still calls config.get("app", "port").

Variable naming

Element pathNo prefixPrefix MYAPP
portPORTMYAPP_PORT
database.hostDATABASE_HOSTMYAPP_DATABASE_HOST
server.api.urlSERVER_API_URLMYAPP_SERVER_API_URL