Nano Store - Ecommerce Docs
Developer ResourcesHome Bento Dynamic

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)

FileRole
packages/db/src/seed/placement-seed-data.tsPLACEMENT_SEEDS (the seven rows), PlacementSeed type, pure diffPlacementSeed(seed, row). No database import.
packages/db/src/seed/seed-placements.tsSeed runner: guarded rename delete, insert with onConflictDoNothing({ target: placements.slug }) and .returning({ slug }), divergence warnings.
packages/db/src/seed/seed-placements.spec.tsnode: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)

FileRole
src/lib/api/banner-schemas.tsWire schema for the serve response, corrected to servedAt and items; adds bgColor, displayOrder, ctaOpenNewTab.
src/lib/api/modules/banner.tsgetBanners(slug); non-404 failures go to logDegraded. Cache { revalidate: 300, tags: ["banners"] }.
src/lib/banners/safe-banner.tstoSafeBannerHref, toSafeBannerImageSrc, isAllowedBannerImageSrc, toBannerImageSrc, BANNER_IMAGE_HOSTS. Server-safe, no React.
src/lib/data/hero-bento.tsHERO_BENTO_PLACEMENTS (slug to position map), toBentoCard, getHeroBentoData.
src/app/_components/hero-bento.tsxServer Component; layout unchanged. Keys are positions (row1-0 to row3-1).
src/app/_components/bento-card-link.tsxClient leaf: link or unlinked box, art-directed mobile image, tracking.
src/app/_lib/use-banner-tracking.tsShared impression and click hook, used by the bento and BannerCard.
src/app/page.tsxAdds getHeroBentoData() to the page's Promise.all.

Admin (Happy-shop-admin, app/(dashboard)/dashboard/)

FileRole
placements/_components/CreatePlacementDialog.tsx, PlacementFormSections.tsx, PlacementSlugField.tsx, placement-form.tsSlug keeps _, validated client-side.
placements/_components/EditPlacementDialog.tsxSlug read-only; payload no longer sends slug.
placements/_schemas/placement.tsSlug regex ^[a-z0-9_-]+$.
campaigns/[publicId]/page.tsxLists 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.tsxImage 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:

ColumnValue
layoutTypeinline_card
maxBanners1
pageContext/
allowPartialRendertrue, so an isFallback assignment in a live campaign can fill the card
isActivedefault true

Per-row values:

slugsortOrderrecommendedWidthrecommendedHeightrecommendedAspectRatio
home_bento_110144018004:5
home_bento_211144018004:5
home_bento_312192024004:5
home_bento_413204810242:1
home_bento_5142048325029:46
home_bento_61514407202:1
home_bento_71614407202: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 onConflictDoNothing on placements.slug and 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 in RENAMED_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 fieldFrom bannerElse
imageprimaryImageUrl through toBannerImageSrcwhole card becomes the fixture
mobileImagemobileImageUrl through toBannerImageSrcomitted
altprimaryImageAlt, trimmedbanner title
titleheadline, trimmedbanner title
hreftoSafeBannerHref(ctaUrl)null: card renders unlinked
openInNewTabctaOpenNewTabfalse
bgColorparsed bgColorfixture colour
priorityfixture'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

KeyWhereMeaning
BANNER_SERVE_CACHE_TTL_SECONDSbackendServe cache TTL. Default 60.
TRUSTED_PROXY_HOPSstorefront (.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_ORIGINstorefrontOrigin 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_URLadminBackend origin, no /api suffix.
BANNER_CACHEstorefront 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.ts and the wire schema.
  • Admin writes (banner.changed) emit content:banners through the admin cache client, which the storefront tag map turns into the banners tag.
  • Throttles: serve uses RATE_LIMITS.PUBLIC_HIGH_FREQUENCY; tracking uses RATE_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:

  1. 503 SYSTEM_MAINTENANCE_ACTIVE: propagate to error.tsx.
  2. 404: null, no log, fixture.
  3. Any other failure, including a schema parse failure: null, logged via logDegraded, fixture.
  4. Success with no banner: fixture.
  5. Success with a banner whose primary image fails the guard: fixture.
  6. Otherwise: banner card, with link, bgColor and 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, _lib

See Also