@hyperfrontend/server/environment

environment

Declares the environment variables a service reads, as data: named variables in groups, a typed reader for each, and one check that reports every missing or malformed variable without repeating a value.

This entry imports no Node.js built-in and never reads the process environment itself. The environment is always passed in, so a service hands over process.env at boot and a test hands over an object.

import { asPort, asSecret, asText, defineEnvironment, optional, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({
  http: { PORT: optional(asPort({ allowZero: true }), 8080), HOST: optional(asText(), '0.0.0.0') },
  hello: { HELLO_GREETING: required(asText()), HELLO_KEY: required(asSecret()) },
})

const values = environment.load({ HELLO_GREETING: 'Hello', HELLO_KEY: 'a-key-of-sixteen-characters-or-more' })
values.http.PORT // 8080, a number: the fallback of an unset variable
values.hello.HELLO_GREETING // 'Hello'
String(values.hello.HELLO_KEY) // '[secret]'

Usage

The outer keys are group names and the inner keys are the variables' names as the environment spells them. The values come back under the same two keys, each typed by its reader, and frozen. A group is a plain object, so a group that several services share is a constant spread into each declaration.

At boot a service loads the process environment and stops when it is not valid. load throws one error named EnvironmentError whose message lists every problem, so a deployment is fixed in one pass instead of one variable per restart:

import { asPort, asSecret, asText, defineEnvironment, optional, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({
  http: { PORT: optional(asPort({ allowZero: true }), 8080) },
  hello: { HELLO_GREETING: required(asText()), HELLO_KEY: required(asSecret()) },
})

try {
  const values = environment.load(process.env)
  console.log(`${values.hello.HELLO_GREETING} from port ${values.http.PORT}`)
} catch (error) {
  console.error(String(error))
  process.exitCode = 1
}
EnvironmentError: Invalid environment:
  - PORT (http) is malformed; expected an integer between 0 and 65535.
  - HELLO_GREETING (hello) is missing; expected non-empty text.
  - HELLO_KEY (hello) is missing; expected a secret of at least 16 characters.

A service that runs on runService does not load the environment itself. It hands the contract over in its definition; the runner checks the process environment before the start function runs, prints the problems as one block on standard error and ends the process with exit code 78, and the start function receives the typed values.

check returns the same problems as a list and never throws, for a tool that prints or counts them itself:

import { asPort, asText, defineEnvironment, optional, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({
  http: { PORT: optional(asPort(), 8080) },
  hello: { HELLO_GREETING: required(asText()) },
})

environment.check({ PORT: 'eighty' })
// [
//   { name: 'PORT', group: 'http', problem: 'malformed', expected: 'an integer between 1 and 65535' },
//   { name: 'HELLO_GREETING', group: 'hello', problem: 'missing', expected: 'non-empty text' },
// ]

variables is the declaration as data, in declaration order: the name, the group, whether the variable is required, whether it is a secret, and the phrase that describes it. A build step or a documentation table reads it without loading anything.

Configuration

Variables

Declared withWhen the variable is unsetWhen it is set
requiredA problem, reported as missingRead; a value the reader refuses is a problem, malformed
optionalThe fallback, as given and without being readRead; a value the reader refuses is a problem, malformed

A variable is unset when the environment holds nothing under its name, or the empty string. A set value is handed to the reader as it is, untrimmed. A set but malformed value is never replaced by the fallback: a typing mistake in a deployment is reported, not hidden behind a default. Names the declaration does not mention are ignored.

A variable that may be absent with no value at all takes a fallback of nothing: optional<string | undefined>(asText(), undefined).

Readers

ReaderAcceptsReturns
asPortDecimal digits from 1 to 65535, with no sign, padding, fraction or exponent; 0 as well with asPort({ allowZero: true })The port, a number
asUrlAn absolute https URL without credentials; plain http for a loopback host (the name localhost, 127.0.0.1 and [::1]), or any host with asUrl({ allowHttp: true })The normalised URL, a string
asOriginA URL under the same scheme rule that is an origin and nothing more: no path, no query, no fragmentThe origin, with no trailing slash
asDurationA whole count and its unit, as in 250ms, 30s, 5m or 1hMilliseconds, a number
asSecretAt least 16 characters, or the count given as asSecret({ minLength: 32 })The text wrapped so that it cannot print
asTextAny text that is not emptyThe text as it is

Every reader refuses what it cannot read exactly: a port written 080 or 1e3, a duration without a unit, an origin with a path. The two URL readers return strings because a URL object can still be changed after it is frozen.

A reader of your own

A reader is an object of three members, so a service writes its own as a literal:

import type { Reader } from '@hyperfrontend/server/environment'
import { defineEnvironment, required } from '@hyperfrontend/server/environment'

const asLogLevel: Reader<'debug' | 'info' | 'error'> = {
  expected: 'one of debug, info or error',
  secret: false,
  read: (raw) => (raw === 'debug' || raw === 'info' || raw === 'error' ? raw : undefined),
}

const environment = defineEnvironment({ logging: { LOG_LEVEL: required(asLogLevel) } })
environment.load({ LOG_LEVEL: 'info' }).logging.LOG_LEVEL // 'info'

The function returns the value, or nothing for a text it refuses. It is synchronous: a returned promise counts as a refusal, and so does a throw, whose message is dropped because it may quote the text. The phrase completes the sentence "expected ..." in a problem line and is printed as written, so it describes the format and never holds a value.

Secrets

What asSecret returns prints as [secret] through string conversion, a template, JSON and Node.js inspection, and gives the text back only through reveal(). A log line, an error message or a JSON response that picks one up by accident shows the mask.

A secret is always required. A declaration that gives one a fallback is refused, because a default secret would be a secret written in source.

The wrapper guards against printing by accident and nothing more. The text stays in the memory of the process and in the environment it was read from, and any code that holds the wrapper can reveal it.

Problems

No problem, error message or description holds a value: not the text a variable was set to, not a fallback, and not what a reader threw. Each names the variable, its group and the reader's phrase, so all of them are safe to log.

defineEnvironment checks the declaration itself and throws once, with a line per fault: a group that is not a plain object or is named __proto__, a variable name that is not upper-case letters, digits and underscores starting with a letter, a value that was not built by required or optional, a name declared in two groups, and a secret with a fallback.

API Reference§

ƒ Functions

§function

asDuration(): Reader<number>

Reads 250ms, 30s, 5m or 1h as milliseconds.
The count is a whole number without padding, and the unit is required, so a bare 30 is refused instead of being guessed at.
Returns
Reader<number>
A frozen reader that yields a whole number of milliseconds.
Example

Reading a refresh interval

import { asDuration } from '@hyperfrontend/server/environment'

asDuration().read('5m') // => 300000
asDuration().read('30') // => undefined
§function

asOrigin(options?: SchemeOptions): Reader<string>

Reads a URL that is exactly an origin (scheme, host, optional port), returned as the serialised origin. The same scheme rule as asUrl.
A path, a query or a fragment is refused, an empty one included. What comes back is the form a browser sends in its Origin header: no trailing slash, and no port when the port is the scheme's default.
Parameters
NameTypeDescription
§options?
SchemeOptionsWhether plain http is accepted for every host; it is not when omitted.
Returns
Reader<string>
A frozen reader that yields the serialised origin.
Example

Reading the origin of the site that calls a service

import { asOrigin } from '@hyperfrontend/server/environment'

asOrigin().read('https://site.example:443/') // => 'https://site.example'
asOrigin().read('https://site.example/app') // => undefined
§function

asPort(options?: PortOptions): Reader<number>

Reads a TCP port written in decimal digits: 1 to 65535, and 0 only with allowZero.
A sign, a decimal point, an exponent, a hexadecimal form, padding zeros and surrounding whitespace are all refused, so 080 and 1e3 are not ports.
Parameters
NameTypeDescription
§options?
PortOptionsWhether port 0 is accepted; it is not when omitted.
Returns
Reader<number>
A frozen reader that yields the port as a number.
Example

Declaring a port the operating system may choose

import { asPort, defineEnvironment, optional } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({ http: { PORT: optional(asPort({ allowZero: true }), 8080) } })
environment.load({ PORT: '0' }).http.PORT // => 0
environment.load({}).http.PORT // => 8080
§function

asSecret(options?: SecretOptions): Reader<Secret>

Reads a secret of at least minLength characters, 16 when omitted, wrapped so that it cannot be printed by accident.
The reader is marked as a secret, so a declaration that gives it a fallback is refused: a default secret must never be written in source.
Parameters
NameTypeDescription
§options?
SecretOptionsThe fewest characters a secret may have.
Returns
Reader<Secret>
A frozen reader that yields the wrapped secret.
Example

Reading a service key

import { asSecret, defineEnvironment, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({ service: { SERVICE_KEY: required(asSecret({ minLength: 32 })) } })
const { SERVICE_KEY } = environment.load({ SERVICE_KEY: 'a-key-of-thirty-two-characters-ok' }).service
String(SERVICE_KEY) // => '[secret]'
SERVICE_KEY.reveal() // => 'a-key-of-thirty-two-characters-ok'
§function

asText(): Reader<string>

Reads any non-empty text, as it is: nothing is trimmed.
Returns
Reader<string>
A frozen reader that yields the text.
Example

Reading a host name

import { asText } from '@hyperfrontend/server/environment'

asText().read('0.0.0.0') // => '0.0.0.0'
asText().read('') // => undefined
§function

asUrl(options?: SchemeOptions): Reader<string>

Reads an absolute https URL without credentials, returned as its normalised string. Plain http is accepted for a loopback host, and anywhere with allowHttp.
The value is a string because a URL object stays mutable even when frozen.
Parameters
NameTypeDescription
§options?
SchemeOptionsWhether plain http is accepted for every host; it is not when omitted.
Returns
Reader<string>
A frozen reader that yields the URL's normalised text.
Example

Reading an identity provider's address

import { asUrl } from '@hyperfrontend/server/environment'

asUrl().read('https://issuer.example/realms/main') // => 'https://issuer.example/realms/main'
asUrl().read('http://issuer.example/') // => undefined
asUrl().read('http://localhost:8080/') // => 'http://localhost:8080/'
§function

defineEnvironment<Shape>(shape: Shape): EnvironmentContract<Shape>

Declares the environment a service reads, as groups of named variables. Throws once, naming every malformed or repeated variable name and every secret declared optional.
The contract reads no environment of its own: check and load take one, so a service passes process.env and a test passes an object. check returns every issue and never throws; load returns the frozen values or throws one error named EnvironmentError with a line per issue. Neither an issue nor the error ever holds a value, so both are safe to log.
Parameters
NameTypeDescription
§shape
ShapeThe groups, each a plain object of variables keyed by environment variable name.
Returns
EnvironmentContract<Shape>
The frozen contract: the declared variables as data, and the two ways to read an environment.
Examples

Loading a service's environment at boot

import { asPort, asSecret, asText, defineEnvironment, optional, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({
  http: { PORT: optional(asPort({ allowZero: true }), 8080), HOST: optional(asText(), '0.0.0.0') },
  hello: { HELLO_GREETING: required(asText()), HELLO_KEY: required(asSecret()) },
})

const values = environment.load(process.env)
values.http.PORT // a number
values.hello.HELLO_KEY.reveal() // the key, which prints as '[secret]' everywhere else

Reporting every problem without a value in it

import { asPort, asText, defineEnvironment, optional, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({
  http: { PORT: optional(asPort(), 8080) },
  hello: { HELLO_GREETING: required(asText()) },
})

environment.load({ PORT: 'eighty' })
// throws EnvironmentError:
// Invalid environment:
//   - PORT (http) is malformed; expected an integer between 1 and 65535.
//   - HELLO_GREETING (hello) is missing; expected non-empty text.
§function

optional<Value>(reader: Reader<Value>, fallback: Value): Variable<Value>

Declares a variable that may be unset, with the value it then takes. A set but malformed value is an issue, never the fallback.
The fallback is handed back as given and does not pass through the reader. A reader of secrets takes no fallback: the declaration is refused.
Parameters
NameTypeDescription
§reader
Reader<Value>How the variable's text becomes a value.
§fallback
ValueThe value of the variable when it is unset or empty.
Returns
Variable<Value>
The frozen variable, to place under its name in a group.
Example

Falling back only when the variable is unset

import { asPort, defineEnvironment, optional } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({ http: { PORT: optional(asPort(), 8080) } })
environment.load({}).http.PORT // => 8080
environment.check({ PORT: 'eighty' })
// => [{ name: 'PORT', group: 'http', problem: 'malformed', expected: 'an integer between 1 and 65535' }]
§function

required<Value>(reader: Reader<Value>): Variable<Value>

Declares a variable that must be set: an unset one is reported as missing.
Parameters
NameTypeDescription
§reader
Reader<Value>How the variable's text becomes a value.
Returns
Variable<Value>
The frozen variable, to place under its name in a group.
Example

Requiring a greeting

import { asText, defineEnvironment, required } from '@hyperfrontend/server/environment'

const environment = defineEnvironment({ hello: { HELLO_GREETING: required(asText()) } })
environment.check({})
// => [{ name: 'HELLO_GREETING', group: 'hello', problem: 'missing', expected: 'non-empty text' }]

◈ Interfaces

§interface

EnvironmentContract

A declared environment: what a service reads, checked as a whole.
Properties
§readonly variables:unknownEvery declared variable, in declaration order.
Methods
§check(env: EnvironmentRecord): unknown
Every issue in the environment, in declaration order; empty when it is valid.

Parameters

NameTypeDescription
§env
EnvironmentRecord
All values, frozen, or one error whose message lists every issue.

Parameters

NameTypeDescription
§env
EnvironmentRecord
§interface

EnvironmentIssue

One problem with one variable. It never carries a value.
Properties
§readonly name:stringThe environment variable's name.
§readonly group:stringThe group that declares it.
§readonly problem:"malformed" | "missing"missing for an unset required variable, malformed for a set value its reader refuses.
§readonly expected:stringThe reader's expected phrase.
§interface

PortOptions

What asPort is told about the ports it accepts.
Properties
§readonly allowZero?:booleanWhether port 0, which lets the operating system choose, is accepted.
§interface

Reader

Turns one raw string into a value. A consumer may write its own as a literal of this shape.
Properties
§readonly expected:stringCompletes "expected ..." in an issue line, for example an integer between 1 and 65535.
§readonly secret:booleanWhether the value is a secret; a secret may not have a fallback.
§readonly read:(raw: string) => ValueReturns the value, or undefined when the text is malformed. A throw also counts as malformed, and its message is dropped. So does a returned promise: a reader is synchronous.
§interface

SchemeOptions

What asUrl and asOrigin are told about the schemes they accept.
Properties
§readonly allowHttp?:booleanWhether plain http is accepted for a host that is not a loopback.
§interface

Secret

A value that prints [secret] through String, a template, JSON and inspection. reveal() is the only way out.
Methods
§reveal(): string
The secret itself. Use it inside a try and throw a message of your own: a parser, an argument check or a client library may quote the text it was given, and runService prints the message of a failed start.
§interface

SecretOptions

What asSecret is told about the secrets it accepts.
Properties
§readonly minLength?:numberThe fewest characters a secret may have; 16 when omitted.
§interface

Variable

One environment variable: how it reads and whether it must be set. Built by required and optional.
Properties
§readonly reader:Reader<Value>The reader that parses and describes it.
§readonly required:booleanWhether an unset variable is an issue.
§readonly fallback:ValueThe value of an unset optional variable.
§interface

VariableDescription

One declared variable, as data for documentation and build tooling. It never carries a value or a fallback.
Properties
§readonly name:stringThe environment variable's name.
§readonly group:stringThe group that declares it.
§readonly required:booleanWhether it must be set.
§readonly secret:booleanWhether it is a secret.
§readonly expected:stringThe reader's expected phrase.

◆ Types

§type

EnvironmentRecord

An environment to read; process.env is one.
type EnvironmentRecord = Readonly<Record<string, string | undefined>>
§type

EnvironmentShape

Groups of variables: the outer key is a group name, the inner key the environment variable's name.
type EnvironmentShape = Readonly<Record<string, Readonly<Record<string, Variable<unknown>>>>>
§type

EnvironmentValues

The values a shape loads to, under the same group and variable names.
type EnvironmentValues = mapped