Home Bento Dynamic Backend Architecture
Internal architecture of the home bento feature across backend seed, storefront and admin — composition, data model, invariants, and configuration.
Module Scope
The feature adds no backend runtime code. The backend contribution is the placement seed. The work is in the storefront (parser, data mapping, card rendering, tracking) and the admin (placement, assignment and analytics screens).
It owns:
- Seven placement rows,
home_bento_1..7, and the seed that creates them. - The storefront mapping from placement to bento card, with per-card fallback.
- The storefront guards for operator-authored links, images and colours.
- The admin changes that make those placements operable.
It does not own:
- Banner, campaign and placement tables, serving, targeting, and tracking ingest. See Banners Backend.
- Any schema, migration, endpoint, DTO or error code change.
- Serve-cache invalidation on admin writes.
Composition
Backend (Nano-store-backend)
| File | Role |
|---|---|
packages/db/src/seed/placement-seed-data.ts | PLACEMENT_SEEDS (the seven rows), PlacementSeed type, pure diffPlacementSeed(seed, row). No database import. |
packages/db/src/seed/seed-placements.ts | Seed runner: guarded rename delete, insert with onConflictDoNothing({ target: placements.slug }) and .returning({ slug }), divergence warnings. |
packages/db/src/seed/seed-placements.spec.ts | node:test spec importing only placement-seed-data.ts (seed-runtime connects and exits at import). |
apps/api/src/modules/banners/customer/serving/ | Existing serve controller, service and DTOs. Unchanged. |
apps/api/src/modules/banners/customer/tracking/ | Existing tracking controller and service. Unchanged. |
Storefront (nano-store-frontend)
| File | Role |
|---|---|
src/lib/api/banner-schemas.ts | Wire schema for the serve response, corrected to servedAt and items; adds bgColor, displayOrder, ctaOpenNewTab. |
src/lib/api/modules/banner.ts | getBanners(slug); non-404 failures go to logDegraded. Cache { revalidate: 300, tags: ["banners"] }. |
src/lib/banners/safe-banner.ts | toSafeBannerHref, toSafeBannerImageSrc, isAllowedBannerImageSrc, toBannerImageSrc, BANNER_IMAGE_HOSTS. Server-safe, no React. |
src/lib/data/hero-bento.ts | HERO_BENTO_PLACEMENTS (slug to position map), toBentoCard, getHeroBentoData. |
src/app/_components/hero-bento.tsx | Server Component; layout unchanged. Keys are positions (row1-0 to row3-1). |
src/app/_components/bento-card-link.tsx | Client leaf: link or unlinked box, art-directed mobile image, tracking. |
src/app/_lib/use-banner-tracking.ts | Shared impression and click hook, used by the bento and BannerCard. |
src/app/page.tsx | Adds getHeroBentoData() to the page's Promise.all. |
Admin (Happy-shop-admin, app/(dashboard)/dashboard/)
| File | Role |
|---|---|
placements/_components/CreatePlacementDialog.tsx, PlacementFormSections.tsx, PlacementSlugField.tsx, placement-form.ts | Slug keeps _, validated client-side. |
placements/_components/EditPlacementDialog.tsx | Slug read-only; payload no longer sends slug. |
placements/_schemas/placement.ts | Slug regex ^[a-z0-9_-]+$. |
campaigns/[publicId]/page.tsx | Lists placements and banners with { pagination: true, page: 1, size: 100 }. |
campaigns/[publicId]/_components/ | BannerAssignmentsTab.tsx, AddAssignmentDialog.tsx, AssignmentFormFields.tsx, placement-hints.ts (recommended size and one-banner help). |
banners/_components/BannerRequiredFields.tsx | Image hints point at the placement's recommended size. |
banner-analytics/page.tsx, _components/BannerAnalyticsFilterForm.tsx, BannerAnalyticsEventsTable.tsx, BannerAnalyticsEventsList.tsx, _lib/ | Placement filter on both tabs, URL-owned state, daily-UTC copy. |
Data Model
No new table, column or enum value. Rows are inserted into placements.
Common to all seven rows:
| Column | Value |
|---|---|
layoutType | inline_card |
maxBanners | 1 |
pageContext | / |
allowPartialRender | true, so an isFallback assignment in a live campaign can fill the card |
isActive | default true |
Per-row values:
| slug | sortOrder | recommendedWidth | recommendedHeight | recommendedAspectRatio |
|---|---|---|---|---|
home_bento_1 | 10 | 1440 | 1800 | 4:5 |
home_bento_2 | 11 | 1440 | 1800 | 4:5 |
home_bento_3 | 12 | 1920 | 2400 | 4:5 |
home_bento_4 | 13 | 2048 | 1024 | 2:1 |
home_bento_5 | 14 | 2048 | 3250 | 29:46 |
home_bento_6 | 15 | 1440 | 720 | 2:1 |
home_bento_7 | 16 | 1440 | 720 | 2:1 |
notes on each row carries the operator rule: one banner shows, lowest display order then highest weight wins, copy is baked in, do not rename, no device/login/new-visitor/referrer targeting.
home_hero, home_promo_left and home_promo_right are removed from the seed list. Rows already in a database are untouched.
Write behavior
- Insert is
onConflictDoNothingonplacements.slugand returns inserted slugs. A re-run inserts 0 rows. - For slugs that already existed, the seed reads the row back and warns per divergent field among
layoutType,maxBanners,allowPartialRender,isActive. It never overwrites an operator's edit. - Log line:
placements: N inserted (...), M already present (...). - The existing guarded delete of renamed slugs is unchanged; its operator message now names
home_bento_1..7. Legacy home slugs are deliberately not inRENAMED_SLUGS, because that path deletes rows and legacy rows may hold campaign history.
Runtime Rules and Domain Invariants
A card is a banner or a fixture, with one exception
toBentoCard(slot, fixture) returns the fixture when the slot is null, has no banners, or the primary image does not pass the image guard. Otherwise it builds the card from banners[0] only. href is never inherited from the fixture. bgColor falls back to the fixture's colour when the banner has none.
| Card field | From banner | Else |
|---|---|---|
image | primaryImageUrl through toBannerImageSrc | whole card becomes the fixture |
mobileImage | mobileImageUrl through toBannerImageSrc | omitted |
alt | primaryImageAlt, trimmed | banner title |
title | headline, trimmed | banner title |
href | toSafeBannerHref(ctaUrl) | null: card renders unlinked |
openInNewTab | ctaOpenNewTab | false |
bgColor | parsed bgColor | fixture colour |
priority | fixture's | |
tracking | { bannerPublicId, placementPublicId, campaignPublicId } | fixture sends nothing |
The slug is the contract
The storefront requests home_bento_n by name. A rename detaches the card silently. The admin edit dialog does not send slug; the backend PATCH still permits a rename.
Linked and unlinked cards
With href set, the box is a <Link> with an aria-label, hover scale, and rel="noopener noreferrer" plus target="_blank" when openInNewTab. With href null, it is a <div> with no hover scale and no aria-label; the image alt carries the text. Impressions are tracked either way when tracking is set.
Art direction
With a mobileImage, the card renders <picture> with a <source media="(max-width: 639px)"> taking only the srcSet from getImageProps, so the mobile crop passes through the same next/image host allowlist. Priority cards use fetchPriority="high" and loading="eager" on the single <img>, with no extra desktop preload on phones.
Tracking
useBannerTracking(ref, bannerPublicId, placementPublicId, campaignPublicId) takes primitive arguments. The impression fires once per banner id at 0.5 visibility, then the observer disconnects. onClick and onAuxClick (middle button) send clicks. Missing bannerPublicId or placementPublicId turns tracking off. The payload sent is { bannerPublicId, placementPublicId, campaignPublicId?, occurredAt, correlationId }; the backend dedupes by correlationId.
Failure is never fatal, except maintenance
getBanners resolves null for 404 (silent) and for every other failure (logged by logDegraded). logDegraded rethrows a 503 SYSTEM_MAINTENANCE_ACTIVE by design. getBanners and getHeroBentoData must not be wrapped to swallow it.
Admin list size
pagination: false does not mean unbounded on this backend: the services fall back to .limit(limit ?? 20). Every admin list the feature relies on is called with exactly { pagination: true, page: 1, size: 100 }, 100 being the DTO maximum. Rows beyond 100 are not shown.
Analytics filter state is the URL
placementPublicId, bannerPublicId, campaignPublicId, dates and tab live in the URL search params. The filter form is the only filter control and renders on both tabs. Submitting preserves other params and resets page. The Events table is prop-driven and remounts on a URL change.
Configuration
| Key | Where | Meaning |
|---|---|---|
BANNER_SERVE_CACHE_TTL_SECONDS | backend | Serve cache TTL. Default 60. |
TRUSTED_PROXY_HOPS | storefront (.env.example: "1") | Must be 1 or more for the tracking throttle precondition. The API hard-codes app.set("trust proxy", 1) in main.ts and has no such variable. |
NEXT_PUBLIC_ASSET_ORIGIN | storefront | Origin whose /public/… images are accepted. Must equal the admin's NEXT_PUBLIC_API_URL origin. Optional; absent means only the fixed hosts pass. |
NEXT_PUBLIC_API_URL | admin | Backend origin, no /api suffix. |
BANNER_CACHE | storefront modules/banner.ts | { revalidate: 300, tags: ["banners"] }. |
FIXED_BANNER_IMAGE_HOSTS in safe-banner.ts must stay in step with images.remotePatterns in the storefront next.config.ts and the img-src list in lib/auth/csp.ts. tests/lib/auth/customer-name.test.ts reads both files as text and fails on drift.
Security and Operational Controls
- Link, image and colour guards are listed in the Feature Guide. They live in
safe-banner.tsand the wire schema. - Admin writes (
banner.changed) emitcontent:bannersthrough the admin cache client, which the storefront tag map turns into thebannerstag. - Throttles: serve uses
RATE_LIMITS.PUBLIC_HIGH_FREQUENCY; tracking usesRATE_LIMITS.PUBLIC_TRACKING_EVENT. Seven serve calls per revalidation, at most about one per 300 seconds per storefront instance, stay under the serve tier. - Tracking ingest uses the existing BullMQ banners queue, untouched. A down queue loses events silently (the BFF answers 202).
- Consistency window after an admin write or a schedule boundary: up to about 60 seconds backend cache plus up to 300 seconds storefront cache.
- Impression and click events are forgeable (existing behaviour); treat analytics as unverified signals.
Error Contract
No new codes. PLACEMENT_NOT_FOUND (404) is the empty state. Precedence on the storefront for each card:
- 503
SYSTEM_MAINTENANCE_ACTIVE: propagate toerror.tsx. - 404:
null, no log, fixture. - Any other failure, including a schema parse failure:
null, logged vialogDegraded, fixture. - Success with no banner: fixture.
- Success with a banner whose primary image fails the guard: fixture.
- Otherwise: banner card, with link,
bgColorand mobile image each degrading independently.
File Map
Nano-store-backend/packages/db/src/seed/
placement-seed-data.ts PLACEMENT_SEEDS, diffPlacementSeed
seed-placements.ts runner (db:seed:placements)
seed-placements.spec.ts node:test spec
nano-store-frontend/src/
lib/api/banner-schemas.ts
lib/api/modules/banner.ts
lib/banners/safe-banner.ts
lib/data/hero-bento.ts
app/_components/hero-bento.tsx
app/_components/bento-card-link.tsx
app/_components/banner-slot-client.tsx refactored onto the hook
app/_lib/use-banner-tracking.ts
app/page.tsx
Happy-shop-admin/app/(dashboard)/dashboard/
placements/ dialogs, schema, form helpers
campaigns/[publicId]/ page, assignments tab, dialog, hints
banners/_components/BannerRequiredFields.tsx
banner-analytics/ page, filter form, events table and list, _libSee Also
Home Bento Dynamic Feature Guide
The seven-card homepage hero bento driven by placements home_bento_1..7, with the operator runbook, deploy steps, safety guards, and known follow-ups.
Home Bento Dynamic API Reference
The existing banner endpoints the home bento relies on, the corrected serve response shape, tracking payloads, and integrator guardrails.