Nano Store - Ecommerce Docs
Developer Resourcesnavigation

Navigation Backend Architecture

Internal architecture of the navigation module — composition, data model, invariants, configuration, and deploy order.

Navigation Module — Backend Documentation

1. Module Scope

The navigation module owns:

  • The header menu: storage, the admin read and replace endpoints, and the public read endpoint
  • Validation of every item against the live catalog, and the admin targetStatus evaluation
  • Serve-time filtering and auto-children expansion
  • The navigation cache domain and its storefront tag

It does not own:

  • Catalog data (categories, brands, series) — it only references them
  • Building storefront URLs — the API returns slugs, and the storefront builds hrefs
  • Picker data in the admin — that comes from the catalog admin endpoints

2. Composition

All files are under apps/api/src/modules/navigation/.

PieceFile
Aggregate modulenavigation.module.ts
Shared module (read service, evaluator)navigation-shared.module.ts
Admin controlleradmin/navigation-admin.controller.ts
Admin read serviceadmin/navigation-admin.service.ts
Admin write serviceadmin/navigation-admin-write.service.ts
Target resolutionadmin/resolve-navigation-targets.ts
Tree validationadmin/validate-navigation-tree.ts
Request DTOsadmin/dto/update-navigation.dto.ts
Customer controllercustomer/navigation-customer.controller.ts
Customer servicecustomer/navigation-customer.service.ts
Shared read queriesshared/navigation-read.service.ts
Status evaluationshared/navigation-evaluate.ts
Wire vocabulary and constantsnavigation.constants.ts

Guards:

  • Admin controller: @UseGuards(JwtAuthGuard, RoleGuard) with @Permissions("Navigation_READ") on GET and @Permissions("Navigation_UPDATE") on PUT.
  • Customer controller: @Public(), @UseGuards(IpThrottlerGuard), @IpThrottle(RATE_LIMITS.PUBLIC_HIGH_FREQUENCY). The throttle needs both the guard and the decorator.

MobileModule imports the leaf NavigationCustomerModule (not the aggregate), so the route mounts at /api/mobile/navigation rather than /api/navigation.


3. Data Model

Migrations 0058_navigation.sql (schema) and 0059_navigation_seed.sql (seed), in packages/db/src/migrations/. Drizzle schema: packages/db/src/schema/navigation/navigation.ts.

Enums

navigation_target_kind (system, category, brand, series, url), navigation_system_key (all_products, brands, sale), navigation_children_mode (none, auto, manual).

ColumnNotes
public_idUnique
keyUnique; check chk_navigation_menu_key admits only 'header'
versionOptimistic-concurrency counter; check >= 1; bumped by 1 per save
updated_by_admin_user_idFK to admin_users, ON DELETE SET NULL

One row per top-level item or child. Children point at their parent via parent_id.

  • Target columns: target_kind, system_key, category_id, brand_id, series_id, url.
  • Catalog FKs use ON DELETE RESTRICT; the menu FK cascades.
  • Unique (menu_id, parent_id, position) with NULLS NOT DISTINCT fixes sibling order.
  • Composite FK (menu_id, parent_id, parent_children_mode) forces a parent to be in manual mode.
  • Check constraints enforce: exactly one target column set for the kind, system items are top-level, label and URL shape, and a non-negative position.

Seed

0059 creates the header menu at version 1 and, only when the menu has no items, inserts the three system items plus catalog-derived items. seedNavigation() in packages/db/src/seed/navigation/seed-navigation.ts runs the same SQL for db:seed:ecommerce. A fresh database without the seeded menu row makes both endpoints fail with NAVIGATION_MENU_MISSING.

Write behavior

PUT deletes every item of the menu and inserts the new tree, then bumps version. It does not diff. Item public_ids therefore change on every save.


4. Runtime Rules and Domain Invariants

Version check first

Inside the transaction the menu row is read FOR UPDATE. Two concurrent saves of the same version serialise there; the second sees the bumped version and gets NAVIGATION_VERSION_CONFLICT. The version check runs before any rule validation, so a 409 carries no violations.

All violations are returned together

Rule failures are collected, not thrown on first. The response errorCode is the code of the first violation and details.violations lists every one: { path, code, message }. path is items[i], items[i].children[j], or the literal items for menu-level rules.

Validation rules

RuleCode
Exactly one top-level item per system key; system items top-level with childrenMode: "none"NAVIGATION_SYSTEM_ITEMS_INVALID
Only the fields for the chosen kind are non-nullNAVIGATION_TARGET_INVALID
Label rule (1–40 code points after trim + NFC, no \p{Cc}/\p{Cf}); label required for urlNAVIGATION_TARGET_INVALID
URL rule: site-relative ^/(?!/)[^\s\\]*$, or absolute https: with no credentials, stored as new URL(value).href, 2048 limit rechecked after normalisationNAVIGATION_TARGET_INVALID
auto only on brand or depth-0 category targets; children empty unless manualNAVIGATION_TARGET_INVALID
Category target depth at most 1NAVIGATION_TARGET_INVALID
Every referenced category, brand and series exists, is not soft-deleted and has a current slug; a series' owning brand is not soft-deletedNAVIGATION_TARGET_NOT_FOUND
Total rows (top-level plus children) at most 200NAVIGATION_LIMIT_EXCEEDED

Array bounds (16 top-level, 30 children) and the 80-character label ceiling are enforced by the DTO; exceeding them is the standard validation 400 with no NAVIGATION_* code.

Customer read snapshot

The public read runs in one read-only REPEATABLE READ transaction, so menu rows, slugs and visibility flags come from the same instant. Statement count is fixed and independent of menu size. There is no Redis layer; the storefront caches the response.

Serve-time filtering

  1. Disabled items, and items whose status would be deleted, invalid or hidden, are omitted. An auto category that is no longer depth 0 is served as a plain link instead.
  2. A depth-1 category target is omitted, and a root emits no auto children, when the parent has fewer than 2 visible, non-deleted children with a current slug (NAV_MIN_VISIBLE_CHILDREN_FOR_CHILD_ROUTE; mirrors the storefront route rule).
  3. Slugs are the current slugs (is_current).
  4. Auto children are visible, non-deleted, current-slug direct children of a root category, or visible non-deleted series of a brand, ordered by display_order, id and capped at the catalog tree child cap (200).

Accepted deviation: missing menu is a 500

If no header menu row exists, both reads and the PUT throw 500 NAVIGATION_MENU_MISSING, per the frozen contract. It is an integrity fault, not a client error. The storefront treats it as a failed read and renders its three-link fallback.

Read bound on the admin endpoint

Both reads are bounded by NAV_MAX_ROWS (200); loadItems takes an overflow mode and defaults to throw (fail closed).

  • Admin GET, and the PUT's before and after snapshots: a menu holding more than 200 rows is logged at error level and fails with 500 NAVIGATION_MENU_OVERFLOW ("The menu has more items than the editor can safely load. Contact an engineer."). An editor that loaded a clipped menu and saved it would permanently drop rows.
  • Storefront GET: clips to the first 200 rows and logs a warning.

Retry on serialization failure

The PUT transaction runs inside withSerializationRetry (apps/api/src/common/utils/serialization-retry.util.ts). The helper re-runs the whole transaction when Postgres aborts it with SQLSTATE 40001 (serialization failure) or 40P01 (deadlock), found on the error or up to 5 levels down its cause chain. Integrity errors are never retried.

  • fn must be the entire transaction and must have no side effects outside the database. Activity logging and cache invalidation run after it resolves.
  • Between attempts it waits full-jitter exponential backoff: random() * min(maxDelayMs, baseDelayMs * 2^(attempt-1)).
  • Each retry logs one warning: [<module>] <label> retry <n>/<max-1> after SQLSTATE <code> (requestId=<id>). The [<module>] prefix and the requestId suffix are omitted when the caller supplies no context. The navigation PUT passes module: "navigation" and no requestId, and reads its attempt count and delays from the three variables below.
  • The PUT runs at READ COMMITTED, where Postgres aborts it only with 40P01; 40001 is retried for callers at a higher isolation level.

When attempts are exhausted the helper throws 409 SYS_TRANSACTION_CONFLICT ("The change conflicted with another update. Please retry.") with the last driver error as cause. A non-retryable error is rethrown unchanged and at once. Attempt count and delays come from the environment (see Configuration).

After commit

Activity logging (navigation.update, module Navigation, with before and after snapshots and the from/to version) and storefront cache invalidation run after the commit. A failure in either is logged and does not fail the request: the save is durable.


5. Cache Invalidation

  • New domain navigation in CACHE_DOMAIN_REGISTRY (apps/api/src/modules/cache-invalidation/cache-invalidation.tags.ts) with storefront tag navigation, no Redis patterns, entity type navigation_menu.
  • PUT calls triggerForWrite({ domain: "navigation", entityId: "header", reason: "navigation.update" }) after commit.
  • The catalog_category, catalog_brand and catalog_brand_series domains also emit the navigation tag.
  • The backend treats any failed tag as a failure and retries the whole domain, so the storefront must accept the navigation tag first (deploy step 0).

6. Configuration

VariableDefaultPurpose
DB_TX_RETRY_MAX_ATTEMPTS3Total attempts of a retried transaction, including the first
DB_TX_RETRY_BASE_DELAY_MS50Base of the exponential backoff
DB_TX_RETRY_MAX_DELAY_MS1000Cap on any single wait

NavigationAdminWriteService reads all three once at construction and throws ERR_CONFIG_INVALID if any is missing or not a positive integer, so a bad value stops the boot instead of falling back silently.

No other navigation-specific configuration exists. The permission codes Navigation_READ and Navigation_UPDATE are added to the permission catalog; run permissions:sync after deploying.


7. Security and Operational Controls

  • Admin routes require JWT plus the permission; the public read has none and is throttled per IP at PUBLIC_HIGH_FREQUENCY. The Redis-backed throttle fails closed: if Redis is down the read returns 500 and the storefront shows its fallback.
  • Absolute URLs must be https: with no username or password; control and format characters are refused in labels and URLs.
  • Request bodies pass through the global ValidationPipe (whitelist, forbidNonWhitelisted, transform), so unknown keys, including a grandchild children, are rejected.

8. Error Contract

CodeHTTPRaised when
NAVIGATION_VERSION_CONFLICT409version differs from the current menu version; checked first
NAVIGATION_TARGET_INVALID400A shape, label, URL, depth or consistency rule fails
NAVIGATION_TARGET_NOT_FOUND400A referenced entity is missing, soft-deleted or has no current slug
NAVIGATION_SYSTEM_ITEMS_INVALID400System items missing, duplicated or nested
NAVIGATION_LIMIT_EXCEEDED400More than 200 rows
NAVIGATION_MENU_MISSING500The header menu row does not exist

Precedence on PUT: validation pipe (no NAVIGATION_* code) → menu lookup (MENU_MISSING) → version check (VERSION_CONFLICT) → tree rules (first violation's code).


9. Deploy Order

  1. Storefront tag registration only (tag-map.ts: navigation in STOREFRONT_TAGS and ["navigation", "navigation"] in PREFIX_RULES), released alone. Inert, and it prevents a retry storm from step 2.
  2. Backend: code, migrations 0058 and 0059, permissions:sync. Catalog writes now also purge navigation.
  3. Storefront nav switch and admin builder together. If the storefront were ahead of the backend, the 404 would show the degraded fallback.

Backend and admin ship in the same window. The two are mutually incompatible across the removal of the category brand and series qualifier: an admin that still sends the old qualifier keys gets a 400 (the global ValidationPipe uses whitelist and forbidNonWhitelisted), and a new admin against an old backend would be sent fields it no longer understands. The storefront release order above is unchanged; it tolerates both wire shapes.

Rollback in reverse: storefront nav switch, admin, backend code, then down migrations 0059 and 0058. The step 1 tag registration may stay.


10. Other Repos

RepoFiles
nano-store-frontendsrc/lib/catalog/nav-href.ts (href builder), src/lib/catalog/nav.ts (getPrimaryNav, fallback), src/lib/api/modules/navigation.ts (fetch, tag navigation), src/app/api/revalidate/tag-map.ts, src/components/layout/primary-nav.tsx, mega-menu.tsx, mobile-menu.tsx
Happy-shop-adminapp/(dashboard)/dashboard/navigation/ (page, _components/, _actions/navigation.ts), lib/mobile-api/admin/navigation.ts and navigation.types.ts, lib/frontend-cache/contract.ts (navigation.changed), lib/Data/SidebarNav.ts (entry gated by Navigation_READ)

See Also