Skip to main content

How Environment Variables Are Parsed

Environment variables are parsed with type safety and support for edge cases:

  • Booleans: "true", "false", true, false
  • Numbers: "123", "3.14"
  • Enums: Restrict to a set of allowed values
  • Strings: Handles quotes, spaces, special characters, escaping
  • Arrays: CSV, quoted, single/double quotes

Parsing Rules

  • Double quotes ("): Supports escape sequences (e.g., \n, \t, \"). # is treated as a literal character.
  • Single quotes ('): Takes the literal value, no escape sequences. # is treated as a literal character.
  • Unquoted: Value is trimmed. # starts a comment. No escape sequences.
  • Empty values: If a variable exists but has no value (e.g., EMPTY=), it returns undefined.

Example

BOOLEAN=true
NUMBER=123
CSV="foo,bar,baz"
QUOTED_STRING="hello world"
ENUM_ENV=production
DOUBLE_QUOTED_ESCAPES="line1\nline2"
SINGLE_QUOTED_LITERAL='line1\nline2'
UNQUOTED_SPACES= some value # comment
EMPTY=
ONLY_SPACES=
HASH_VALUE="value#notacomment"
UNQUOTED_HASH=foo # this is a comment
const env = createEnvSchema(schema => ({
BOOLEAN: schema.boolean(),
NUMBER: schema.number(),
CSV: schema.array(),
QUOTED_STRING: schema.string(),
ENUM_ENV: schema.enum(['development', 'production', 'test'] as const),
DOUBLE_QUOTED_ESCAPES: schema.string(),
SINGLE_QUOTED_LITERAL: schema.string(),
UNQUOTED_SPACES: schema.string(),
EMPTY: schema.string(),
ONLY_SPACES: schema.string(),
HASH_VALUE: schema.string(),
UNQUOTED_HASH: schema.string(),
}));

console.log(env.get('BOOLEAN')); // true
console.log(env.get('NUMBER')); // 123
console.log(env.get('CSV')); // ['foo', 'bar', 'baz']
console.log(env.get('QUOTED_STRING')); // 'hello world'
console.log(env.get('ENUM_ENV')); // 'production'
console.log(env.get('DOUBLE_QUOTED_ESCAPES')); // 'line1\nline2' (with actual newline)
console.log(env.get('SINGLE_QUOTED_LITERAL')); // 'line1\nline2' (literal backslash-n)
console.log(env.get('UNQUOTED_SPACES')); // 'some value'
console.log(env.get('EMPTY')); // undefined
console.log(env.get('ONLY_SPACES')); // undefined
console.log(env.get('HASH_VALUE')); // 'value#notacomment'
console.log(env.get('UNQUOTED_HASH')); // 'foo'

Notes

  • Enums: If the value is not in the allowed set, an error is thrown at load time.
  • Quoting: Use double quotes for escape sequences, single quotes for literal values, and unquoted for trimmed values with comment support.
  • Empty values: Any variable present in the .env file but with no value will return undefined.