Skip to content

load() turns a missing env var into the string "undefined" #2

Description

@frog-fm

Expected Behavior

A variable the server needs but cannot find should stop it, or at least be visible. load() returns a
Config whose fields are typed string, so reading one should mean it was set.

Current Behavior

load() builds every field with String(process.env.X), and String(undefined) is the six-character
string "undefined". A missing variable becomes a plausible-looking value instead of an error:

$ GREETING="Hello, world" PORT=3000 npm start   # SERVICE_NAME not set
$ curl localhost:3000/health
{"service":"undefined","status":"ok"}

tsc --noEmit passes, because String() really does return a string. Nothing is wrong as far as
the types are concerned, and the endpoint reports ok while serving the wrong answer.

Possible Solution

Read variables through a helper that throws naming the variable when it is absent, so Config only
describes values that actually exist:

function required(name: string): string {
  const value = process.env[name]
  if (!value) throw new Error(`${name} is not set.`)
  return value
}

Minimal Reproducible Example

See artifacts/. reproduce.sh starts the server without SERVICE_NAME and calls /health;
output.txt is what it printed.

Context

Hit while adding the /health endpoint. I followed the pattern already in config.ts, the typecheck
passed, and the endpoint returned 200, so the change looked finished. The wrong value only showed up
when I read the response body properly. Anyone adding the next variable will hit exactly the same thing,
because the pattern is the thing that is wrong, not the line I wrote.


Logged by @jxom in wevm/frog-demo via #1. Filed by frog.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions