XConfig

The XConfig class provides a typed interface for environment variable access with parsing, fallbacks, and existence checks. It exposes convenience getters for the current NODE_ENV and offers a require method for fail-fast validation of mandatory variables at boot time.

Contents
  1. Usage
  2. Static properties
  3. Static methods

Usage

Reading environment variables

import { X } from "@ozanarslan/corpus";

const dbUrl = X.Config.get("DATABASE_URL");
const apiKey = X.Config.get("API_KEY", { fallback: "dev-key" });

Parsing typed values

const port = X.Config.get("PORT", {
	parser: (raw) => Number.parseInt(raw, 10),
	fallback: 3000,
});

const debug = X.Config.get("DEBUG", {
	parser: (raw) => raw === "true",
	fallback: false,
});

Requiring values at boot

const dbUrl = X.Config.require("DATABASE_URL");
const port = X.Config.require("PORT", Number);

Environment checks

if (X.Config.isProd) {
	// Production-only logic
}

if (X.Config.has("FEATURE_FLAG")) {
	// Conditionally enable a feature
}

Setting values at runtime

X.Config.set("FEATURE_FLAG", true);
X.Config.set("RETRY_COUNT", 3);

Static properties

PropertyTypeDescription
envNodeJS.ProcessEnvThe platform's environment variable object.
nodeEnv"development" | "production" | "test"The current NODE_ENV value, defaulting to "development" when unset.
isProdbooleanTrue when nodeEnv equals "production".
isDevbooleanTrue when nodeEnv equals "development".
isTestbooleanTrue when nodeEnv equals "test".

Static methods

has

has(key): boolean

Checks whether an environment variable is defined and non-empty.

Parameters

if (X.Config.has("REDIS_URL")) {
	// Connect to Redis
}

get

get<T = string>(key, opts?): T | undefined

Reads an environment variable with optional parsing and fallback. The return type narrows based on the options provided:

When both parser and fallback are provided, the parser is applied to the raw value if present; otherwise the fallback is returned as-is without parsing.

Parameters

const url = X.Config.get("DATABASE_URL");

const port = X.Config.get("PORT", {
	parser: (raw) => Number.parseInt(raw, 10),
	fallback: 3000,
});

const maybeNumber = X.Config.get("OPTIONAL_PORT", { parser: Number });

require

require<T = string>(key, parser?): T

Reads an environment variable and throws if it is not defined. Use this for variables that must exist for the application to function correctly.

Parameters

Throws

Throws an Error when the key is not defined in the environment.

const dbUrl = X.Config.require("DATABASE_URL");
const port = X.Config.require("PORT", Number);

set

set(key, value): void

Writes a value to the environment. Numbers and booleans are coerced to their string representations via String(value).

Parameters

X.Config.set("LOG_LEVEL", "debug");
X.Config.set("MAX_CONNECTIONS", 100);
X.Config.set("DEBUG_MODE", true);