# 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. ```ts 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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-EnvironmentContract) throws one error named EnvironmentError whose message lists every problem, so a deployment is fixed in one pass instead of one variable per restart: ```ts 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 } ``` ```text 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`](https://www.hyperfrontend.dev/docs/libraries/server/#api-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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-EnvironmentContract) returns the same problems as a list and never throws, for a tool that prints or counts them itself: ```ts 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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-EnvironmentContract-prop-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 with | When the variable is unset | When it is set | | ------------------------------------------------------------------------------------------- | --------------------------------------------- | -------------------------------------------------------- | | [`required`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-required) | A problem, reported as missing | Read; a value the reader refuses is a problem, malformed | | [`optional`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-optional) | The fallback, as given and without being read | Read; 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(asText(), undefined)`. ### Readers | Reader | Accepts | Returns | | ----------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------- | | [`asPort`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asPort) | Decimal digits from 1 to 65535, with no sign, padding, fraction or exponent; 0 as well with `asPort({ allowZero: true })` | The port, a number | | [`asUrl`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asUrl) | An 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 | | [`asOrigin`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asOrigin) | A URL under the same scheme rule that is an origin and nothing more: no path, no query, no fragment | The origin, with no trailing slash | | [`asDuration`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asDuration) | A whole count and its unit, as in `250ms`, `30s`, `5m` or `1h` | Milliseconds, a number | | [`asSecret`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asSecret) | At least 16 characters, or the count given as `asSecret({ minLength: 32 })` | The text wrapped so that it cannot print | | [`asText`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-asText) | Any text that is not empty | The 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: ```ts 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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-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`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-required) or [`optional`](https://www.hyperfrontend.dev/docs/libraries/server/environment/#api-optional), a name declared in two groups, and a secret with a fallback. ## API Reference ### Functions #### asDuration ```typescript function asDuration(): Reader ``` 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`: A frozen reader that yields a whole number of milliseconds. **Example: Reading a refresh interval** ```typescript import { asDuration } from '@hyperfrontend/server/environment' asDuration().read('5m') // => 300000 asDuration().read('30') // => undefined ``` #### asOrigin ```typescript function asOrigin(options?: SchemeOptions): Reader ``` 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** | Name | Type | Description | | --- | --- | --- | | `options?` | `SchemeOptions` | Whether plain `http` is accepted for every host; it is not when omitted. | **Returns** `Reader`: A frozen reader that yields the serialised origin. **Example: Reading the origin of the site that calls a service** ```typescript import { asOrigin } from '@hyperfrontend/server/environment' asOrigin().read('https://site.example:443/') // => 'https://site.example' asOrigin().read('https://site.example/app') // => undefined ``` #### asPort ```typescript function asPort(options?: PortOptions): Reader ``` 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** | Name | Type | Description | | --- | --- | --- | | `options?` | `PortOptions` | Whether port 0 is accepted; it is not when omitted. | **Returns** `Reader`: A frozen reader that yields the port as a number. **Example: Declaring a port the operating system may choose** ```typescript 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 ``` #### asSecret ```typescript function asSecret(options?: SecretOptions): Reader ``` 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** | Name | Type | Description | | --- | --- | --- | | `options?` | `SecretOptions` | The fewest characters a secret may have. | **Returns** `Reader`: A frozen reader that yields the wrapped secret. **Example: Reading a service key** ```typescript 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' ``` #### asText ```typescript function asText(): Reader ``` Reads any non-empty text, as it is: nothing is trimmed. **Returns** `Reader`: A frozen reader that yields the text. **Example: Reading a host name** ```typescript import { asText } from '@hyperfrontend/server/environment' asText().read('0.0.0.0') // => '0.0.0.0' asText().read('') // => undefined ``` #### asUrl ```typescript function asUrl(options?: SchemeOptions): Reader ``` 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** | Name | Type | Description | | --- | --- | --- | | `options?` | `SchemeOptions` | Whether plain `http` is accepted for every host; it is not when omitted. | **Returns** `Reader`: A frozen reader that yields the URL's normalised text. **Example: Reading an identity provider's address** ```typescript 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/' ``` #### defineEnvironment ```typescript function defineEnvironment(shape: Shape): EnvironmentContract ``` 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** | Name | Type | Description | | --- | --- | --- | | `shape` | `Shape` | The groups, each a plain object of variables keyed by environment variable name. | **Returns** `EnvironmentContract`: The frozen contract: the declared variables as data, and the two ways to read an environment. **Example: Loading a service's environment at boot** ```typescript 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 ``` **Example: Reporting every problem without a value in it** ```typescript 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. ``` #### optional ```typescript function optional(reader: Reader, fallback: Value): Variable ``` 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** | Name | Type | Description | | --- | --- | --- | | `reader` | `Reader` | How the variable's text becomes a value. | | `fallback` | `Value` | The value of the variable when it is unset or empty. | **Returns** `Variable`: The frozen variable, to place under its name in a group. **Example: Falling back only when the variable is unset** ```typescript 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' }] ``` #### required ```typescript function required(reader: Reader): Variable ``` Declares a variable that must be set: an unset one is reported as missing. **Parameters** | Name | Type | Description | | --- | --- | --- | | `reader` | `Reader` | How the variable's text becomes a value. | **Returns** `Variable`: The frozen variable, to place under its name in a group. **Example: Requiring a greeting** ```typescript 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 #### EnvironmentContract A declared environment: what a service reads, checked as a whole. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly variables` | `unknown` | Every declared variable, in declaration order. | ##### check ```typescript check(env: EnvironmentRecord): unknown ``` Every issue in the environment, in declaration order; empty when it is valid. **Parameters** | Name | Type | Description | | --- | --- | --- | | `env` | `EnvironmentRecord` | | ##### load ```typescript load(env: EnvironmentRecord): EnvironmentValues ``` All values, frozen, or one error whose message lists every issue. **Parameters** | Name | Type | Description | | --- | --- | --- | | `env` | `EnvironmentRecord` | | #### EnvironmentIssue One problem with one variable. It never carries a value. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The environment variable's name. | | `readonly group` | `string` | The group that declares it. | | `readonly problem` | `"malformed" \| "missing"` | `missing` for an unset required variable, `malformed` for a set value its reader refuses. | | `readonly expected` | `string` | The reader's `expected` phrase. | #### PortOptions What asPort is told about the ports it accepts. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly allowZero?` | `boolean` | Whether port 0, which lets the operating system choose, is accepted. | #### Reader Turns one raw string into a value. A consumer may write its own as a literal of this shape. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly expected` | `string` | Completes "expected ..." in an issue line, for example `an integer between 1 and 65535`. | | `readonly secret` | `boolean` | Whether the value is a secret; a secret may not have a fallback. | | `readonly read` | `(raw: string) => Value` | Returns 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. | #### SchemeOptions What asUrl and asOrigin are told about the schemes they accept. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly allowHttp?` | `boolean` | Whether plain `http` is accepted for a host that is not a loopback. | #### Secret A value that prints `[secret]` through `String`, a template, JSON and inspection. `reveal()` is the only way out. ##### reveal ```typescript 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. #### SecretOptions What asSecret is told about the secrets it accepts. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly minLength?` | `number` | The fewest characters a secret may have; 16 when omitted. | #### Variable One environment variable: how it reads and whether it must be set. Built by `required` and `optional`. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly reader` | `Reader` | The reader that parses and describes it. | | `readonly required` | `boolean` | Whether an unset variable is an issue. | | `readonly fallback` | `Value` | The value of an unset optional variable. | #### VariableDescription One declared variable, as data for documentation and build tooling. It never carries a value or a fallback. **Properties** | Name | Type | Description | | --- | --- | --- | | `readonly name` | `string` | The environment variable's name. | | `readonly group` | `string` | The group that declares it. | | `readonly required` | `boolean` | Whether it must be set. | | `readonly secret` | `boolean` | Whether it is a secret. | | `readonly expected` | `string` | The reader's `expected` phrase. | ### Types #### EnvironmentRecord An environment to read; `process.env` is one. ```typescript type EnvironmentRecord = Readonly> ``` #### EnvironmentShape Groups of variables: the outer key is a group name, the inner key the environment variable's name. ```typescript type EnvironmentShape = Readonly>>>> ``` #### EnvironmentValues The values a shape loads to, under the same group and variable names. ```typescript type EnvironmentValues = mapped ``` --- Canonical page: https://www.hyperfrontend.dev/docs/libraries/server/environment/ This file: https://www.hyperfrontend.dev/docs/libraries/server/environment.md Documentation index: https://www.hyperfrontend.dev/llms.txt