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
headermenu: storage, the admin read and replace endpoints, and the public read endpoint - Validation of every item against the live catalog, and the admin
targetStatusevaluation - Serve-time filtering and auto-children expansion
- The
navigationcache 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/.
| Piece | File |
|---|---|
| Aggregate module | navigation.module.ts |
| Shared module (read service, evaluator) | navigation-shared.module.ts |
| Admin controller | admin/navigation-admin.controller.ts |
| Admin read service | admin/navigation-admin.service.ts |
| Admin write service | admin/navigation-admin-write.service.ts |
| Target resolution | admin/resolve-navigation-targets.ts |
| Tree validation | admin/validate-navigation-tree.ts |
| Request DTOs | admin/dto/update-navigation.dto.ts |
| Customer controller | customer/navigation-customer.controller.ts |
| Customer service | customer/navigation-customer.service.ts |
| Shared read queries | shared/navigation-read.service.ts |
| Status evaluation | shared/navigation-evaluate.ts |
| Wire vocabulary and constants | navigation.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).
navigation_menu
| Column | Notes |
|---|---|
public_id | Unique |
key | Unique; check chk_navigation_menu_key admits only 'header' |
version | Optimistic-concurrency counter; check >= 1; bumped by 1 per save |
updated_by_admin_user_id | FK to admin_users, ON DELETE SET NULL |
navigation_item
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)withNULLS NOT DISTINCTfixes sibling order. - Composite FK
(menu_id, parent_id, parent_children_mode)forces a parent to be inmanualmode. - 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
| Rule | Code |
|---|---|
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-null | NAVIGATION_TARGET_INVALID |
Label rule (1–40 code points after trim + NFC, no \p{Cc}/\p{Cf}); label required for url | NAVIGATION_TARGET_INVALID |
URL rule: site-relative ^/(?!/)[^\s\\]*$, or absolute https: with no credentials, stored as new URL(value).href, 2048 limit rechecked after normalisation | NAVIGATION_TARGET_INVALID |
auto only on brand or depth-0 category targets; children empty unless manual | NAVIGATION_TARGET_INVALID |
| Category target depth at most 1 | NAVIGATION_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-deleted | NAVIGATION_TARGET_NOT_FOUND |
| Total rows (top-level plus children) at most 200 | NAVIGATION_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
- Disabled items, and items whose status would be
deleted,invalidorhidden, are omitted. Anautocategory that is no longer depth 0 is served as a plain link instead. - 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). - Slugs are the current slugs (
is_current). - 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, idand 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.
fnmust 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 nocontext. The navigation PUT passesmodule: "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;40001is 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
navigationinCACHE_DOMAIN_REGISTRY(apps/api/src/modules/cache-invalidation/cache-invalidation.tags.ts) with storefront tagnavigation, no Redis patterns, entity typenavigation_menu. - PUT calls
triggerForWrite({ domain: "navigation", entityId: "header", reason: "navigation.update" })after commit. - The
catalog_category,catalog_brandandcatalog_brand_seriesdomains also emit thenavigationtag. - The backend treats any failed tag as a failure and retries the whole domain, so the storefront must accept the
navigationtag first (deploy step 0).
6. Configuration
| Variable | Default | Purpose |
|---|---|---|
DB_TX_RETRY_MAX_ATTEMPTS | 3 | Total attempts of a retried transaction, including the first |
DB_TX_RETRY_BASE_DELAY_MS | 50 | Base of the exponential backoff |
DB_TX_RETRY_MAX_DELAY_MS | 1000 | Cap 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 grandchildchildren, are rejected.
8. Error Contract
| Code | HTTP | Raised when |
|---|---|---|
NAVIGATION_VERSION_CONFLICT | 409 | version differs from the current menu version; checked first |
NAVIGATION_TARGET_INVALID | 400 | A shape, label, URL, depth or consistency rule fails |
NAVIGATION_TARGET_NOT_FOUND | 400 | A referenced entity is missing, soft-deleted or has no current slug |
NAVIGATION_SYSTEM_ITEMS_INVALID | 400 | System items missing, duplicated or nested |
NAVIGATION_LIMIT_EXCEEDED | 400 | More than 200 rows |
NAVIGATION_MENU_MISSING | 500 | The 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
- Storefront tag registration only (
tag-map.ts:navigationinSTOREFRONT_TAGSand["navigation", "navigation"]inPREFIX_RULES), released alone. Inert, and it prevents a retry storm from step 2. - Backend: code, migrations 0058 and 0059,
permissions:sync. Catalog writes now also purgenavigation. - 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
| Repo | Files |
|---|---|
| nano-store-frontend | src/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-admin | app/(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
- Feature doc: /docs/developer/navigation/feature
- API doc: /docs/developer/navigation/api