Skip to main content

Function Signature

function maybeEnvInt(key: string): number | undefined

Parameters

key
string
required
The name of the environment variable to read

Returns

number | undefined - The parsed integer value, or undefined if the variable is not set or empty.

Behavior

Returns undefined when:
  • The environment variable is not set
  • The environment variable is an empty string
  • The environment variable contains only whitespace
Throws TypeError when:
  • The value cannot be parsed as a number

Example

import { maybeEnvInt } from "@load-env/core"

// Optional port configuration
export const PORT = maybeEnvInt("PORT")

const port = PORT ?? 3000
console.log(`Server listening on port ${port}`)

// Optional worker count
export const WORKER_COUNT = maybeEnvInt("WORKER_COUNT")

const workerCount = WORKER_COUNT ?? require("os").cpus().length
console.log(`Starting ${workerCount} workers`)

// Optional timeout
export const TIMEOUT_MS = maybeEnvInt("TIMEOUT_MS")

if (TIMEOUT_MS) {
  setTimeout(() => {
    console.log("Timeout reached")
  }, TIMEOUT_MS)
}

When to Use

Use maybeEnvInt instead of envInt when:
  • The environment variable is optional
  • You want to handle missing values gracefully with undefined
  • You have a default value or can compute a fallback
Use envInt when:
  • The environment variable is required for your application
  • You want the application to fail fast if the variable is missing

Build docs developers (and LLMs) love