Structured your environment with ease
de-env is a library that helps you manage your environment variables in a structured way.
Your env file
.env
DB_NAME=myapp
DB_USER=admin
DB_PASSWORD=secret123
DB_SSL=true
Define your env schema or use cli to generate it
config.ts
import { EnvSchema } from "de-env";
export const Env = EnvSchema({
DB_NAME:"string",
DB_USER:"string",
DB_PASSWORD:"string",
DB_SSL:"boolean",
});
de-env will automatically parse your env variables and return the value of the key you want.
Env('DB_SSL') // boolean
Passing invalid type in .env will throw an error, Here in the schema we have defined DB_SSL as a boolean
.env
DB_SSL: any-string
This will throw an error when we pass an invalid type in .env
From config.ts
Expected 'DB_SSL' to be a boolean, but got 'any-string'
You can make a variable optional by adding optional to the schema. By default, all variables are required.
config.ts
export const Env = EnvSchema({
DB_HOST: ["string", "optional"],
DB_PORT: ["number", "optional"],
});
If you don't provide a value for a optional variable, de-env will throw an error.
.env
DB_HOST=localhost
We didn't define DB_USER in the schema, so it will throw an error
From config.ts
Missing required environment variables: [ DB_USER ]
de-env cli will automatically make a schema from your env file
.env
DB_NAME=myapp
DB_USER=admin
DB_PASSWORD=secret123
DB_SSL=true
Running de-env parse will generate a schema from your env file
config.ts
import { EnvSchema } from "de-env";
export const Env = EnvSchema({
DB_NAME: "string",
DB_USER: "string",
DB_PASSWORD: "string",
DB_SSL: "boolean",
});
You can mark a variable as optional by adding #! before the variable name in .env file
DB_USER will be marked as optional in the schema
.env
DB_NAME=myapp
#!
DB_USER=admin
DB_PASSWORD=secret123
DB_SSL=true
Running de-env parse will now generate the schema with DB_USER as optional
.env
import { EnvSchema } from "de-env";
export const Env = EnvSchema({
DB_NAME: "string",
DB_USER: ["string", "optional"],
DB_PASSWORD: "string",
DB_SSL: "boolean",
});
You can also define multiple variables as optional with optional block
Start the block with #!!! and end it with #---
All the variables between #!!! and #--- will be marked as optional in the schema
.env
#!!!
DB_NAME=myapp
DB_USER=admin
#---
DB_SSL=true
DB_POOL_MIN=5
DB_POOL_MAX=20
Running de-env parse will now generate the schema with DB_NAME and DB_USER as optional
.env
import { EnvSchema } from "de-env";
export const Env = EnvSchema({
DB_NAME: ["string", "optional"],
DB_USER: ["string", "optional"],
DB_SSL: "boolean",
DB_POOL_MIN: "number",
DB_POOL_MAX: "number",
});