Configuration resolution
How the one AppConfig object the whole process reads is built: which file supplies the environment, which values come from environment variables, where the startup checks sit relative to the settings preset, how the preset is merged, what is derived afterwards, and which features need which settings. The two-layer model is introduced on Configuration Model; every variable is listed on Environment Variables. Terms: preset, instance.
Construction order
src/config.ts is evaluated once per process, synchronously, the first time anything imports it. The server (src/index.ts) and the worker (src/worker.ts) each build their own copy the same way. The preset modules are imported (evaluated) when src/config.ts imports src/lib/settings.ts, so before the asserts; they are only merged after them. The config container token (src/providers/config.ts) is a plain useValue of the merged object.
- Environment file.
envFilePathispath.join(<repository root>, process.env.DOT_ENV_CONFIG || ".env"). A missing file is not an error (dotenv.configis called withquiet: trueand its result is ignored); the process then runs on the real environment alone. Becausedotenvnever overwrites an existing variable, a variable exported by the shell or the platform wins over the same name in the file.path.joinappends the value to the repository root, so an absoluteDOT_ENV_CONFIGis not used as an absolute path. - Environment to
AppConfig. The object literal reads each value fromprocess.envand supplies a default. Parsing is inline:parseInt,=== "true",split(","),JSON.parseforSETTINGS_FEATURED_LISTINGS, and the enum parsers insrc/lib/config.utils.ts(an invalid enum list falls back to the default with aconsole.warn; an unknownAUTH_OTP_MESSAGE_TYPEfalls back tolink_and_code). - Startup asserts. They run on the object literal, before
Settingsexists. A preset cannot satisfy them and cannot relax them. See Startup prerequisites. - Preset lookup.
Settingsis constructed withconfig.app.settings(the value ofAPP_SETTINGS_PRESET). - Merge.
Settings.mergecalls_.mergeWith(config, preset, customizer). The customizer returns the source array whenever the source value is an array, so arrays are replaced, never concatenated or merged by index. - Post-processing.
Settings.postProcessrunsconstructEventsCollectionUrls, always, with or without a preset. - Export. The merged object is the module’s default export. It is the same object that was passed to
mergeWith: the merge mutates the env-built object in place.
Merge semantics
The preset is a DeepPartial<AppConfig> and wins over the environment for every key it sets. These rules come from _.mergeWith plus the array customizer, and were run against a small object to confirm them:
| Preset value | Result |
|---|---|
A scalar, including "", 0 and false | Replaces the env-built value |
An array, including [] | Replaces the env-built array wholesale |
null | Replaces the env-built value with null (verified with the same lodash call), so a preset can clear a value that way |
undefined (a key written with no value) | Skipped: the env-built value stays |
| A nested object | Merged key by key; keys the preset does not mention keep their env-built values |
| A key absent from the preset | The env-built value stays |
The test test/lib/settings.test.ts (“array overrides via merge”) covers the replacement of safeFields and dropFields and the retention of arrays the preset does not declare.
An unset or unknown preset name does not stop the process. With no name, Settings logs [SETTINGS] No preset specified. Using environment variables only.; with a name that is not a key of the registry (src/settings/index.ts), it logs [SETTINGS] Preset not found: <name>. In both cases the preset is empty and the merge changes nothing.
Not in OSS: the registry in src/settings/index.ts carries one import and one
entry per deployment inside @oss-remove-start / @oss-remove-end markers.
The open-source export registers defaults and a test fixture preset only, so
any other APP_SETTINGS_PRESET value takes the “not found” path there.
Effective configuration
Where a value comes from, how it is combined, and who reads it. “Env” means an AppConfig field built from process.env in src/config.ts; “preset” means a key a preset may set.
| Setting / namespace | Origin | Merge / default operation | Phase | Consumer | Generic example |
|---|---|---|---|---|---|
auth.jwt.* (key paths, issuer, expiry) | Env (JWT_*) | Preset may override | Asserts check the key paths; files are read lazily | src/providers/middleware/jwt/config.keys.ts (a value starting exactly -----BEGIN PRIVATE KEY----- / -----BEGIN PUBLIC KEY----- is used as the key text; any other value, including a -----BEGIN RSA PRIVATE KEY----- block, is treated as a file path and read from disk) | JWT_PRIVATE_KEY=keys/private.pem |
auth.roleOverrides | Env builds Agent.jwt.expire (AGENT_JWT_EXPIRE, default 1d) | Objects merge; other roles are preset-only | Merge | AuthService.generateToken (only when persistence is on) | preset auth: { roleOverrides: { Admin: { jwt: { expire: "1h" } } } } |
auth.oauth.*.scopes, auth.social.*.scopes | Preset-only: literal strings in config.ts, no env var | Replaced by a preset scalar | Merge | OAuthService.url | n/a |
app.disable_persistence | Env APP_DISABLE_PERSISTENCE | Preset wins over the env var | Merge | AuthService.generateToken (the only reader in src/); package.json db:migrate:prod reads the environment variable, not the merged value | app: { disable_persistence: true } |
cache.*.ttl_ms | Env (CACHE_*_TTL) | Preset wins | Merge | @cached call sites, read at import time of the decorated class | cache: { statswidget: { ttl_ms: 21_600_000 } } |
repliers.api_key, historical_data_key, cache_warmup_api_key, rate limits | Env only by convention (secrets) | Preset may set them; secrets are conventionally env-only | Asserts check api_key and the warmup/SSG pair | RepliersBase, src/providers/throttler/* | REPLIERS_API_LIMIT=5 |
repliers.autosuggest.* | Env (REPLIERS_AUTOSUGGEST_*, PROXIMITY_SEARCH_*) | Preset wins; array fields (listingStatus, listingType, …) are replaced | Merge | AutosuggestService | repliers: { autosuggest: { max_results: 10 } } |
mapbox.autosuggest.types, jaro_winkler_distance | Preset-only: constants in config.ts ("street,postcode,address", 0.9) | Preset scalar replaces | Merge | Mapbox autosuggest path | mapbox: { autosuggest: { jaro_winkler_distance: 0.95 } } |
mapbox.autosuggest.region_code | Env PROXIMITY_SEARCH_REGION_CODE | A preset undefined does not clear it (skipped) | Merge | Mapbox autosuggest path | n/a |
eventsCollection.*Url | Env (BOSS_*_URL), absolute https://example.tld/... defaults | Preset wins; then rewritten by urlHost | Merge, then post-processing | EventsCollectionService | see URL assembly |
eventsCollection.formTags | Preset-only: no env var | Objects merge | Merge | selectRequestInfoParams.ts, selectScheduleParams.ts | formTags: { inquiry: { sale: "Buy", rent: "Rent" } } |
eventsCollection.defaultPersonFields.tags, eventTags.* | Env (CSV) | Arrays replaced | Merge | EventsCollectionService | tags: ["web"] |
settings.scrubbing.* | Env (SETTINGS_SCRUBBING_*) | Arrays (board_ids, safeFields, dropFields, …) replaced | Merge; src/services/scrubber/listings.ts reads dropFields, safeFields, safeAddressFields into module constants at import | ListingsScrubber | scrubbing: { board_ids: [110] } |
settings.defaults.*, settings.locations.* | Env (APP_DEFAULTS_BOARDIDS, APP_LOCATIONS_BOARDID, SETTINGS_LOCATIONS_*) | Preset wins; allowed_areas replaced | Merge | src/services/listings.ts, routes | locations: { allow_all_areas: false, allowed_areas: [] } |
settings.allowedListingsStandardStatuses | Env (CSV, undefined when unset) | Preset wins | Merge | constrainStandardStatus in src/services/listings/listingHelpers.ts, applied by src/services/repliers/listings.ts and src/services/repliers/favorites.ts | allowedListingsStandardStatuses: ["Active"] |
settings.restrictedListings, settings.mlsNumberPrefix | Env (SETTINGS_RESTRICTED_LISTINGS, SETTINGS_MLSNUMBER_PREFIX) | Preset wins; array replaced | Merge | src/services/listings.ts, favorites.ts, excludeRestrictedListings, mlsNumberPrefix.ts | restrictedListings: ["X1"] |
settings.validationVersion | Env SETTINGS_VALIDATION_VERSION | Preset wins | Merge; read at import of src/validate/contact.ts | overrides() in src/validate/overrides/overrides.ts | validationVersion: "" |
settings.featuredListings | Env, JSON string | Array replaced | Merge | featured-listings service | featuredListings: [{ slug: "a", clientId: 1 }] |
db (connection, pool, migrations) | Env (DATABASE_URL, DB_*); pool and migration directory are literals | Preset could override | Merge | src/providers/db.ts, src/knexfile.ts | DB_USE_SSL=true |
nats.* | Env (NATS_*) | Preset wins (nats.enabled) | Merge | src/providers/nats.ts, src/worker.ts | nats: { enabled: false } |
boss.enabled | Env (BOSS_ENABLED, true unless exactly "false") | Preset wins | Merge | BossService, eventsCollection middleware provider | boss: { enabled: false } |
redis.keyv_enable | Env REDIS_KEYV_ENABLE | Preset wins | Merge | Keyv providers, @cached | redis: { keyv_enable: true } |
Two things the register shows:
- Not every
AppConfigfield has an env var.auth.oauth.*.scopes,auth.social.*.scopes,mapbox.autosuggest.types,mapbox.autosuggest.jaro_winkler_distance,eventsCollection.formTags,db.poolanddb.migrationsare constants or optional keys inconfig.ts. The first four can be changed only through a preset (or by editing the file).eventsCollection.formTagsis declared optional and has no default at all. - The preset wins over the environment for the keys it sets, even when the same variable is exported. A preset that sets
app.disable_persistencehidesAPP_DISABLE_PERSISTENCEfrom every reader of the merged object. The one reader outside the merged object,db:migrate:prod, still sees the raw variable, so the two can disagree.
Startup prerequisites
All asserts are in src/config.ts, after the object literal and before new Settings(...). Each failure is an AssertionError thrown at import time, so neither src/index.ts nor src/worker.ts starts.
| Condition | Message |
|---|---|
Always: MAPBOX_ACCESS_TOKEN empty | No MAPBOX_ACCESS_TOKEN env variable |
Always: REPLIERS_API_KEY empty | No REPLIERS_API_KEY env variable |
Always: JWT_PRIVATE_KEY empty | No JWT_PRIVATE_KEY env variable |
Always: JWT_PUBLIC_KEY empty | No JWT_PUBLIC_KEY env variable |
REPLIERS_CACHE_WARMUP_API_KEY set and XFF_SSG_TOKEN (or REPLIERS_PROXY_XFF_SSG_TOKEN) empty | REPLIERS_CACHE_WARMUP_API_KEY is set but XFF_SSG_TOKEN is empty ... |
BOSS_WEBHOOK_ENABLED=true and BOSS_SYSTEM empty | Please, specify some unique BOSS_SYSTEM ... |
… and also BOSS_WEBHOOK_USE_NGROK=true and NGROK_AUTHTOKEN empty | No NGROK_AUTHTOKEN env variable |
The raw process.env.APP_ENVIRONMENT is anything other than the string localhost (including unset) and GOOGLE_CREDENTIALS is empty | No GOOGLE_CREDENTIALS env variable |
DEBUG_AUTH_OTP_EXPOSE_CODE=true and APP_ENVIRONMENT contains prod | Debugging OTP exposed in production environment |
So the app does not always start: with an empty environment the process stops on the first assert. These checks read process.env or the env-built values, so a preset that sets repliers, mapbox or auth.jwt values does not satisfy them. The APP_ENVIRONMENT check uses the raw variable, not config.app.env (whose default is localhost): leaving the variable unset therefore requires GOOGLE_CREDENTIALS, although the merged config reports localhost. GOOGLE_CREDENTIALS is only asserted in src/; nothing in src/ reads its value.
The Mapbox token assert does not depend on REPLIERS_AUTOSUGGEST_PROVIDER; a deployment that uses Google for autosuggest still needs a non-empty Mapbox token to start.
There is a second, later class of startup failure in post-processing, described next.
Events collection URL assembly
constructEventsCollectionUrls (in src/lib/settings.ts) runs after the merge. It makes the three link templates (propertyUrl, clientUrl, estimateUrl) and, if non-empty, savedSearchUrl absolute:
SETTINGS_EVENTS_COLLECTOR_URL_HOST (urlHost) | The URL templates | Result |
|---|---|---|
| Set | All three relative (start with / or contain no ://) | Each becomes host (trailing slashes stripped) + "/" + path (leading slashes stripped) |
| Set | Any of the three absolute | Throws eventsCollection URL conflict: full URLs found while urlHost is set |
| Not set | All three absolute | Unchanged |
| Not set | Any of the three relative | Throws eventsCollection URLs are relative but SETTINGS_EVENTS_COLLECTOR_URL_HOST is not set |
The env defaults for the templates are absolute (https://example.tld/...); the defaults preset sets them relative (/listing/[MLS_NUMBER]?boardId=[BOARD_ID] and similar). Combinations that were run for this page, with placeholder values for the four required variables and no other settings:
APP_SETTINGS_PRESET | SETTINGS_EVENTS_COLLECTOR_URL_HOST | Outcome |
|---|---|---|
| unset | unset | Starts; templates stay https://example.tld/...; disable_persistence is false |
defaults | unset | Throws the “relative but not set” error |
defaults | set | Starts; templates are prefixed with the host; disable_persistence is true |
| an unknown name | unset | Starts, as with no preset |
A message is logged for the resolved URLs; a localhost in any of them adds a warning.
Immutability
The code never reloads configuration and nothing in src/ calls Object.freeze on it; the merged object is a plain mutable object shared by reference through the container (useValue) and by direct import config from "../config.js". “Immutable at runtime” therefore describes how the code is used: there is no endpoint or timer that changes settings, and a change needs a restart. Several modules copy values at import time (the scrubber’s field lists, validationVersion in src/validate/contact.ts, @cached TTLs), so those copies would not follow a later mutation even if one were made.
A preset is selected per process through an environment variable, so there is no per-request preset and no way for a request to choose one.
Policy and validation as configuration
Some values that behave like configuration are not in the environment/preset layers above, or they change behaviour in ways easy to miss.
| Item | What it does | Source |
|---|---|---|
allowedListingsStandardStatuses | When non-empty, every listings search and favorites query is narrowed in place: the caller’s standardStatus is intersected with the allowed set; an empty intersection or no filter becomes the full allowed set | constrainStandardStatus in src/services/listings/listingHelpers.ts |
hide_unavailable_listings_statuses, hide_unavailable_listings_standard_statuses, hide_unavailable_listings_http_code | Status lists (default empty) and the HTTP code (default 410). validateAvailability throws ApiError with that code for a single listing that is restricted, has displayInternetEntireListing N, or whose lastStatus / standardStatus is in the matching list | src/services/listings.ts |
restrictedListings | MLS numbers the instance never serves; empty is off | excludeRestrictedListings, dropRestricted call sites in src/services/listings.ts, src/services/favorites.ts |
validationVersion | Chooses the Joi schemas for contact and request-info. overrides(version) returns an object with optional contactSchema and requestInfoSchema; each is used when present, otherwise the shared schema in src/validate/contact.ts. An unrecognised or empty version returns {} | src/validate/overrides/overrides.ts, src/validate/contact.ts |
| Joi defaults | .default(...) values inside schemas (for example limit and offset in src/validate/admin.ts) fill omitted request fields. They are part of a request’s resolved input, not of AppConfig, and no preset or variable changes them | src/validate/*.ts |
Not in OSS: the override modules under src/validate/overrides/ (one case
in overrides() and its schema file) are tenant-only code between
@export-only-start / @export-only-end markers, and so are the matching DTO
types in src/validate/contact.ts. The open-source export keeps overrides()
with only the default branch.
Feature dependencies
What each feature needs and what the code does when it is missing. “Absent” means the setting is empty or the flag is off.
| Feature | Required services and settings | Behaviour when absent |
|---|---|---|
| Core process | MAPBOX_ACCESS_TOKEN, REPLIERS_API_KEY, JWT_PRIVATE_KEY, JWT_PUBLIC_KEY (asserts) | Process does not start |
| JWT signing and verification | Readable key files, or key text starting with exactly -----BEGIN PRIVATE KEY----- / -----BEGIN PUBLIC KEY-----; any other value is read as a path, resolved in src/providers/middleware/jwt/config.keys.ts | A path that does not exist throws from fs.readFileSync the first time the keys are resolved, not at the assert |
| Persistence-backed routes (ACL, assets, virtual tours, social links, sync, webhooks) | PostgreSQL reachable through config.db; migrations applied | Knex is created lazily by src/providers/db.ts; a repository call without a reachable database fails at that call. APP_DISABLE_PERSISTENCE / app.disable_persistence is read only in AuthService.generateToken (skips the ACL lookup, so no role from ACL and no per-role expiry) and in db:migrate:prod (skips migrations); it does not stop any other repository from querying |
| Redis-backed Keyv | REDIS_KEYV_ENABLE=true, REDIS_URL | In-memory Keyv per process: OTPs, blocklist and result caches are not shared and are lost on restart (see Data Ownership) |
| Follow Up Boss (CRM) | BOSS_ENABLED not "false", BOSS_USERNAME, BOSS_PASSWORD, BOSS_SYSTEM, BOSS_SYSTEM_KEY | Disabled: BossService.request logs a warning and returns {}; the events-collection middleware provider returns a no-op middleware. Enabled with empty credentials: requests are sent with empty auth and fail upstream |
| FUB webhooks | BOSS_WEBHOOK_ENABLED=true, BOSS_SYSTEM, and BOSS_ENABLED; ngrok only with BOSS_WEBHOOK_USE_NGROK and NGROK_AUTHTOKEN | Off by default; installHooks logs and returns. On with boss.enabled false: logs an error and returns. Missing BOSS_SYSTEM or ngrok token: assert |
| NATS and the worker | NATS_ENABLED=true, NATS_SERVER, optional NATS_CREDS, stream and consumer names | nats.enabled false: the nats token resolves to DummyNats; src/worker.ts still resolves that dummy consumer, but its consume loop is guarded by if (config.nats.enabled), so no loop runs |
| SMTP | SMTP_ENABLED=true, GMAIL_USER, GMAIL_APP_PASSWORD; for contact notifications also REPLIERS_AGENT_EMAIL | SmtpService creates no transport and send rejects with SMTP transport is not configured; the contact path in src/services/contact.ts uses SMTP only when both smtp.enabled and defaultAgentEmail are set, otherwise it sends through the Repliers messages API |
| OAuth sign-in | OAUTH_<PROVIDER>_CLIENT_ID, _CLIENT_SECRET, _REDIRECT_URI (CSV) | Google: src/providers/oauth/google.ts runs OpenID discovery with the configured client when first resolved. No redirect URI configured and none in the request: ApiError 400 A redirect_uri is not configured for <provider>.... The Facebook adapter is wired into OAuthService, but no oauth.facebook provider is registered in src/providers/index.ts |
| Social links (Pinterest) | SOCIAL_PINTEREST_* | Client id and secret default to "1", redirect URI to "" |
| Email-token login | AUTH_EMAILTOKEN_ENABLED=true | Off by default; AuthService.useRepliersToken throws ApiError 400 Endpoint is not activated when auth.emailtoken.enabled is false |
| OTP delivery | REPLIERS_AGENT_ID, REPLIERS_UNAUTHENTICATED_CLIENT_ID, AUTH_OTP_* | Ids default to 0; DEBUG_AUTH_OTP_EXPOSE_CODE is refused in an environment whose name contains prod |
| Geocoding: Mapbox (default) | MAPBOX_ACCESS_TOKEN, PROXIMITY_SEARCH_* | Token is asserted at startup in every case |
| Geocoding: Google Maps | REPLIERS_AUTOSUGGEST_PROVIDER=googlemaps, GOOGLE_MAPS_API_KEY | AutosuggestService.address switches provider; the key defaults to "", so the upstream call fails rather than the startup |
| Warmup key for SSG traffic | REPLIERS_CACHE_WARMUP_API_KEY and XFF_SSG_TOKEN; optional REPLIERS_CACHE_WARMUP_API_LIMIT / _INTERVAL_MS | No warmup key: an SSG request uses the normal key and the shared throttler (RepliersBase.resolveApiKey, activeThrottler). Warmup key without SSG token: assert. The SSG decision needs a non-empty X-Forwarded-For-Token header equal to the token (XFFProvider.isSsgRequest) |
| Historical data key | REPLIERS_API_KEY_EXTRA | Empty: EstimateService does not switch keys (if (historical_data_key)) |
| Scrubbing | settings.scrubbing.board_ids (default 12 from env) | Only listings whose boardId is in board_ids are scrubbed (ListingsScrubber) |
| Restricted listings | settings.restrictedListings | Empty: no filtering; non-empty: removed from search, similar, history, favorites and single reads |
| MLS number prefix | settings.mlsNumberPrefix | Empty: the prefix codec is off |
| Allowed-status policy | settings.allowedListingsStandardStatuses | Unset or empty: constrainStandardStatus returns without changing the query |
| Google logging | APP_LOGGING_GCP_LOGGER_ENABLED | Off by default; read in src/providers/logger.global.ts. GOOGLE_CREDENTIALS is not read there or anywhere else in src/ |
| Swagger UI | APP_USESWAGGER=true | Off by default |
| Per-environment CORS | APP_CORS_DOMAIN (CSV), NODE_ENV | Outside production the CORS middleware allows any origin; in production it echoes only matching origins and otherwise returns the first valid domain |
Not in OSS: cache.listingsLastUpdatedOn
(CACHE_LISTINGS_LAST_UPDATED_ON_TTL) is declared and set only between
@oss-remove-start / @oss-remove-end markers in src/config.ts.
Evidence
| Item | Where |
|---|---|
| Construction order, asserts, merge | src/config.ts; src/lib/settings.ts (Settings.merge, postProcess) |
| Preset registry | src/settings/index.ts; the shipped preset is src/settings/defaults.ts |
| Env enum parsing | src/lib/config.utils.ts |
| Tests | test/lib/settings.test.ts (URL assembly, array replacement) |
| Combinations run for this page | src/config.ts imported with placeholder values for the four required variables and no env file; the four outcomes in the URL table above |
| Not established by this checkout | The environment, presets and secrets of any real deployment; whether a given upstream key is valid; behaviour of Redis or NATS when they are down |
Gotchas
- Asserts run before the preset merge. A preset cannot provide
MAPBOX_ACCESS_TOKEN, the Repliers key or the JWT paths; they must be in the environment (src/config.ts). - Unset
APP_ENVIRONMENTdemandsGOOGLE_CREDENTIALS. The check readsprocess.envdirectly, notconfig.app.env(src/config.ts). - The
defaultspreset needsSETTINGS_EVENTS_COLLECTOR_URL_HOST. Its URL templates are relative; without a host,constructEventsCollectionUrlsthrows (src/lib/settings.ts). - A preset beats an exported variable. For any key the preset sets, the environment value is ignored, including
app.disable_persistence(Settings.merge). undefinedin a preset does nothing. Use an explicit empty value ("",[],false,null) to clear an env-built value (_.mergeWithsemantics).- Arrays are replaced whole. A preset
board_idsorsafeFieldslist is the complete list, not an addition (Settings.mergecustomizer). - The persistence flag has two readers that can disagree. The app reads the merged value;
db:migrate:prodreads the raw variable (src/services/auth.ts,package.json). - An unknown preset name is only a warning. The process runs on environment defaults (
Settingsconstructor). DOT_ENV_CONFIGis relative to the repository root. An absolute value is appended, not used as is (src/config.ts,envFilePath).- The Mapbox token is required even with Google autosuggest (
src/config.tsasserts).
Verified against portal-backend 997ae3e, 2026-10-20.