Skip to content

Option to treat empty envs as undefined #695

@yamcodes

Description

@yamcodes

Currently, ArkEnv preserves empty environment variable values (e.g., MY_ENV= in a .env file) as empty strings (""). While this mirrors how Node.js populates process.env, it prevents ArkType from applying defined default values and often results in unnecessary validation errors for numeric or boolean types.

Current Behavior Example

Given the following schema:

const env = arkenv({
  PORT: "number = 3000",
  DEBUG: "boolean = false"
});

If a user has an "empty" entry in their .env:

PORT=
DEBUG=

ArkEnv processes this as:

  1. PORT is "". Validation fails: "PORT must be a number (was a string)".
  2. DEBUG is "". Validation fails: "DEBUG must be a boolean (was a string)".

The user's intent when leaving a value blank is typically to fallback to the default or treat it as "not set."


Proposed Solution

Modify the coerce logic to optionally or by default transform empty strings ("") into undefined before passing the data to the validator.

Expected Behavior After Change

  • Input: VAL= (manifests as "")
  • Coercion: Transforms "" to undefined.
  • Validation:
    • If VAL: "string = 'default'" → result is 'default'.
    • If VAL: "string?" → result is undefined.
    • If VAL: "string" → validation fails correctly with "VAL is missing".

Implementation Considerations

  • Opt-in vs Default: Decide if this should be the default behavior or controlled via ArkEnvConfig (e.g., emptyAsUndefined: boolean).
  • String Intent: Evaluate if any users genuinely need "" to be treated as a valid value. If so, a configuration flag is preferable.
  • Array Consistency: Ensure this doesn't break the existing successful parsing of empty strings into empty arrays [].

Recommended Test Case

it("should apply defaults to empty environment variables", () => {
    const env = createEnv(
        { PORT: "number = 3000" },
        { env: { PORT: "" } }
    );
    expect(env.PORT).toBe(3000); 
});

Metadata

Metadata

Assignees

No one assigned

    Labels

    arkenvChanges to the `arkenv` npm package.enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions