Skip to content
Env Reader
Language:en Author:AtomForge

Getting Started

Installation

npm install @atom-forge/env-reader

Import the EnvReader class and, when needed, the asReadonly function from the public entry point.

import { EnvReader, asReadonly } from "@atom-forge/env-reader";

const env = new EnvReader(process.cwd());

export const config = asReadonly({
    mode: env.oneOf("APP_ENV", ["dev", "prod", "test"], "prod"),
    databaseUrl: env.string("DATABASE_URL"),
    port: env.int("PORT", 3000),
});

process.cwd() is an absolute path, but it means the working directory of the process. Use it as the project root only if you really start the application from there; otherwise pass an explicit absolute project path.

How startup works

flowchart TD
    A[Application starts] --> B[Environment variables are available]
    B --> C[Build the configuration with EnvReader]
    C --> D{Read succeeded?}
    D -->|Yes| E[Typed configuration]
    E --> F[Start services]
    D -->|No| G[Abort startup with an error]

Required value or default?

If a variable is undefined and no default is given, the method throws. A default normally replaces only a missing variable: it does not repair a value that is present but invalid.

const required = env.string("DATABASE_URL");
const optional = env.boolean("DEBUG", false);

Next chapter: Values and Lists.

Teaches (2)

  • installation
  • startup configuration