The source of truth for environment configuration is the repo-root .env.example file. This page walks through it grouped by domain. Which keys each host reads is declared in @repo/config (packages/config), parsed at boot by apps/api, apps/worker and the apps/svelte-web server; bun run scripts/check-env-schema.ts (CI) fails when .env.example, the per-app .env.example files or turbo.json drift from it. A bad environment refuses to boot; CONFIG_ENFORCE=false logs the report and starts anyway.
App connection string. Railway DEV uses a service reference to the private postgres.railway.internal host.
DIRECT_URL
Direct DB connection used by migrations. Railway DEV also derives it from the postgres service rather than duplicating a credential.
DATABASE_POOL_MAX
Max pg connections per process (packages/database/src/kysely.ts). Default 10; the svelte-web Dockerfile sets 5 because web serves many short requests per instance (PRO-173, decision D2). Every autoscaled instance opens its own pool, so size it against the database’s connection limit.
DATABASE_POOL_IDLE_TIMEOUT_MS
Close a pooled connection idle this long. Default 30000; 0 keeps connections open.
DATABASE_POOL_CONNECT_TIMEOUT_MS
Fail a checkout waiting this long for a free connection. Default 10000; 0 waits forever. A pool that is too small for the load surfaces here as timeout exceeded when trying to connect.
DATABASE_STATEMENT_TIMEOUT_MS
Server-side statement_timeout sent as a startup parameter on every pooled connection. Default 30000; 0 disables. The migrators and the operator scripts under apps/worker/scripts/ use getDbWithoutStatementTimeout() and are exempt; inside a host, wrap a known-long query in a transaction with SET LOCAL statement_timeout. A tripped timeout is pg SQLSTATE 57014, tagged db_timeout=statement_timeout on the Sentry event by all three hosts. Invalid values for any of these four log one warning at boot and keep the default.
32+ character secret. Generate with openssl rand -base64 32.
BETTER_AUTH_URL
Origin for cookie scope. http://localhost:5173 in dev.
COOKIE_DOMAIN
Leave unset for single-origin dev/prod. Set to a parent domain (.<domain>) once apps/api is on a sibling subdomain — adds Domain + crossSubDomainCookies for sharing. Cookies stay SameSite=Lax (web↔api are same-site).
AUTH_COOKIE_PREFIX
Per-environment session cookie name prefix (kottia-dev / kottia-stg / kottia). PRD’s apex-scoped Domain=.kottia.com cookie also reaches the dev/stg hosts, so distinct names keep the tiers’ sessions from overwriting each other in one browser profile. Unset = Better Auth’s default better-auth, which local dev, the e2e fixtures and the contract-fixture generator expect. Changing it on a deployed tier signs everyone out once.
TRUSTED_PROXY_CIDRS
Comma-separated IPv4 CIDRs whose socket peers may supply forwarded client-IP headers. Railway DEV currently sets 100.64.0.0/10 on web and API as the internal proxy range. Treat it as provisional: verify observed socket peers and prove that forged forwarding headers sent directly to Railway-provided domains cannot influence client-IP resolution before calling it final. When unset in production, getTrustedClientIp fails closed to the socket peer.
AUTH_TRUST_CUSTOM_SCHEMES
true (default) keeps the native apps’ custom URL schemes in Better Auth trustedOrigins. Set false only after verified App Links are live — otherwise mobile sign-in breaks.
Comma-separated browser origin allowlist. Used by both the CORS layer and the CSRF Origin allowlist (enforceOrigin + avatar guard) — a browser request with a non-listed Origin is rejected 403. Mobile (RN fetch) sends no Origin and is exempt.
BETTER_AUTH_URL_API
Override BETTER_AUTH_URL specifically for apps/api. Falls back to BETTER_AUTH_URL when unset.
Local-tooling only — consumed by native/tooling/src/firebase-distribute.ts (Bun auto-loads .env.local from the repo root), never by an app build or a deployed service. CLI auth is a one-time firebase login, not an env var.
Origin of the standalone tRPC host for browser-side fetches. Build-time — baked into the browser bundle via a Vite define; a runtime change does nothing, so rebuild. Required on Railway DEV as https://api.dev.useast.kottia.com. Railway passes service variables to Docker builds for matching declared ARGs, which is how the existing Dockerfile receives it. SSR/form actions are unaffected because they use createCaller(locals) in process.
Sender address (e.g. noreply@<domain>). The domain must be verified in Resend for each tier before that tier’s first account purge: the account deleted email cannot be resent later (see Transactional email).
CONTACT_INBOX_EMAIL
Inbox for the footer “Contacto” form (web /contact action, PRO-120). Messages arrive with the visitor as reply-to; unset makes the form report a send failure.
redis://... or rediss://... for TLS. The volatile instance (ADR-0028): server-side cache and rate-limit counters — maxmemory-policy volatile-lru, no persistence. Also the fallback for VALKEY_DURABLE_URL.
VALKEY_DURABLE_URL
The durable instance: BullMQ queues (db1), the psearch:* property search index (db0), withLock keys, session-revocation epochs — maxmemory-policy noeviction + AOF. Optional: unset, everything uses VALKEY_URL (one instance, the pre-split behaviour). On Railway DEV it references the original valkey service (\${{valkey.VALKEY_URL}} in Doppler) while VALKEY_URL references valkey-volatile. See ADR-0028.
VALKEY_TLS
true for self-signed TLS (Proxmox). The TLS settings apply to both instances.
VALKEY_TLS_REJECT_UNAUTHORIZED
false to accept self-signed certs over TLS (default verifies). Honored by @repo/cache, the shared queue connection, and the worker (apps/worker/src/connection.ts no longer hardcodes rejectUnauthorized: false).
VALKEY_CA_CERT
Optional PEM CA cert for verifying a private TLS Valkey endpoint.
QUEUE_SUFFIX
Suffix appended to every BullMQ queue name. Railway DEV and local dev use -dev; production will leave it empty. Producer and worker must use the same suffix.
WORKER_QUEUES
Worker only (PRO-168). Which queues this process consumes: a comma-separated list of queue names (search-indexing, leads, alerts, billing, cdn-purge, storage, accounts, identity, image-sanitize, ai-room-staging, ai-descriptions, listing-import, ai-import-extraction) and/or the pool aliases core (the first eight) and media (the last five). Unset or empty means all thirteen — the single-service default on DEV today. Names are exact and case-sensitive; an unknown name stops the boot with the valid list in the error. Every repeatable job is registered by the module that consumes its queue, so a pool owns exactly its own schedulers and two pools never double-fire or orphan one. /health reports only the queues the process started. Set it per service when the worker is split into core / media pools (two Railway services from one image); until then leave it unset.
DLQ_RETENTION_DAYS
Days to retain failed_lead_ingestions rows before the worker dlq-purge job deletes them (default 90). Resolved / replayed / discarded rows are purged regardless of age.
ACCOUNT_DELETION_GRACE_DAYS
Days between an account-deletion request and the worker purge that erases the PII (default 30). The account is hidden and its listings go offline at request time; signing in before the window ends restores it. Read by @repo/integrations (requestAccountDeletion) when the request is opened — it fixes scheduledFor on the row; the worker’s hourly account-purge-scan only compares that timestamp, so changing the value later does not move purges already scheduled. Set in Doppler dev (inherited by every branch config); add it to each STG/PRD config when those exist.
BULL_BOARD_USER / BULL_BOARD_PASSWORD
HTTP Basic auth for the worker’s Bull Board dashboard. DEV/STG only — Bull Board is not deployed in PRD (a Cloud Run worker pool has no URL; PRD uses the queue:admin scripts — see Incident guides). Required wherever the dashboard runs, in every environment — the worker refuses to start it without both (it grants full queue control + exposes lead PII, and binds 0.0.0.0). Leaving them unset is what keeps the dashboard off PRD; there is no NODE_ENV gate, and none would work, because apps/worker/Dockerfile pins NODE_ENV=production into DEV and STG images too. The credential gate itself used to key off NODE_ENV=production, which served the dashboard unauthenticated wherever the platform env said development/staging. Failed auth attempts are limited to 10/min per client IP (resolved through getTrustedClientIp, so admins behind a proxy don’t share one bucket), after which the IP is refused for 5 minutes before its password is compared. During a Valkey outage the counter still denies but the lockout is not remembered — degraded, not absent.
S3-compatible endpoint. Cloudflare R2 (https://<ACCOUNT_ID>.r2.cloudflarestorage.com, region auto) on the deployed dev env; local SeaweedFS / MinIO for local dev. The S3 client keeps forcePathStyle.
AWS_S3_BUCKET_NAME
Bucket name (e.g. uploads).
AWS_ACCESS_KEY_ID / AWS_SECRET_ACCESS_KEY
Credentials.
AWS_DEFAULT_REGION
auto for Cloudflare R2 (dev env). us-east-1 for local SeaweedFS / MinIO (conventional default).
Fail-closed paid-prediction switch. Only exact true enables submissions/new provider attempts; unset or false stays disabled. Set identically on svelte-web, apps/api, and worker. Persisted active attempts remain recoverable/cancelable.
BFL_API_KEY
Worker only. Creates and polls FLUX.2 [pro] tasks on the Black Forest Labs API (x-key header). Never placed on apps/api or svelte-web; there is no staging webhook.
AI_STAGING_LEGACY_ALIAS_SUNSET_AT
svelte-web + apps/api. ISO timestamp ending the 90-day compatibility window for the six legacy style names.
AI_STAGING_RESOLUTION
svelte-web + apps/api. Output megapixel budget captured on each new job: match_input, 1mp (default), 2mp, or 4mp. The worker derives the exact width/height from the source photo and keeps its aspect ratio.
AI_STAGING_OUTPUT_FORMAT
svelte-web + apps/api. jpeg (default), png, or webp; captured on each new job.
AI_STAGING_PROVIDER_MODEL
svelte-web + apps/api. BFL model for new staging jobs: unset is flux-2-pro (default); flux-3-image opts in to anchor boxes (PRO-107, off until its paid spike passes). Any other value fails submission closed.
Worker only. Independent BullMQ controls for the dedicated ai-staging queue. BFL allows 24 active tasks per account, so concurrency × worker replicas must stay at or below it.
AI_DESCRIPTION_CONCURRENCY
Worker only. Description queue concurrency; intentionally separate from staging.
AI_STAGING_STRUCTURE_CHECK
Worker only. Structural guardrail mode (PRO-64): off, log (default; record a Claude structure verdict on every attempt, never reject) or enforce (a drifted output fails with OUTPUT_STRUCTURE_DRIFT and is retried once on a new seed). Any other value is treated as log. Uses ANTHROPIC_API_KEY.
AI_STAGING_USER_HASH_SECRET
Worker only. Independent HMAC secret used to pseudonymize the opaque user identifier sent to BFL. Generate with openssl rand -hex 32.
Three independent, strict-"true" kill switches (PRO-79 / PRO-81 / PRO-82). Set each one identically on svelte-web, apps/api and the worker — the web reads them for routes and the dropzone, the shared service for create / confirm, the api host for the document upload route, the worker to start the queues. All three are false on PRD until QA signs off the matching scenarios in the Testing team.
Variable
Purpose / placement
LISTING_IMPORT_ENABLED
Phase 1: the spreadsheet importer at /dashboard/listings/import, the listing-import queue (import-batch, import-purge, import-document-purge). The plan gate (maxImportRowsPerBatch) is the product control once enabled. Geocoding at preview time uses GOOGLE_MAPS_API_KEY.
IMPORT_AI_MAPPING_ENABLED
Phase 2: Claude header mapping for spreadsheets that do not match the template (ai queue, ANTHROPIC_API_KEY on the worker). Off, such a file is refused with header_row_missing.
IMPORT_AI_EXTRACTION_ENABLED
Phase 3: PDF / DOCX documents through POST /api/listing-imports/document and the dedicated ai-import queue (ANTHROPIC_API_KEY on the worker; pdf-lib and mammoth are pure JS, no image change). Documents live under the S3 prefix imports/ for 7 days after the batch finishes. Off, the dropzone accepts spreadsheets only and the route answers import_ai_extraction_disabled.
IMPORT_PARSER_ISOLATION
apps/api + worker (PRO-100). The document parsers (pdf-lib, mammoth) run in a throwaway child process per document under the budget below; a child stopped by a limit refuses the document (import_document_invalid at upload, document_unreadable in the worker). On unless exactly "false"; turn it off only to debug locally. Leave it unset in every deployed environment.
IMPORT_PARSER_MAX_RSS_MB
apps/api + worker. The parser child’s resident-memory watchdog, default 768. The in-process bounds keep a legitimate 20 MB document far below it; raise it only if the worker logs a memory budget refusal on a document that should pass.
Spend per month, for the three Claude uses of the importer:
select date_trunc('month', "createdAt") asmonth, type, count(*) as jobs,
sum("tokensIn") as tokens_in, sum("tokensOut") as tokens_out, sum("costCents") as cents
Public origin serving signed images (e.g. https://assets.<domain>).
IMGPROXY_KEY / IMGPROXY_SALT
Hex-encoded HMAC key + salt. Match the imgproxy container config.
IMGPROXY_URL_TTL_SECONDS
Signed URL lifetime (default 86400 = 24 hours). Expiry is part of the HMAC payload — leaked URLs stop working after this window. Also caps the image routes’ cache window: both /api/images/* proxies ship max-age = s-maxage = min(86400, this), so lowering it shortens the browser and CDN windows with it. A literal 0 is the exception — it disables signature expiry rather than requesting a zero-second cache, so the window stays at 86400. Empty, unset, or non-numeric all fall back to the default; only a literal 0 disables expiry (not recommended — the URL then never stops working).
Worker only — consumed by the cdn-purge queue, which evicts a listing’s photos from the edge when it stops being publicly viewable.
Variable
Purpose
CDN_PURGE_PROVIDER
cloudflare, or gcp-cloud-cdn (not implemented — throws on the first job so a misconfigured STG fails loudly; see PRODUCTION.md prerequisite 8). Leave unset to disable purging: jobs complete as no-ops with one log line per process and de-listed photos stay cached until the 24h s-maxage clamp expires.
CLOUDFLARE_ZONE_ID
Zone containing the web + api hosts.
CLOUDFLARE_API_TOKEN
API token scoped to exactly one permission: Zone → Cache Purge. Cloudflare honours tag purges on Enterprise zones only — on any other plan the worker logs one Sentry warning (cdn-purge-unsupported) and falls back to the 24h bound.
Worker only — consumed by the storage queue. The per-minute outbox drain needs no configuration; these two govern the daily orphan sweep.
Variable
Purpose
STORAGE_ORPHAN_SWEEP_EXECUTE
Only exact true arms the sweep to act. Unset (the default) is report-only: it logs a summary and raises one fingerprinted Sentry warning when it finds anything. When armed it still does not call DeleteObject — it enqueues the keys into storage_deletion_outbox with reason ORPHAN_SWEEP, so the drain’s reference re-check remains the single deletion path. Leave unset until a dry run has been read.
STORAGE_ORPHAN_SWEEP_GRACE_HOURS
How old an unreferenced object must be before it counts as an orphan (default 48). Must cover both the pending-upload window (bytes land before the row that points at them) and the drain’s 24h “still referenced” defer. Empty, unset, negative, fractional or non-numeric all fall back to the default; only a literal 0 disables the grace, which is for local verification and never production.
Server-only. Signs the userToken for Knock Feed authenticate(). Required in production — signKnockUserToken throws when missing. Enable “Require identification token verification” in the Knock dashboard.
KNOCK_FCM_CHANNEL_ID
Server-only. Android FCM push (shared by both apps).
KNOCK_APNS_CHANNEL_ID
Server-only. iOS APNs for the agent app.
KNOCK_APNS_USER_CHANNEL_ID
Server-only. iOS APNs for the customer app (separate bundle id / auth key). registerDevice’s app field routes customer tokens here; leave empty until the channel is provisioned (push then no-ops).
KNOCK_SERVICE_TOKEN
CLI/CI only — not read by the app. Authenticates the Knock CLI for knock push/pull against the knock/ source of truth.
Consent-gated product analytics in the browser. svelte-web, apps/api and the worker also use them server-side to read the product flags (PRO-170); unset, each flag reads its env key.
POSTHOG_PERSONAL_API_KEY
Server-only, worker. A PostHog personal API key with the person:write scope (the project key cannot delete persons). The account purge uses it to delete the user’s PostHog person with its events and recordings. Unset: that step is skipped.
POSTHOG_PROJECT_ID
Worker. Numeric PostHog project id for the purge step above. Both this and the key must be set.
POSTHOG_API_HOST
Worker, optional. PostHog app host for that API call; defaults to https://us.posthog.com (not the us.i.posthog.com ingest host).
SENTRY_DSN / VITE_SENTRY_DSN
Error + replay. One project per deployable, so each service (svelte-web, apps/api, apps/worker) sets SENTRY_DSN to its own project’s DSN; VITE_SENTRY_DSN is the svelte-web client DSN (same project as the server). Native-app DSNs are inlined in each app’s Monitoring init (publishable, not env).
SENTRY_RELEASE
apps/api, optional. Release tag on captured events; unset, the commit Railway injects as RAILWAY_GIT_COMMIT_SHA is used.
SENTRY_ENVIRONMENT
Tier tag on captured events (development / staging / production). apps/api, the svelte-web server hooks and apps/worker read it ahead of NODE_ENV, which every Dockerfile pins to production and so cannot distinguish the tiers. Set per Doppler root config.
SENTRY_ORG / SENTRY_PROJECT / SENTRY_AUTH_TOKEN
Source-map / symbol upload during build (svelte-web; native apps upload symbols from their own build pipelines).
Server-only. apps/api (session create, decision reads) and apps/worker (reconcile scan, account purge). Use the Sandbox application’s key everywhere except production. Unset: verification reads as unavailable.
DIDIT_WORKFLOW_ID
The Didit workflow new sessions run on. Same hosts.
DIDIT_ENVIRONMENT
sandbox (default) or live: the Didit application this deployment works against. Results from the other environment are ignored. All three hosts, with the same value.
DIDIT_WEBHOOK_SECRET
apps/api only. The webhook destination’s secret_shared_key; verifies POST /api/webhooks/didit.
IDENTITY_VERIFICATION_ENABLED
The env default of the identity-verificationproduct flag. All three hosts.
Server-only. Read by @repo/integrations, apps/api (the webhook at POST /api/webhooks/stripe) and apps/worker (the daily stripe-reconcile). Unset disables checkout and the billing pages rather than erroring. Test and live are separate keys — each tier needs its own.
NATIVE_PURCHASE_MODE
The env default of the native-purchase-modeproduct flag: it answers only while that flag does not exist in PostHog. apps/api only, read per request and returned on billing.getSubscription (PRO-110). Decides how the native apps start a purchase: web (default, and any unknown value) opens /dashboard/billing in the in-app browser, checkout opens Stripe Checkout / the Customer Portal directly, hidden shows no link. App Store and Google Play payment policies for the Mexico storefronts forbid in-app links to non-store purchases, so leave it unset unless a store decision changes; flipping it needs no app release.
STRIPE_WEBHOOK_SIGNING_SECRET
Verifies the webhook signature before any event is trusted. It is per endpoint, not per account, so a new endpoint means a new secret even in the same Stripe account.
Checkout is Stripe-hosted, so no publishable key and no Stripe.js reach the browser — which is also why nothing here changes the web CSP.
Server-only. Stamps CFDI 4.0 documents at the SAT through FacturAPI’s PAC. Unsetting it is the clean stop: the facturación card hides and the 15-minute cfdi-scan no-ops, leaving the rest of billing untouched. Live mode additionally needs CSD certificates uploaded in the FacturAPI dashboard — a live key with no certificates stamps nothing.
SAT catalog codes (c_ClaveProdServ, c_ClaveUnidad, c_FormaPago), not secrets. The defaults are defensible; which code actually applies is the issuer’s fiscal call and their contador’s to confirm.
PII_ENCRYPTION_KEY encrypts the fiscal identity both of these integrations exchange — see Settings → Secrets, because it is the one secret in the repo that cannot be re-issued.
Canonical site origin used in OpenGraph tags + sitemap and the base of the web’s Stripe return URLs. Also read by apps/api and apps/worker to absolutize billing-email and account-deleted-email CTAs — unset in a deployed tier, those degrade to relative paths silently — and by apps/api to build the native apps’ Stripe return URLs (/billing/return?app=…, PRO-89): with it unset in production, billing.checkout / billing.portalSession refuse with stripe_unavailable; in dev they fall back to http://localhost:5173.
Doppler project kottia-com, branch config dev_local, injected by doppler run -- (see Local setup). Its data-store URLs point at the deployed DEV tier (Postgres through a Railway TCP proxy). .env.local (gitignored) is only the fallback for a machine without a Doppler token.
Local container stack
Doppler branch config dev_docker (loopback wiring + the third-party dev keys) plus the gitignored per-workspace deploy/local/.env (ports, generated secrets). bun run local exec -- … exports the workspace wiring and preserves it through doppler run -c dev_docker; bun run local doctor validates the key names. See Local environment (Compose).
Dev (deployed)
Railway project kottia.com, environment development. Variables on svelte-web / api / worker are synced from Doppler (dev_web / dev_api / dev_worker, all inheriting dev), imgproxy from kottia-infra — see Secrets; internal wiring stays a Railway service reference. Declared Docker ARGs receive matching service variables during builds, including required PUBLIC_API_URL. Mobile builds point at https://api.dev.useast.kottia.com.
Staging + Production
Doppler root configs stg / prd (same key set as dev, skeletons in place), delivered to Cloud Run on GCP us-central1 through the Doppler → Secret Manager sync. Own vendor key sets per tier, SENTRY_ENVIRONMENT=staging / production, QUEUE_SUFFIX=-stg on staging and empty on production, no BULL_BOARD_* on production. Decided, not provisioned yet — see Production landscape.
See Settings → Secrets for the policy on how secrets are stored and rotated.