v8.1.1-next.0

Quick Start

Install envapt and read your first typed value on Node, Bun, Deno, Workers, or the browser.

WARNING

envapt is ESM only. Node throws ERR_PACKAGE_PATH_NOT_EXPORTED on require('envapt'). In a CommonJS project, load it with await import('envapt') inside an async function. Compatibility lists the runtime versions.

Install

pnpm add envapt

Read a value

On Node, Bun, and Deno, importing envapt binds process.env and your .env files, so there's nothing to set up. Workers and Vite give you config as an object, so on those and other edge runtimes the tab below binds it with useSource before the first read. A read before that throws NoSourceBound.

envapt loads the .env files from your working directory. This step reads CACHE_TTL from the file below. The startup check further down reads the other three keys.

.env
PORT=8080
DATABASE_URL=postgres://app:secret@localhost:5432/app
CACHE_TTL=10m
ALLOWED_ORIGINS=https://app.example.com,https://admin.example.com
src/config.ts
const cacheTtl = .('CACHE_TTL', ., '1m');
const cacheTtl: number

getAs turns 10m into 600000 milliseconds. The '1m' fallback applies if CACHE_TTL is missing, empty, or isn't a duration. Coming from dotenv? .env files on Node has the envapt/config import that replaces dotenv/config.

Reading values covers the other readers. Converters has the full set of converters, including URLs, durations, and arrays. To check a value against a schema from a library such as zod, valibot, or arktype, see Validating with a schema.

Check required config at startup

A fallback hides a bad value. If the app can't run without a setting, call getRequiredAll for the group. It throws one error that lists every bad key:

  • MissingEnvValue lists the keys that are unset or empty.
  • InvalidEnvValue lists the keys that are set but can't convert.

For a single setting, use getRequired.

src/config.ts
export const  = .(
    {
        : .,
        : .,
        : .()
    },
    'camelCase'
);

config;
const config: {
    allowedOrigins: string[];
    databaseUrl: URL;
    port: number;
}

The result is typed from the object you pass. Converters.Url gives a URL, and Converters.array() gives a string[] split on commas. The 'camelCase' argument turns DATABASE_URL into config.databaseUrl, and without it the keys stay as you wrote them. Required values describes the other casings and the error codes.

Import config from your app's entry point. The module throws when it loads, so a missing or bad value stops the app at startup.

WARNING

If a value can't convert and nothing catches the error, Node prints the error's issues, and an issue can quote a secret such as the password in DATABASE_URL. Required values shows a catch block that logs only the keys.

Prefer class fields? The @Envapt decorator declares the same settings on a class.

On this page