Application Runtime Contract
This document defines the authoritative, provider-neutral runtime contract for the wedding website application. Any supported hosting infrastructure—including Docker containers, cloud container services (e.g., Google Cloud Run, AWS App Runner/ECS, Azure Container Apps), serverless hosting (e.g., Vercel), static showcase CDNs, or bare-metal/VM local production environments—must satisfy the specifications described here.
1. Node.js & Next.js Standalone Runtime
- Target Architecture: Dual-mode Next.js App Router configuration in
next.config.ts:- Standalone Server Mode (Default): Configured with
output: 'standalone'whenSTATIC_EXPORTis unset or false, producing a self-contained Node.js server bundle at.next/standalone/server.js(packaged at/app/server.jsin OCI containers). - Static Showcase Export Mode (
STATIC_EXPORT): SettingSTATIC_EXPORT=trueorSTATIC_EXPORT=1—or runningnpm run build:export(scripts/build-export.mjs)—switchesnext.config.tstooutput: 'export'withdistDir: '.next-export',trailingSlash: true,images.unoptimized: true, and optional subpath routing viaNEXT_PUBLIC_BASE_PATH(basePath,assetPrefix, and client/showcase URL resolution viawithBasePathandresolveShowcasePathinsrc/lib/basePath.ts).scripts/build-export.mjsstages build inputs withoutsrc/app/api(and withoutpublic/uploadsorpublic/mockServiceWorker.js) inside.next/export-stage, compiles withturbopack.rootpinned to the repository root, persists the export build cache in.next-export/cache, moves the generatedout/directory to the repository root without modifyingsrc/app/apior.next/standalone, and cleans up.next/export-stageautomatically on exit orSIGINT/SIGTERM/SIGHUPwhilesrc/lib/config.tsand feature repositories render pages against deterministic static seed data frombuildArchetypeSeedDatainsrc/lib/sampleData/builder.tswithout requiring PostgreSQL connectivity.- Interactive Browser Demo Runtime: In static exports (
isStaticExport),RootLayoutClientinsrc/components/layout/RootLayoutClient.tsxinitializesensureStaticDemoRuntime(src/lib/staticDemo/runtime.ts), enablesDemoProvider(src/components/demo/DemoContext.tsx), and rendersDemoToolbar(src/components/demo/DemoToolbar.tsx) with subpath-safe showcase return links (/,/api/,/storybook/).DemoProviderhydrates visitor persona, wedding archetype, theme preset, and dataset mutations fromlocalStorage(wedding_showcase_demo_v1) viahydrateDemoStateFromStorageinsrc/lib/demo/demoStore.tsand intercepts same-origin/api/*and/api/admin/*requests in-browser viainstallDemoFetchInterceptorinsrc/lib/demo/demoApiHandler.ts. Registry cash-fund previews use non-charging test cards viaSimulatedCardCheckoutandSIMULATED_TEST_CARDSinsrc/features/registry/components/SimulatedCardCheckout.tsx, andAdminSetupPageinsrc/app/admin/setup/page.tsxrenders<SetupWizard />directly at/admin/setupwithout server headers or database queries.
- Interactive Browser Demo Runtime: In static exports (
- Standalone Server Mode (Default): Configured with
- Node.js & Package Manager Requirement: Node.js v22.x LTS runtime (
>=22.22.1 <23.0.0acrossengines.nodeanddevEngines.runtime) andnpm^10.9.0(npm@10.9.x), pinned via.nvmrc,.npmrc, and bothenginesanddevEngines(onFail: "error") inpackage.json. - OCI Container Support:
- The official
Dockerfilecompiles build stages onnode:22-bookworm-slim(pinned by@sha256digest, configuringupdate-notifier=falsein/usr/local/etc/npmrcand a lockfile-pinned/opt/prisma-cli) and produces a multi-platformrunnerOCI image ondebian:bookworm-slim(pinned by@sha256digest) containing only the stripped Node.jsv22/usr/local/bin/nodebinary (openssl,ca-certificates,tini,libstdc++6, and zeronpm/npx/corepack/yarn), offline/usr/local/bin/prisma(symlinked at/app/node_modules/.bin/prisma),tiniinstalled as PID 1 (ENTRYPOINT ["/usr/bin/tini", "-s", "--", "docker-entrypoint.sh"]), setuid/setgid bits stripped across the root filesystem, and a built-in/api/liveHEALTHCHECK. - The isolated Prisma CLI is installed outside
/appat/opt/prisma-cli(owned byroot:root, invoked through/usr/local/bin/prismaand symlinked at/app/node_modules/.bin/prisma) alongside/usr/local/bin/docker-entrypoint.sh(root:root). Under/app, only the Next.js standalone server output (server.jsand tracednode_modules),.next/static,public,prisma,prisma.config.ts,src/lib/postgres-url.js, and/app/scripts/generate-password-hash.mjs(scripts/generate-password-hash.mjs, not the entire repositoryscripts/directory) are packaged and owned byroot:rootso the non-root runtime user (nextjs:nodejs, UID/GID 1001) holds write access to zero static code paths (only runtime cache/upload mountpoints/app/.next/cacheand/app/public/uploadsare owned bynextjs:nodejs).
- The official
2. Network Interface, Listening Port & Host Binding
- Listening Port & Host Interface:
- Listening port is configured via the
PORTenvironment variable (defaults to3000). - Host interface binding is configured via the
HOSTNAMEenvironment variable (ENV HOSTNAME="0.0.0.0"inDockerfileandHOSTNAME: "0.0.0.0"indocker-compose.yml), ensuring the standaloneserver.jsbinds to all available network interfaces (0.0.0.0) rather than a container-internal hostname.
- Listening port is configured via the
- Protocol: HTTP/1.1 or HTTP/2 unencrypted traffic internally, expecting TLS termination at the ingress/reverse-proxy layer.
3. Database Specification & PostgreSQL Policy
- Engine: PostgreSQL version 15.0 or higher (tested with PostgreSQL 15-alpine and Neon serverless Postgres).
- Driver / ORM & Singleton Pool: Prisma ORM with
@prisma/adapter-pgbacked by a process-wide singletonpg.Poolcached onglobalThisviaglobalForPrisma(GlobalPrismaStateprismaandpgPoolproperties insrc/lib/prisma.ts) so SSR, API Route Handlers, hot reloads, and shutdown hooks share one connection pool. Pool parameters are constructed viabuildPostgresRuntimeConfig(src/lib/postgresPool.ts), defaultingconnectionTimeoutMillisto10000ms(10s, overridable in seconds via?connect_timeout=or?pool_timeout=fromDEFAULT_POSTGRES_CONNECTION_TIMEOUT_MSinsrc/lib/postgres-url.js),query_timeoutto10000ms(10s, overridable in seconds via?socket_timeout=fromDEFAULT_POSTGRES_QUERY_TIMEOUT_MSinsrc/lib/prisma.ts), andmaxto5(overridable via?connection_limit=). Custom?schema=identifiers are validated against/^[A-Za-z_][A-Za-z0-9_$]*$/(1–63 UTF-8 bytes), double-quoted across/api/ready,AuthLockout, and all raw SQL queries (qualifyPostgresTable), and set via-c search_pathon direct non-pooledpg.Poolconnections while omitting startupoptionson PgBouncer/transaction poolers (isPooledPostgresUrl); TLS modes (disable,allow,prefer,require,no-verify,verify-ca,verify-full) follow standard PostgreSQLlibpqsemantics. - Connection Strings:
DATABASE_URL: Primary connection string bound todatasource.urlviaresolvePrismaDatasourceUrl(normalized for Prisma CLI viarewritePostgresUrlForPrismaCli) inprisma.config.ts. Used for Next.js runtime operations (supporting PgBouncer, Neon Connection Pooling, Supabase Pooler, or direct TCP) and Prisma CLI commands. WhenDATABASE_URLroutes through a transaction-mode connection pooler (isPooledPostgresUrl) andPOSTGRES_URL_NON_POOLINGis an unpooled PostgreSQL URI targeting the same database and schema,resolvePrismaDatasourceUrlinprisma.config.tspromotesPOSTGRES_URL_NON_POOLINGasdatasource.urlsoprisma migrate deploy,status, andresolvecan acquire advisory locks directly (or operators can pass an explicitDATABASE_URLoverride), andverifyPostgresTlsHandshake(src/lib/postgres-url.js) validates libpq TLS certificates on the effective migration endpoint (resolveDirectMigrationPostgresUrl) beforeprisma migrateruns indocker-entrypoint.sh,scripts/preflight-migration-summary.ts, anddb-migrate.yml.POSTGRES_URL_NON_POOLING(Optional): Direct, non-pooled connection URL inspected byresolvePrismaDatasourceUrlandresolvePrismaShadowDatabaseUrlinprisma.config.ts. WhenDATABASE_URLis pooled andPOSTGRES_URL_NON_POOLINGis unpooled for the same database and schema,prisma.config.tspromotes it asdatasource.urlfor migrations while keepingdatasource.shadowDatabaseUrlundefinedoutsideprisma migrate dev,reset, anddiff(preventing PrismaP3025collisions); whenPOSTGRES_URL_NON_POOLINGpoints to a separate shadow database duringmigrate dev/reset/diff,resolvePrismaShadowDatabaseUrlbinds it todatasource.shadowDatabaseUrl.
- Provider Neutrality: No database-vendor specific features or proprietary extensions are required. Standard relational PostgreSQL features (tables, foreign keys, indexes, JSONB) are used.
Persisted Entities, Full-Site Backups & Multi-Site Isolation (prisma/schema.prisma)
- Persisted Relational Entities:
prisma/schema.prismadefines the authoritative relational data model persisted in PostgreSQL:- Configuration & Content:
AppConfig,ContentNode,SnapshotVersion,Media - Celebration Roster & Venue Logistics:
WeddingPartyMember,Attraction,SeatingTable - Guest Access, Events & RSVPs:
InvitationCode,SubEvent,SubEventAccess,SubEventRsvp HouseholdMember— Relational individual household member profile (PRIMARY,PARTNER,CHILD,PLUS_ONE) linked toInvitationCodeand optionalSeatingTable.SubEventMemberRsvp— Per-member sub-event RSVP attendance, meal option, and dietary notes linked toSubEventRsvpandHouseholdMember.- Gift Registry & Contributions:
RegistryItem,ExternalRegistry,Contributor - Communications:
BroadcastMessage,BroadcastRecipient - Security & Rate Limiting:
AuthLockout(ephemeral HMAC-SHA256 hashed IP brute-force lockout counters)
- Configuration & Content:
- Full-Site Backup & Restore Coverage: Administrative maintenance backups (
/api/admin/maintenance/exportand/api/admin/maintenance/import) export and restore all 18 domainprisma/schema.prismamodels (excluding ephemeralAuthLockoutcounters) so operators can migrate or snapshot an entire wedding deployment without vendor lock-in. - Multi-Site Subdomain Scope (
MULTISITE_ENABLED): EnablingMULTISITE_ENABLED=trueroutes subdomain requests (X-Forwarded-Hostchecked beforeHostinsrc/lib/config.ts) to subdomain-specificAppConfigbranding/profile rows only. All other persisted models inprisma/schema.prismaare shared across subdomains without tenant row isolation.
4. Environment Variable Matrix
All operator-facing configuration across application runtime (src/env.ts, src/lib/config.ts), Next.js and VitePress build pipelines (next.config.ts, scripts/build-export.mjs, docs-portal/.vitepress/config.mts), and container orchestration (Dockerfile, docker-compose.yml, docker-compose.rollout.yml) is supplied via environment variables. Core runtime variables are validated at startup by src/env.ts (Zod schema). Internal framework and test-runner flags (NEXT_RUNTIME, npm_lifecycle_event, and JEST_WORKER_ID) are managed automatically by Next.js, npm, and Jest rather than configured by operators.
Mandatory Runtime Variables
| Variable | Default Value | Description & Validation Requirements |
|---|---|---|
DATABASE_URL | None | Primary PostgreSQL connection URL (datasource.url in prisma.config.ts). Must be a valid postgresql:// or postgres:// connection string. |
ADMIN_PASSWORD | None | Scrypt hash for admin authentication. Must match format scrypt:[16-byte saltBase64]:[64-byte keyBase64] (generated via scripts/generate-password-hash.mjs); plaintext passwords, non-64-byte hashes, and ALWAYS_BLOCKED_PROD_ADMIN_HASHES placeholders are rejected, E2E_FALLBACK_ADMIN_HASHES are blocked in production unless E2E_TEST=true, and src/core/auth/auth.server.ts derives a domain-separated HMAC signing key from the decoded hash bytes. |
Production-Required Variables
These variables provide convenience defaults for local development and test modes in src/env.ts, but startup validation strictly requires unique, non-default values when NODE_ENV=production (Security Note: setting E2E_TEST=true under NODE_ENV=production disables the E2E_FALLBACK_ADMIN_HASHES, E2E_FALLBACK_GUEST_PASSCODES, and E2E_FALLBACK_SESSION_SECRETS blocklists in src/env.ts for disposable container smoke tests while keeping ALWAYS_BLOCKED_PROD_ADMIN_HASHES, ALWAYS_BLOCKED_PROD_GUEST_PASSCODES, and ALWAYS_BLOCKED_PROD_SESSION_SECRETS enforced—never set E2E_TEST=true in real production deployments):
| Variable | Dev / Test Default | Production Requirements & Description |
|---|---|---|
GUEST_PASSCODE | wedding2026 | Global passcode required for guest website access. Required in production (must not be empty or match ALWAYS_BLOCKED_PROD_GUEST_PASSCODES such as wedding2026 or template placeholders; E2E_FALLBACK_GUEST_PASSCODES are also rejected unless E2E_TEST=true). |
GUEST_SESSION_SECRET | default-guest-session-secret | Dedicated server secret for signing and verifying guest invitation session tokens (HMAC-SHA256). Required in production; must be at least 32 characters long, distinct from GUEST_PASSCODE, and must not match ALWAYS_BLOCKED_PROD_SESSION_SECRETS (default-guest-session-secret or template placeholders; E2E_FALLBACK_SESSION_SECRETS are also rejected unless E2E_TEST=true). |
Security Warning (E2E_TEST): Setting E2E_TEST=true (src/env.ts, isE2ETestMode) disables NODE_ENV=production blocklists for the repository's committed E2E_FALLBACK_ADMIN_HASHES, E2E_FALLBACK_GUEST_PASSCODES, and E2E_FALLBACK_SESSION_SECRETS (while ALWAYS_BLOCKED_PROD_ADMIN_HASHES, ALWAYS_BLOCKED_PROD_GUEST_PASSCODES, and ALWAYS_BLOCKED_PROD_SESSION_SECRETS remain rejected). Never enable E2E_TEST=true in real production deployments.
Optional Infrastructure & Feature Variables
| Variable | Default Value | Description |
|---|---|---|
NODE_ENV | development | Runtime mode (production, development, test). Automatically set to production in Dockerfile runner environments. |
ALLOWED_HOSTS | localhost,127.0.0.1,*.localhost | Comma-separated list of whitelisted host domains or wildcard patterns validated against X-Forwarded-Host / Host in src/middleware.ts. Defaults to loopback hosts; production deployments serving custom domains must explicitly include their public hostnames (e.g., localhost,127.0.0.1,wedding.example,*.wedding.example). |
POSTGRES_URL_NON_POOLING | None | Direct non-pooled connection string read by prisma.config.ts (resolvePrismaDatasourceUrl promotes it when DATABASE_URL uses PgBouncer for the same database and schema, and resolvePrismaShadowDatabaseUrl binds it during prisma migrate dev/reset/diff when targeting a separate shadow database). |
MULTISITE_ENABLED | false | Enable subdomain-based AppConfig branding/profile routing (src/lib/config.ts resolves host via TRUST_PROXY-gated resolveRequestSubdomain) and tenant claim enforcement (siteId and subdomain) across admin_auth, guest_auth, guest_invite_session, and guest_photo_session cookies. Switches AppConfig rows only; all other persisted models in prisma/schema.prisma are shared across subdomains without tenant row isolation. |
RUN_MIGRATIONS | false | Automatically run database schema migrations (./node_modules/.bin/prisma migrate deploy) during container startup in docker-entrypoint.sh when set to true or 1 (both docker-entrypoint.sh and src/env.ts accept RUN_MIGRATIONS=true and RUN_MIGRATIONS=1). |
TRUST_PROXY | false | Opt-in boolean (true/false) or non-negative integer hop count enabling trusted hop selection on X-Forwarded-Host, X-Forwarded-Proto, X-Forwarded-For, and X-Real-IP behind reverse proxies. |
HISTORY_VERSION_LIMIT | 50 | Maximum version history entries retained per content item (integer >= 1). |
CRON_SECRET | None | Bearer authorization secret for triggering scheduled background endpoints (/api/cron/*). |
Optional Object Storage Variables (S3-Compatible)
When storing uploaded media assets externally, all four core S3 credential variables must be supplied together as a coherent group:
| Variable | Requirement | Default Value | Description |
|---|---|---|---|
S3_BUCKET | Required if using S3 | None | Target S3/R2 bucket name. |
S3_REGION | Required if using S3 | None | S3 region (e.g., us-east-1 or auto for Cloudflare R2; S3_REGION=auto requires S3_ENDPOINT). |
S3_ACCESS_KEY_ID | Required if using S3 | None | AWS/S3 API access key ID. |
S3_SECRET_ACCESS_KEY | Required if using S3 | None | AWS/S3 API secret access key. |
S3_ENDPOINT | Required when S3_REGION=auto; Optional otherwise | None | Custom S3 API endpoint URL (e.g., https://<account_id>.r2.cloudflarestorage.com, https://storage.googleapis.com, or MinIO). |
S3_PUBLIC_URL | Required when S3_ENDPOINT targets *.r2.cloudflarestorage.com; Optional otherwise | None | Custom CDN, R2 Custom Domain, or public https://pub-<id>.r2.dev asset delivery URL prefix. |
Note: Supplying partial core S3 credentials—or configuring Cloudflare R2 with S3_REGION=auto without S3_ENDPOINT or a private *.r2.cloudflarestorage.com endpoint without S3_PUBLIC_URL—will cause startup and build-time environment validation to fail.
Optional Stripe Card Checkout Variables
When enabling online credit card and digital wallet processing for cash and experience funds, STRIPE_SECRET_KEY and NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY must be supplied together as a pair (or both omitted for direct-transfer-only registries):
| Variable | Requirement | Default Value | Description |
|---|---|---|---|
STRIPE_SECRET_KEY | Required if using Stripe card checkout | None | Server-side Stripe API secret key (sk_... or rk_...). Placeholder mock keys are rejected in non-test environments. |
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY | Required if using Stripe card checkout | None | Client-side Stripe publishable key (pk_...) used by Stripe Elements. Placeholder mock keys are rejected in non-test environments. |
STRIPE_WEBHOOK_SECRET | Optional (recommended if using Stripe webhooks) | None | Endpoint signing secret (whsec_...) used to verify incoming /api/registry/webhook/stripe events. |
Note: Supplying only one of STRIPE_SECRET_KEY or NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY will cause startup environment validation to fail fast.
Optional Server, Build, Portal & Container Variables
These variables configure container port binding, static HTML export builds, VitePress documentation portal asset paths, Docker Compose PostgreSQL service interpolation, and E2E setup bypasses:
| Variable | Default Value | Scope | Description |
|---|---|---|---|
PORT | 3000 | Container / Standalone Server | HTTP listening port (ENV PORT=3000 in Dockerfile; 127.0.0.1:${PORT:-3000}:3000 in docker-compose.yml). |
HOSTNAME | 0.0.0.0 | Container / Standalone Server | Network interface address bound by standalone server.js (ENV HOSTNAME="0.0.0.0" in Dockerfile; HOSTNAME: "0.0.0.0" in docker-compose.yml). |
NEXT_PHASE | None | Build (src/env.ts) | Next.js build phase identifier (phase-production-build) set automatically during next build so build-time schema checks allow template placeholders before runtime secret enforcement. |
STATIC_EXPORT | None | Build (next.config.ts, scripts/build-export.mjs, src/) | Switches Next.js to static HTML export (output: 'export') and STATIC_MOCK_CONFIG data when set to 'true' or '1'. |
NEXT_PUBLIC_BASE_PATH | None | Static Export Build & Client Runtime (next.config.ts, src/lib/basePath.ts) | Optional URL subpath prefix (basePath, assetPrefix, and root-relative client API, redirect, download, and asset URL resolution via withBasePath) when serving under a subpath and value is not '/'. |
VITEPRESS_BASE | / | Docs Portal (docs-portal/.vitepress/config.mts) | Base URL path for building and serving the VitePress documentation portal. |
E2E_TEST | false (docker-compose.yml) | Runtime / Compose (src/env.ts, src/lib/config.ts, docker-compose.yml) | Defaults to false in docker-compose.yml so <SetupWizard /> onboarding and full production credential blocklists stay active; setting E2E_TEST=true bypasses <SetupWizard /> in src/lib/config.ts and disables NODE_ENV=production blocklists for committed E2E_FALLBACK_* credentials in src/env.ts. Restrict strictly to .env.ci, docker-compose.ci.yml, and automated E2E harnesses—never enable in production. |
CONTAINER_DATABASE_URL | None | Docker Compose (docker-compose.yml, docker-compose.rollout.yml) | Explicit PostgreSQL connection URL override (${CONTAINER_DATABASE_URL:-...}) for migration, app, and app-standby containers (e.g., external managed PostgreSQL) so host DATABASE_URL (@localhost:5432) never leaks into container networking. |
CONTAINER_POSTGRES_URL_NON_POOLING | None | Docker Compose (docker-compose.yml, docker-compose.rollout.yml) | Optional direct non-pooling PostgreSQL connection URL override (${CONTAINER_POSTGRES_URL_NON_POOLING:-}) forwarded as POSTGRES_URL_NON_POOLING into migration, app, and app-standby containers when CONTAINER_DATABASE_URL uses PgBouncer, preventing host POSTGRES_URL_NON_POOLING (@localhost:5432/wedding_shadow) from leaking into containers. |
DB_USER | wedding | Docker Compose (docker-compose.yml) | PostgreSQL username interpolated into the db container (POSTGRES_USER) and fallback migration/app CONTAINER_DATABASE_URL default. |
DB_PASSWORD | None | Docker Compose (docker-compose.yml) | Mandatory PostgreSQL password (${DB_PASSWORD:?...}) interpolated into the db container (POSTGRES_PASSWORD) and fallback migration/app CONTAINER_DATABASE_URL default (.env.example and .env.ci supply wedding123 for local and CI runs). |
DB_NAME | wedding | Docker Compose (docker-compose.yml) | PostgreSQL database name interpolated into the db container (POSTGRES_DB) and fallback migration/app CONTAINER_DATABASE_URL default. |
DB_PORT | 5432 | Docker Compose (docker-compose.yml) | Loopback host TCP port published to container port 5432 for the db service (127.0.0.1:${DB_PORT:-5432}:5432). |
STANDBY_PORT | 3001 | Docker Compose Rollout (docker-compose.rollout.yml, scripts/rollout-vps.sh) | Loopback host TCP port published to container port 3000 for the temporary app-standby service during zero-downtime VPS rollouts (127.0.0.1:${STANDBY_PORT:-3001}:3000). |
Optional Site Configuration Overrides (SITE_*)
src/lib/config.ts (getEnvConfigOverrides, readNonEmptySiteEnv, and getAppConfig) supports 32 optional Layer 1 environment variable overrides that take precedence over database AppConfig rows and APP_DEFAULTS. Both docker-compose.yml (app) and docker-compose.rollout.yml (app-standby) forward all 32 SITE_* keys from the host environment (${SITE_*:-}), and readNonEmptySiteEnv trims leading/trailing whitespace via .trim() while treating empty or whitespace-only strings as unset (undefined) before validation and isSiteInitialized checks (whereas non-empty malformed overrides fail AppConfigSchema / coordinateSchema validation at runtime, throwing Production Configuration Validation Failure in NODE_ENV=production):
| Variable | Default Value | Target AppConfig Field | Description |
|---|---|---|---|
SITE_PARTNER1_NAME | None | partner1Name, brideName | Override Partner 1 display name and synchronize legacy brideName (when non-empty). |
SITE_PARTNER2_NAME | None | partner2Name, groomName | Override Partner 2 display name and synchronize legacy groomName (when non-empty). |
SITE_BRIDE_NAME | None | brideName, partner1Name | Legacy alias overriding both brideName and partner1Name (when non-empty). |
SITE_GROOM_NAME | None | groomName, partner2Name | Legacy alias overriding both groomName and partner2Name (when non-empty). |
SITE_WEDDING_DATE | None | weddingDate | ISO 8601 date/timestamp string trimmed via readNonEmptySiteEnv and parsed via new Date(...) when non-empty (blank/whitespace values are ignored; non-empty invalid date strings fail AppConfigSchema validation). |
SITE_BASE_URL | None | baseUrl | Canonical public base URL of the wedding website. |
SITE_VENUE_NAME | None | venueName | Primary wedding venue name (when non-empty). |
SITE_VENUE_ADDRESS | None | venueAddress | Street address of the primary venue. |
SITE_VENUE_CITY | None | venueCity | City of the primary venue. |
SITE_VENUE_STATE | None | venueState | State/province of the primary venue. |
SITE_VENUE_ZIP | None | venueZip | Postal/ZIP code of the primary venue. |
SITE_LATITUDE | None | latitude | Venue latitude coordinate trimmed via readNonEmptySiteEnv and parsed via parseFloat(...) when non-empty (blank/whitespace values are ignored; non-empty non-numeric or out-of-range values fail coordinateSchema validation). |
SITE_LONGITUDE | None | longitude | Venue longitude coordinate trimmed via readNonEmptySiteEnv and parsed via parseFloat(...) when non-empty (blank/whitespace values are ignored; non-empty non-numeric or out-of-range values fail coordinateSchema validation). |
SITE_TIMEZONE | None | timezone | IANA timezone identifier for event schedules (e.g., America/Chicago). |
SITE_COLOR_PRIMARY | None | colorPrimary | Primary brand hex color token (when non-empty). |
SITE_COLOR_SECONDARY | None | colorSecondary | Secondary accent hex color token (when non-empty). |
SITE_THEME_PRESET | None | themePreset | Active theme preset identifier (e.g., classic). |
SITE_THEME_TOKENS | None | themeTokens | JSON-encoded map of custom CSS design token overrides (malformed JSON is ignored). |
SITE_SHOW_COUNTDOWN | None | showCountdown | Boolean string ('true' / 'false', case-insensitive) toggling the homepage countdown widget. |
SITE_SHOW_ADD_TO_CALENDAR | None | showAddToCalendar | Boolean string ('true' / 'false', case-insensitive) toggling the homepage Add-to-Calendar widget. |
SITE_SEO_TITLE | None | seoTitle | Custom HTML <title> / Open Graph title override. |
SITE_SEO_DESCRIPTION | None | seoDescription | Custom meta / Open Graph description override. |
SITE_BRAND_MONOGRAM | None | brandMonogram | Couple monogram text displayed in branding elements. |
SITE_BRAND_LOGO_URL | None | brandLogoUrl | URL or asset path for the custom brand logo image. |
SITE_BRAND_LOGO_ALT | None | brandLogoAlt | Accessible alt text for the custom brand logo image. |
SITE_HERO_IMAGE_URL | None | heroImageUrl | URL or asset path for the homepage hero image. |
SITE_HERO_IMAGE_ALT | None | heroImageAlt | Accessible alt text for the homepage hero image. |
SITE_BRAND_WATERMARK_URL | None | brandWatermarkUrl | URL or asset path for the decorative brand watermark graphic. |
SITE_BRAND_WATERMARK_ALT | None | brandWatermarkAlt | Accessible alt text for the decorative brand watermark graphic. |
SITE_BADGE_GRAPHIC_URL | None | badgeGraphicUrl | URL or asset path for the custom badge graphic. |
SITE_BADGE_GRAPHIC_ALT | None | badgeGraphicAlt | Accessible alt text for the custom badge graphic. |
SITE_CONTACT_EMAIL | None | contactEmail | Host contact email address displayed to guests. |
5. Statelessness & Filesystem Expectations
- Stateless Application Layer: The application process is fully stateless and ephemeral.
- Local Filesystem & Read-Only Root Execution: Scratch write operations to
/tmpor/app/.next/cache(for Next.js/_next/imageoptimization) are temporary and must not be relied upon across container restarts or horizontal scaling.docker-compose.yml(anddocker-compose.rollout.ymlforapp-standby) enforcesread_only: true,cap_drop: [ALL], andsecurity_opt: [no-new-privileges:true]on application and migration containers (NoNewPrivs: 1acrossdb,migration,app, andapp-standby),shm_size: "256mb"ondb, boundedjson-filelog rotation (max-size: "10m",max-file: "3"), explicitpids_limitandmem_limitcaps, and ephemeraltmpfsvolumes at/tmpand/app/.next/cache:uid=1001,gid=1001,mode=0755. - Data & Media Persistence:
- Application state, registry items, contributors, and content configurations are stored in PostgreSQL (
prisma/schema.prisma). - Uploaded media files are stored in S3-compatible object storage when
S3_*credentials are configured, or written to/app/public/uploadsviaLocalStorageProvider(src/utils/storage.ts) when backed by a persistent volume/disk (such asuploads_data:/app/public/uploadsindocker-compose.ymlor a Render Persistent Disk) and streamed dynamically at/uploads/*in standalone mode (next.config.tsserverrewrites()+src/app/api/uploads/[...path]/route.tswithX-Content-Type-Options: nosniff).
- Application state, registry items, contributors, and content configurations are stored in PostgreSQL (
6. Reverse Proxy & Forwarded Header Handling
The application expects to be deployed behind an HTTP reverse proxy, load balancer, or cloud ingress controller (e.g., NGINX, Cloudflare, Google Cloud Run Ingress, AWS ALB).
- Host Header Forwarding (
TRUST_PROXY):- Direct deployments (
TRUST_PROXY=false, the default) ignoreX-Forwarded-Hostand evaluate only theHostheader againstALLOWED_HOSTS. - Reverse proxies (e.g., Nginx with
proxy_set_header Host $host;andproxy_set_header X-Forwarded-Host $host;) must pair forwarded headers withTRUST_PROXY=1(orTRUST_PROXY=2behind two-hop load balancers). WhenTRUST_PROXYis enabled,resolveRequestHost(src/utils/hostValidation.ts) selects the configured right-to-left hop fromX-Forwarded-Hostbefore falling back toHost, andsrc/middleware.ts,src/lib/config.ts,src/app/metadata.ts, and export/broadcast origin helpers validate the resolved host againstALLOWED_HOSTS(rejecting invalid or unapproved hosts at the perimeter withHTTP 400 Bad Request).
- Direct deployments (
- Perimeter Session Exclusions:
- Public static exclusions in
src/middleware.tsare limited to explicit asset prefixes (/images/,/assets/,/fonts/,/_next/static/,/_next/image/,/favicon.ico, and/robots.txt). - Non-probe perimeter-exempt paths (
/api/registry/webhook/stripe,/api/cron/*, and/uploads/*) enforce fullALLOWED_HOSTSvalidation (isHostAllowed) insrc/middleware.tsbefore bypassing guest/admin session cookies in favor of route-specific controls (stripe-signatureverification viaSTRIPE_WEBHOOK_SECRET,Authorization: Bearer <CRON_SECRET>, or path-containednosniffmedia streaming). - Stateless read-only (
GETandHEAD) probe requests to/api/live,/api/health, and/api/readyenforce syntacticHostvalidation (isHostSyntaxValidinsrc/utils/hostValidation.ts) only, rejecting empty, whitespace, comma-separated, CRLF, or invalid-port headers while permitting platform probe hosts (e.g.,healthcheck.railway.app, Cloud Run internal pod/kubelet IPs, and127.0.0.1:3000). Non-read-only methods (such asPOST) on probe paths still enforce fullALLOWED_HOSTSvalidation.
- Public static exclusions in
- Protocol Header Forwarding (
TRUST_PROXY):- Proxies should forward
X-Forwarded-Proto(httpsorhttp);resolveRequestProtocolhonorsX-Forwarded-Protoonly whenTRUST_PROXYis enabled and ignores spoofed forwarded protocol headers whenTRUST_PROXY=false.
- Proxies should forward
- Client IP Header Forwarding (
TRUST_PROXY):- By default (
TRUST_PROXY=false), the rate limiter ignoresX-Forwarded-ForandX-Real-IPheaders so direct callers cannot spoof IP headers to bypass lockouts. SetTRUST_PROXY=1behind single-hop reverse proxies (Caddy, Nginx, Vercel, Railway, Render) orTRUST_PROXY=2behind two-hop load balancers such as Google Cloud Run (<client-ip>, <lb-ip>).
- By default (
7. HTTPS Assumptions & Security Policy
- Transport Security: Production deployments assume HTTPS termination at the reverse proxy/ingress layer.
- Security Headers (Standalone / Server Mode Only):
- Static Non-CSP Headers (
next.config.ts): When running in standalone/server mode (!isStaticExport),next.config.ts(headers()) injects static non-CSP security headers across all routes (/(.*)):Strict-Transport-Security: max-age=31536000; includeSubDomainsX-Frame-Options: SAMEORIGINX-Content-Type-Options: nosniffReferrer-Policy: strict-origin-when-cross-originPermissions-Policy: camera=(), microphone=(), geolocation=()
- Per-Request Nonced Application CSP (
src/middleware.ts&src/lib/csp.ts): On non-upload routes,src/middleware.tsgenerates a cryptographic base64 nonce (x-nonce/CSP_NONCE_HEADER) and emits a per-requestContent-Security-PolicyviabuildContentSecurityPolicy(src/lib/csp.ts)—replacing production'unsafe-inline'and'unsafe-eval'inscript-srcwith'nonce-<base64>','wasm-unsafe-eval', andblob:workers (allowing'unsafe-eval'only whenNODE_ENV === 'development'), enforcingobject-src 'none',base-uri 'self',form-action 'self', andframe-ancestors 'self', and scopingconnect-srcto'self',https://api.stripe.com,https://js.stripe.com,https://hooks.stripe.com,https://*.basemaps.cartocdn.com, and any configuredS3_PUBLIC_URLorigin (src/app/layout.tsxreadsx-nonceviaheaders()when!isStaticExportand passesnonceto the inline theme<script>). - Sandboxed Upload Stream CSP (
src/app/api/uploads/[...path]/route.ts):src/middleware.tsskips/uploads/*and/api/uploads/*when emitting the applicationContent-Security-Policysosrc/app/api/uploads/[...path]/route.tsemits a singleContent-Security-Policy: default-src 'none'; sandboxheader alongsideCross-Origin-Resource-Policy: same-origin(andContent-Disposition: attachmentfor fallbackapplication/octet-streampayloads).
- Static Non-CSP Headers (
- Static Export Header Caveat: Next.js
headers()and Edge Middleware are disabled whenSTATIC_EXPORTis'true'or'1'(output: 'export'). Operators serving static showcase builds must configure equivalentContent-Security-Policy(including'wasm-unsafe-eval',worker-src 'self' blob:, andblob:inscript-srcso/heartRapier WASM physics and 3D textblob:workers succeed),Permissions-Policy, HSTS, framing, MIME-sniffing, and referrer headers at their CDN, static host, or reverse-proxy layer.
8. Application Lifecycle & Probes
+------------------+ +----------------------------------+ +-----------------------+ +-----------------------+
| Build Phase | --> | Migration Phase | --> | Start Phase | --> | Liveness & Readiness |
| npm run build | | ./node_modules/.bin/prisma | | tini -> entrypoint -> | | GET /api/live |
| (or build:export)| | migrate deploy (offline in OCI) | | exec node server.js | | GET /api/health |
+------------------+ +----------------------------------+ +-----------------------+ | GET /api/ready |
+-----------------------+- Build Phase (
npm run build/npm run build:export):- Executes Prisma Client generation (
prisma generate), Next.js standalone compilation (output: 'standalone'), and standalone asset staging (postbuild), or static HTML export (output: 'export') vianpm run build:export(STATIC_EXPORT=true). - Does not require an active database connection. Safe for CI/CD build environments.
- Executes Prisma Client generation (
- Migration Phase (
/usr/local/bin/prisma migrate deploy/./node_modules/.bin/prisma migrate deploy):- Runs offline before application startup via the
migrationservice indocker-compose.yml(./node_modules/.bin/prisma migrate deploy), via Cloud Run Jobs or PaaS release hooks (/usr/local/bin/prisma migrate deploy), indocker-entrypoint.shwhenRUN_MIGRATIONS=trueorRUN_MIGRATIONS=1(normalizing and preserving non-emptyPOSTGRES_URL_NON_POOLING, unsetting blank values, and invoking/opt/prisma-clivia/usr/local/bin/prismasymlinked at/app/node_modules/.bin/prismawithNPM_CONFIG_UPDATE_NOTIFIER=falseandCHECKPOINT_DISABLE=1so zero npm registry calls occur), or via CI/CD release pipelines (.github/workflows/db-migrate.yml). - Applies pending database migrations safely without data loss.
- Runs offline before application startup via the
- Start Phase (
tini->docker-entrypoint.sh->node server.js):/usr/bin/tini -sruns as PID 1 (or subreaper underinit: true) and invokesdocker-entrypoint.sh, which validatesDATABASE_URLand hands off viaexec "$@"(exec node server.js), launching the Next.js standalone HTTP server onPORT(0.0.0.0) and validatingsrc/env.ts.
- Liveness, Startup, & Readiness Probes:
- Liveness Endpoint (
GET /api/live,src/app/api/live/route.ts):- Direct Next.js Route Handler returning
HTTP 200 OKwith{ "status": "alive", "timestamp": "..." }andCache-Control: no-storewithout querying PostgreSQL. - Exempted from guest/admin session checks (
src/middleware.ts), invite revocation checks (src/utils/withApiMiddleware.ts), and API rate limits (src/utils/withApiMiddleware.ts,src/utils/rateLimit.ts). - Targeted by the
DockerfileHEALTHCHECK,docker-compose.ymlapphealthcheck, and Google Cloud Run--liveness-probe=httpGet.path=/api/live,httpGet.port=3000,periodSeconds=30(or KnativelivenessProbe) so transient database blips never trigger container restart loops.
- Direct Next.js Route Handler returning
- Startup & Rollout Health Endpoint (
GET /api/health,src/app/api/health/route.ts):- Wrapped in
withApiMiddleware(isHealthProbe: trueinsrc/utils/withApiMiddleware.ts), executesSELECT 1via Prisma, and returnsHTTP 200 OKwithCache-Control: no-storeand wrapped JSON{ "success": true, "data": { "status": "ok", "timestamp": "...", "database": "connected" } }when PostgreSQL is reachable. - When PostgreSQL is unreachable,
GET /api/healthreturnsHTTP 503 Service UnavailablewithCache-Control: no-store, andwithApiMiddleware(isHealthProbe: true) preserves diagnostic probe fields{ "success": false, "status": "degraded", "database": "disconnected", "timestamp": "...", "error": "Database connection failed" }(sanitizing error text inNODE_ENV=productionso internal driver details never leak). - Used by Cloud Run Knative
startupProbe(httpGet.path: /api/health,port: 3000), Railway deploy healthchecks (/api/healthwithHost: healthcheck.railway.app), and CI/CD post-deployment/rollback verification alongside/api/ready(.github/workflows/deploy-stage.ymland.github/workflows/rollback.yml). - Exempted from guest/admin session checks in
src/middleware.ts(normalizedPath === '/api/health') and exempted from API rate limiting insrc/utils/withApiMiddleware.ts(isHealthPath).
- Wrapped in
- Readiness Endpoint (
GET /api/ready,src/app/api/ready/route.ts):- Direct Next.js Route Handler (not wrapped by
withApiMiddleware, settingCache-Control: no-store) backed by the zero-I/O manifest insrc/lib/readinessManifest.ts(scripts/check-prisma-schema.tsenforces compile-time parity) that verifies all 16 persistedprisma/schema.prismatables (AppConfig,Media,WeddingPartyMember,Attraction,RegistryItem,Contributor,InvitationCode,SeatingTable,ContentNode,SnapshotVersion,SubEvent,SubEventAccess,SubEventRsvp,BroadcastMessage,BroadcastRecipient,AuthLockout) exist incurrent_schema()viainformation_schema.tablesand—when_prisma_migrationsis present—confirms all 47 committed migrations inREQUIRED_MIGRATION_NAMEScompleted with zero failed or unfinished entries (finished_at IS NULL AND rolled_back_at IS NULL) while allowing extra forwardN+1migrations duringN-1rollbacks. When_prisma_migrationsis absent (for example afterprisma db pushinplaywright.config.ts),/api/readysucceeds as soon as all 16 schema tables exist. - Never calls
isSiteInitialized(src/lib/config.ts) and never requires rows inAppConfig, returningHTTP 200 OKwithCache-Control: no-storeand unwrapped JSON{ "status": "ready", "database": "connected", "timestamp": "..." }on unseeded migrated databases so first-run<SetupWizard />onboarding (src/app/layout.tsx) and pre-seed container boot succeed. - Returns
HTTP 503 Service UnavailablewithCache-Control: no-storeand{ "status": "unhealthy", "database": "connected", "error": "Database schema is not ready", "timestamp": "..." }on zero-table databases, any missing schema table, any missing required migration, or failed migrations, or{ "status": "unhealthy", "database": "disconnected", "error": "Database connection failed", "timestamp": "..." }on database connection failures (internal table, migration, and driver details are masked whenNODE_ENV=production). - Exempted from guest/admin session checks in
src/middleware.ts(normalizedPath === '/api/ready') and not subject towithApiMiddlewarerate-limit buckets (enforcing its own100req /60sIP burst limit and5ssingle-flight healthy memoization).
- Direct Next.js Route Handler (not wrapped by
- Perimeter Host Validation: Read-only (
GETandHEAD) requests to/api/live,/api/health, and/api/readyvalidateHostheader syntax (isHostSyntaxValidinsrc/utils/hostValidation.ts) without requiringALLOWED_HOSTSmembership, allowing PaaS and container orchestrator probes (such ashealthcheck.railway.app,169.254.1.1:3000, and loopback127.0.0.1:3000) while still rejecting malformed or CRLF-injectedHostheaders withHTTP 400. Non-read-only methods on probe routes and all non-probe routes enforce fullALLOWED_HOSTSchecks (isHostAllowed).
- Liveness Endpoint (
- Process Shutdown, Pool Draining & Signal Delivery:
Dockerfileruns/usr/bin/tini -sas PID 1 (anddocker-compose.ymlsetsinit: trueandstop_grace_period: 15sonapp; standalonedocker rundeployments should pass--init --stop-timeout 15) whiledocker-entrypoint.shhands off viaexec "$@"soSIGTERMandSIGINTpropagate cleanly tonode server.jsand orphaned child processes are reaped.src/lib/prisma.tscachesglobalForPrisma.prismaandglobalForPrisma.pgPoolonglobalThisacross all module graphs in every environment and registers idempotentSIGTERMandSIGINThooks (registerPrismaShutdownHooks()): when framework signal listeners (such as Next.js standalonestart-server.js) are attached,interceptProcessExitUntilDrained()wrapsprocess.exitwith an unref'd5000msdrain safety timer so HTTP listeners finish in-flight requests beforeshutdownPrisma()runsprisma.$disconnect()andpool.end(); when no framework listener is attached,handleTerminationSignalrunsshutdownPrisma()directly under a5000mssafety timer and exits with code130(SIGINT) or143(SIGTERM), transmitting PostgreSQLTerminate(0x58) frames well within the15scontainer stop grace window.