Coercion
Environment variables are auto-morphed into typesafe numbers, booleans, and more.
Traditionally, environment variables are always strings by default. ArkEnv coerces these strings into their target types based on your schema, so you only have to think about the types you want.
Important
Coercion is only available in ArkType mode (the default). When using validator: "standard", your Standard Schema validators handle their own parsing and type conversion.
Numbers
Any field defined as a number or a numeric subtype (like number.integer or number.port) will be automatically parsed.
// All are numbers! (hover `env` to see)
const = ({
: "number.port",
: "number.integer = 3",
: "0 <= number.integer <= 120"
});Booleans
The boolean type handles strings like "true" and "false".
// DEBUG is true if process.env.DEBUG is "true"
const = ({
: "boolean = false"
});Arrays
ArkEnv can parse strings into arrays. By default, it splits the string by commas and trims each value.
const = ({
: "string[]",
: "number[]"
}, {
: {
: "web, app, api",
: "3000, 8080"
}
});Array format
If your environment variables use JSON format instead of commas, you can change the arrayFormat option:
const = (
{ : "string[]" },
{
: "json",
: { : '["web", "app"]' }
}
);Objects
ArkEnv can parse JSON strings into objects. This is useful for grouping related configuration into a single environment variable.
import from "arkenv";
const = ({
: {
: "string",
: "number"
}
}, {
: {
: '{"HOST": "localhost", "PORT": "5432"}'
}
});Coercion works recursively: even variables inside a JSON object are coerced to their correct types (like PORT becoming a number above).
How it works
ArkEnv introspects your schema to identify fields that should be numbers, booleans, and other non-string types you define. When you call createEnv() (or arkenv()), it pre-processes your environment variables to perform these conversions before validation.
Performance
Coercion is highly optimized: ArkEnv performs a one-time introspection of your schema to map out exactly which paths need conversion. At runtime, it only touches the variables that actually need coercion, keeping your startup time virtually identical to manually parsing process.env.
Disabling coercion
You can opt-out of this behavior by setting coerce to false.
// ⚠️ This will throw an error!
// "3000" (string) is not a number.
const = (
{
: "number.port",
},
{
: false, // < -- Disable coercion
: {
: "3000",
},
}
);When coercion is disabled, environment variables are validated exactly as they are. Since environment variables are strings, this means validation will fail for number or boolean fields unless you morph them yourself.