ArkType
Validate environment variables with @arkenv/core and ArkType.
@arkenv/core is the ArkType engine: DSL strings, keywords such as
number.port and string.host, and built-in string coercion.
For an overview of available engines, see Validators.
Installation
Install @arkenv/core and its peer dependency arktype:
npm install @arkenv/core arktypepnpm add @arkenv/core arktypeyarn add @arkenv/core arktypebun install @arkenv/core arktypeDefine your schema
Declare environment variables in an env.ts file using ArkType string definitions
or compiled type() objects:
import from "@arkenv/core";
export const = ({
: "string",
: "number.port = 3000",
: "boolean = false",
: "'development' | 'production' | 'test' = 'development'",
});Import { env } from "./env" at application startup. If any required variables
are missing or fail validation, ArkEnv throws an
ArkEnvError with formatted issue details.
Automatic coercion
ArkEnv inspects the compiled ArkType schema's JSON Schema to automatically coerce incoming string values into numbers, booleans, and arrays before validation:
import from "@arkenv/core";
export const = (
{
: "number.port",
: "boolean",
: "string[]",
},
{
: {
: "8080",
: "true",
: "web, api",
},
},
);
.; // number
.; // boolean
.; // string[]To disable automatic string conversion and preserve raw strings for custom morphs,
pass { coerce: false }. Learn more in Coercion.
Defaults and optionals
ArkType syntax supports inline default values and optional properties:
| Pattern | Behavior |
|---|---|
= 'value' / = 3000 | Fallback value when the variable is undefined |
string | undefined or string? | Optional environment variable |
emptyAsUndefined: true | Converts empty strings ("") to undefined so defaults trigger |
For specialized validators like string.host and number.port, see
Keywords. To build complex custom schemas or morphs,
see Defining types.