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.
Link to section: numbersNumbers
Any field defined as a number or a numeric subtype (like number.integer or number.port) will be automatically parsed.
import arkenv from "arkenv";
const env = arkenv({
PORT: "number.port",
RETRY_COUNT: "number.integer = 3",
AGE: "0 <= number.integer <= 120"
});
// All are numbers!
console.log({
port: env.PORT,
retryCount: env.RETRY_COUNT,
age: env.AGE
}); Link to section: booleansBooleans
The boolean type handles strings like "true" and "false".
import arkenv from "arkenv";
const env = arkenv({
DEBUG: "boolean = false"
});
// DEBUG is true if process.env.DEBUG is "true"
console.log({
debug: env.DEBUG
});Link to section: how-it-worksHow 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.
Link to section: performancePerformance
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.
Link to section: disabling-coercionDisabling coercion
You can opt-out of this behavior by setting coerce to false.
import arkenv from "arkenv";
// ⚠️ This will throw an error!
// "3000" (string) is not a number.
const env = arkenv(
{
PORT: "number.port",
},
{
coerce: false, // < -- Disable coercion
env: {
PORT: "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.