Skip to Content
ArchitectureConfiguration Resolution

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.

  1. Environment file. envFilePath is path.join(<repository root>, process.env.DOT_ENV_CONFIG || ".env"). A missing file is not an error (dotenv.config is called with quiet: true and its result is ignored); the process then runs on the real environment alone. Because dotenv never overwrites an existing variable, a variable exported by the shell or the platform wins over the same name in the file. path.join appends the value to the repository root, so an absolute DOT_ENV_CONFIG is not used as an absolute path.
  2. Environment to AppConfig. The object literal reads each value from process.env and supplies a default. Parsing is inline: parseInt, === "true", split(","), JSON.parse for SETTINGS_FEATURED_LISTINGS, and the enum parsers in src/lib/config.utils.ts (an invalid enum list falls back to the default with a console.warn; an unknown AUTH_OTP_MESSAGE_TYPE falls back to link_and_code).
  3. Startup asserts. They run on the object literal, before Settings exists. A preset cannot satisfy them and cannot relax them. See Startup prerequisites.
  4. Preset lookup. Settings is constructed with config.app.settings (the value of APP_SETTINGS_PRESET).
  5. Merge. Settings.merge calls _.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.
  6. Post-processing. Settings.postProcess runs constructEventsCollectionUrls, always, with or without a preset.
  7. 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 valueResult
A scalar, including "", 0 and falseReplaces the env-built value
An array, including []Replaces the env-built array wholesale
nullReplaces 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 objectMerged key by key; keys the preset does not mention keep their env-built values
A key absent from the presetThe 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 / namespaceOriginMerge / default operationPhaseConsumerGeneric example
auth.jwt.* (key paths, issuer, expiry)Env (JWT_*)Preset may overrideAsserts check the key paths; files are read lazilysrc/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.roleOverridesEnv builds Agent.jwt.expire (AGENT_JWT_EXPIRE, default 1d)Objects merge; other roles are preset-onlyMergeAuthService.generateToken (only when persistence is on)preset auth: { roleOverrides: { Admin: { jwt: { expire: "1h" } } } }
auth.oauth.*.scopes, auth.social.*.scopesPreset-only: literal strings in config.ts, no env varReplaced by a preset scalarMergeOAuthService.urln/a
app.disable_persistenceEnv APP_DISABLE_PERSISTENCEPreset wins over the env varMergeAuthService.generateToken (the only reader in src/); package.json db:migrate:prod reads the environment variable, not the merged valueapp: { disable_persistence: true }
cache.*.ttl_msEnv (CACHE_*_TTL)Preset winsMerge@cached call sites, read at import time of the decorated classcache: { statswidget: { ttl_ms: 21_600_000 } }
repliers.api_key, historical_data_key, cache_warmup_api_key, rate limitsEnv only by convention (secrets)Preset may set them; secrets are conventionally env-onlyAsserts check api_key and the warmup/SSG pairRepliersBase, src/providers/throttler/*REPLIERS_API_LIMIT=5
repliers.autosuggest.*Env (REPLIERS_AUTOSUGGEST_*, PROXIMITY_SEARCH_*)Preset wins; array fields (listingStatus, listingType, …) are replacedMergeAutosuggestServicerepliers: { autosuggest: { max_results: 10 } }
mapbox.autosuggest.types, jaro_winkler_distancePreset-only: constants in config.ts ("street,postcode,address", 0.9)Preset scalar replacesMergeMapbox autosuggest pathmapbox: { autosuggest: { jaro_winkler_distance: 0.95 } }
mapbox.autosuggest.region_codeEnv PROXIMITY_SEARCH_REGION_CODEA preset undefined does not clear it (skipped)MergeMapbox autosuggest pathn/a
eventsCollection.*UrlEnv (BOSS_*_URL), absolute https://example.tld/... defaultsPreset wins; then rewritten by urlHostMerge, then post-processingEventsCollectionServicesee URL assembly
eventsCollection.formTagsPreset-only: no env varObjects mergeMergeselectRequestInfoParams.ts, selectScheduleParams.tsformTags: { inquiry: { sale: "Buy", rent: "Rent" } }
eventsCollection.defaultPersonFields.tags, eventTags.*Env (CSV)Arrays replacedMergeEventsCollectionServicetags: ["web"]
settings.scrubbing.*Env (SETTINGS_SCRUBBING_*)Arrays (board_ids, safeFields, dropFields, …) replacedMerge; src/services/scrubber/listings.ts reads dropFields, safeFields, safeAddressFields into module constants at importListingsScrubberscrubbing: { board_ids: [110] }
settings.defaults.*, settings.locations.*Env (APP_DEFAULTS_BOARDIDS, APP_LOCATIONS_BOARDID, SETTINGS_LOCATIONS_*)Preset wins; allowed_areas replacedMergesrc/services/listings.ts, routeslocations: { allow_all_areas: false, allowed_areas: [] }
settings.allowedListingsStandardStatusesEnv (CSV, undefined when unset)Preset winsMergeconstrainStandardStatus in src/services/listings/listingHelpers.ts, applied by src/services/repliers/listings.ts and src/services/repliers/favorites.tsallowedListingsStandardStatuses: ["Active"]
settings.restrictedListings, settings.mlsNumberPrefixEnv (SETTINGS_RESTRICTED_LISTINGS, SETTINGS_MLSNUMBER_PREFIX)Preset wins; array replacedMergesrc/services/listings.ts, favorites.ts, excludeRestrictedListings, mlsNumberPrefix.tsrestrictedListings: ["X1"]
settings.validationVersionEnv SETTINGS_VALIDATION_VERSIONPreset winsMerge; read at import of src/validate/contact.tsoverrides() in src/validate/overrides/overrides.tsvalidationVersion: ""
settings.featuredListingsEnv, JSON stringArray replacedMergefeatured-listings servicefeaturedListings: [{ slug: "a", clientId: 1 }]
db (connection, pool, migrations)Env (DATABASE_URL, DB_*); pool and migration directory are literalsPreset could overrideMergesrc/providers/db.ts, src/knexfile.tsDB_USE_SSL=true
nats.*Env (NATS_*)Preset wins (nats.enabled)Mergesrc/providers/nats.ts, src/worker.tsnats: { enabled: false }
boss.enabledEnv (BOSS_ENABLED, true unless exactly "false")Preset winsMergeBossService, eventsCollection middleware providerboss: { enabled: false }
redis.keyv_enableEnv REDIS_KEYV_ENABLEPreset winsMergeKeyv providers, @cachedredis: { keyv_enable: true }

Two things the register shows:

  • Not every AppConfig field has an env var. auth.oauth.*.scopes, auth.social.*.scopes, mapbox.autosuggest.types, mapbox.autosuggest.jaro_winkler_distance, eventsCollection.formTags, db.pool and db.migrations are constants or optional keys in config.ts. The first four can be changed only through a preset (or by editing the file). eventsCollection.formTags is 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_persistence hides APP_DISABLE_PERSISTENCE from 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.

ConditionMessage
Always: MAPBOX_ACCESS_TOKEN emptyNo MAPBOX_ACCESS_TOKEN env variable
Always: REPLIERS_API_KEY emptyNo REPLIERS_API_KEY env variable
Always: JWT_PRIVATE_KEY emptyNo JWT_PRIVATE_KEY env variable
Always: JWT_PUBLIC_KEY emptyNo JWT_PUBLIC_KEY env variable
REPLIERS_CACHE_WARMUP_API_KEY set and XFF_SSG_TOKEN (or REPLIERS_PROXY_XFF_SSG_TOKEN) emptyREPLIERS_CACHE_WARMUP_API_KEY is set but XFF_SSG_TOKEN is empty ...
BOSS_WEBHOOK_ENABLED=true and BOSS_SYSTEM emptyPlease, specify some unique BOSS_SYSTEM ...
… and also BOSS_WEBHOOK_USE_NGROK=true and NGROK_AUTHTOKEN emptyNo NGROK_AUTHTOKEN env variable
The raw process.env.APP_ENVIRONMENT is anything other than the string localhost (including unset) and GOOGLE_CREDENTIALS is emptyNo GOOGLE_CREDENTIALS env variable
DEBUG_AUTH_OTP_EXPOSE_CODE=true and APP_ENVIRONMENT contains prodDebugging 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 templatesResult
SetAll three relative (start with / or contain no ://)Each becomes host (trailing slashes stripped) + "/" + path (leading slashes stripped)
SetAny of the three absoluteThrows eventsCollection URL conflict: full URLs found while urlHost is set
Not setAll three absoluteUnchanged
Not setAny of the three relativeThrows 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_PRESETSETTINGS_EVENTS_COLLECTOR_URL_HOSTOutcome
unsetunsetStarts; templates stay https://example.tld/...; disable_persistence is false
defaultsunsetThrows the “relative but not set” error
defaultssetStarts; templates are prefixed with the host; disable_persistence is true
an unknown nameunsetStarts, 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.

ItemWhat it doesSource
allowedListingsStandardStatusesWhen 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 setconstrainStandardStatus in src/services/listings/listingHelpers.ts
hide_unavailable_listings_statuses, hide_unavailable_listings_standard_statuses, hide_unavailable_listings_http_codeStatus 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 listsrc/services/listings.ts
restrictedListingsMLS numbers the instance never serves; empty is offexcludeRestrictedListings, dropRestricted call sites in src/services/listings.ts, src/services/favorites.ts
validationVersionChooses 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 themsrc/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.

FeatureRequired services and settingsBehaviour when absent
Core processMAPBOX_ACCESS_TOKEN, REPLIERS_API_KEY, JWT_PRIVATE_KEY, JWT_PUBLIC_KEY (asserts)Process does not start
JWT signing and verificationReadable 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.tsA 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 appliedKnex 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 KeyvREDIS_KEYV_ENABLE=true, REDIS_URLIn-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_KEYDisabled: 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 webhooksBOSS_WEBHOOK_ENABLED=true, BOSS_SYSTEM, and BOSS_ENABLED; ngrok only with BOSS_WEBHOOK_USE_NGROK and NGROK_AUTHTOKENOff 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 workerNATS_ENABLED=true, NATS_SERVER, optional NATS_CREDS, stream and consumer namesnats.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
SMTPSMTP_ENABLED=true, GMAIL_USER, GMAIL_APP_PASSWORD; for contact notifications also REPLIERS_AGENT_EMAILSmtpService 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-inOAUTH_<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 loginAUTH_EMAILTOKEN_ENABLED=trueOff by default; AuthService.useRepliersToken throws ApiError 400 Endpoint is not activated when auth.emailtoken.enabled is false
OTP deliveryREPLIERS_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 MapsREPLIERS_AUTOSUGGEST_PROVIDER=googlemaps, GOOGLE_MAPS_API_KEYAutosuggestService.address switches provider; the key defaults to "", so the upstream call fails rather than the startup
Warmup key for SSG trafficREPLIERS_CACHE_WARMUP_API_KEY and XFF_SSG_TOKEN; optional REPLIERS_CACHE_WARMUP_API_LIMIT / _INTERVAL_MSNo 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 keyREPLIERS_API_KEY_EXTRAEmpty: EstimateService does not switch keys (if (historical_data_key))
Scrubbingsettings.scrubbing.board_ids (default 12 from env)Only listings whose boardId is in board_ids are scrubbed (ListingsScrubber)
Restricted listingssettings.restrictedListingsEmpty: no filtering; non-empty: removed from search, similar, history, favorites and single reads
MLS number prefixsettings.mlsNumberPrefixEmpty: the prefix codec is off
Allowed-status policysettings.allowedListingsStandardStatusesUnset or empty: constrainStandardStatus returns without changing the query
Google loggingAPP_LOGGING_GCP_LOGGER_ENABLEDOff by default; read in src/providers/logger.global.ts. GOOGLE_CREDENTIALS is not read there or anywhere else in src/
Swagger UIAPP_USESWAGGER=trueOff by default
Per-environment CORSAPP_CORS_DOMAIN (CSV), NODE_ENVOutside 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

ItemWhere
Construction order, asserts, mergesrc/config.ts; src/lib/settings.ts (Settings.merge, postProcess)
Preset registrysrc/settings/index.ts; the shipped preset is src/settings/defaults.ts
Env enum parsingsrc/lib/config.utils.ts
Teststest/lib/settings.test.ts (URL assembly, array replacement)
Combinations run for this pagesrc/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 checkoutThe 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

  1. 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).
  2. Unset APP_ENVIRONMENT demands GOOGLE_CREDENTIALS. The check reads process.env directly, not config.app.env (src/config.ts).
  3. The defaults preset needs SETTINGS_EVENTS_COLLECTOR_URL_HOST. Its URL templates are relative; without a host, constructEventsCollectionUrls throws (src/lib/settings.ts).
  4. A preset beats an exported variable. For any key the preset sets, the environment value is ignored, including app.disable_persistence (Settings.merge).
  5. undefined in a preset does nothing. Use an explicit empty value ("", [], false, null) to clear an env-built value (_.mergeWith semantics).
  6. Arrays are replaced whole. A preset board_ids or safeFields list is the complete list, not an addition (Settings.merge customizer).
  7. The persistence flag has two readers that can disagree. The app reads the merged value; db:migrate:prod reads the raw variable (src/services/auth.ts, package.json).
  8. An unknown preset name is only a warning. The process runs on environment defaults (Settings constructor).
  9. DOT_ENV_CONFIG is relative to the repository root. An absolute value is appended, not used as is (src/config.ts, envFilePath).
  10. The Mapbox token is required even with Google autosuggest (src/config.ts asserts).

Verified against portal-backend 997ae3e, 2026-10-20.

Last updated on