Skip to content

fix: cache deferred section data across SPA navigations + registerSectionsSync module form - #8

Merged
JonasJesus42 merged 7 commits into
mainfrom
fix/deferred-section-spa-cache
Mar 13, 2026
Merged

JonasJesus42 merged 7 commits into
mainfrom
fix/deferred-section-spa-cache

Conversation

@JonasJesus42

@JonasJesus42 JonasJesus42 commented Mar 13, 2026 •

Copy link
Copy Markdown
Contributor

Problem

Two related issues in DeferredSectionWrapper that caused CLS on SPA navigation back to a previously-visited page (e.g. PDP → home):

1. No cross-navigation cache for deferred section data

DeferredSectionWrapper stored resolved section data in component-local useState. Each navigation away unmounts the component; navigating back remounts it with section=null, triggering a new _serverFn fetch. During this fetch (~200–800ms even with server-side caching), the section goes through:

null (optionsReady=false) → skeleton (optionsReady=true, section=null) → content

This causes a significant CLS spike, especially for product shelves.

2. optionsReady=false for sync-registered sections

DeferredSectionWrapper initializes optionsReady = !!getSectionOptions(component). For sections registered via registerSectionsSync, sectionOptions was never populated at registration time — only after preloadSectionModule() resolved async. This caused a brief null render before the skeleton appeared, even for sections whose module was already loaded.

Solution

Fix 1 — Module-level deferred section cache

Added a Map<stableKey, {section, ts}> at module level in DecoPageRenderer.tsx:

  • TTL matches cmsRouteConfig staleTime: 5 min prod / 5 s dev
  • useState initializer reads from cache on client mount
  • stableKey change detection restores from cache instead of always resetting to null
  • loadFn callbacks store the resolved section in the cache

Result: navigating PDP → home renders deferred sections immediately from cache — no empty/skeleton phase.

Fix 2 — registerSectionsSync accepts full module objects

Extended the API (backwards compatible) to accept either a ComponentType or a full module object:

// Before (still works)
registerSectionsSync({
  "site/sections/Product/ProductShelf.tsx": ProductShelfComponent,
});

// New: pass the full module to pre-populate LoadingFallback
import * as ProductShelfModule from "./sections/Product/ProductShelf";
registerSectionsSync({
  "site/sections/Product/ProductShelf.tsx": ProductShelfModule,
});

When the module form is used, LoadingFallback and ErrorFallback are stored in sectionOptions immediately. DeferredSectionWrapper initializes optionsReady=true and shows the correct skeleton on first paint.

Test plan

  • Navigate to a page with deferred sections (e.g. home with product shelves)
  • Navigate to PDP
  • Navigate back to home — sections should render immediately, no skeleton flash
  • Wait 5 min, navigate back — sections should re-fetch (cache expired)
  • Dev mode: cache should expire after 5 s
  • registerSectionsSync with plain component still works (backwards compat)
  • registerSectionsSync with module object populates getSectionOptions() immediately

🤖 Generated with Claude Code


Summary by cubic

Fixes CLS on SPA back navigation by caching deferred section data with prop-aware keys, and updates registerSectionsSync to accept full module objects so skeletons render on first paint. Adds geo-safe caching using country|region|city keys with purge support, plus new matchers and safety guards.

  • Bug Fixes

    • Cache deferred sections across SPA navigations with prop-aware keys (TTL: 5 min prod / 5 s dev) to remove skeleton flashes.
    • Vary route cache keys by CF geo tuple country|region|city; purge accepts countries[] as geo strings and always clears the non-geo variant to prevent content leaks.
    • Harden UA regex against ReDoS; location matcher reads __cf_geo_region_code (fallback to region name) and matches both short code and full name.
  • New Features

    • registerSectionsSync accepts full module objects ({ default, LoadingFallback?, ErrorFallback? }) to show the correct skeleton on first paint (backwards compatible).
    • Added matchers: location (via CF geo cookies), user agent, environment, multi (AND/OR), negate; exported evaluateMatcher and injectGeoCookies; registered admin schemas.

Written for commit 9e67d7c. Summary will update on new commits.

JonasJesus42 and others added 2 commits March 12, 2026 21:04
DeferredSectionWrapper previously stored resolved section data in
component-local useState. Each SPA navigation away and back caused the
component to unmount/remount with section=null, triggering a new
_serverFn fetch — producing an empty → skeleton → content transition
that caused significant CLS (especially for product shelves).

Add a module-level Map<stableKey, {section, ts}> cache with a TTL
matching cmsRouteConfig staleTime (5 min prod / 5 s dev):

- useState initializer reads from cache on client mount
- stableKey change detection restores from cache instead of always
  setting section=null
- loadFn callbacks store the resolved section in the cache

Result: navigating PDP → home reuses cached section data and renders
product shelves immediately — no empty/skeleton phase on back navigation.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
…e sectionOptions

Previously registerSectionsSync only accepted ComponentType<any> references.
DeferredSectionWrapper would start with optionsReady=false even for sync-registered
sections and call preloadSectionModule() async to discover LoadingFallback —
causing a brief null render before the skeleton appeared.

Extend the API to accept either a plain component or a full module object:

  registerSectionsSync({
    "site/sections/Product/ProductShelf.tsx": ProductShelfModule,
  });

  // where ProductShelfModule = { default, LoadingFallback?, ErrorFallback? }

When the module form is used, LoadingFallback and ErrorFallback are stored
in sectionOptions immediately at registration time. DeferredSectionWrapper
then initializes optionsReady=true and renders the correct skeleton on the
first paint — no async round-trip needed.

Backwards compatible: plain ComponentType<any> still works unchanged.

Co-Authored-By: Claude Sonnet 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

1 issue found across 2 files

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/hooks/DecoPageRenderer.tsx">

<violation number="1" location="src/hooks/DecoPageRenderer.tsx:221">
P1: Reusing cached sections here is unsafe because the cache key ignores `deferred.rawProps`, so prop changes for the same slot can render stale data and never refetch.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/hooks/DecoPageRenderer.tsx Resolved
JonasJesus42 and others added 2 commits March 12, 2026 21:18
Migrate all missing matchers from Fresh/Deno to TanStack Start:

- location.ts: geo-targeting via __cf_geo_* cookies with country name-to-ISO mapping
- userAgent.ts: substring and regex matching on User-Agent
- environment.ts: production vs development via process.env.NODE_ENV
- multi.ts: AND/OR combinator with recursive evaluateMatcher
- negate.ts: boolean NOT with recursive evaluateMatcher

Also:
- Export evaluateMatcher from cms/resolve for recursive matcher evaluation
- Export injectGeoCookies from sdk/workerEntry for CF geo data injection
- Register admin schemas for all 5 new matchers

Co-Authored-By: Claude Opus 4.6 <[email protected]>
The cache key for deferred sections only used pagePath, component, and
index — ignoring rawProps. If CMS props changed for the same slot, stale
cached data would be served. Add a DJB2 hash of rawProps to the key.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 5 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/sdk/workerEntry.ts">

<violation number="1" location="src/sdk/workerEntry.ts:314">
P1: Adding Cloudflare geo data to `Cookie` makes location-based matchers affect the rendered HTML, but the worker cache key does not vary by those cookies. The first location to fill the edge cache can therefore leak geo-targeted content to other locations.</violation>
</file>

<file name="src/matchers/builtins.ts">

<violation number="1" location="src/matchers/builtins.ts:252">
P2: `regionCode` rules are reading the wrong cookie, so location matches by region code will never work against Cloudflare geo data.</violation>

<violation number="2" location="src/matchers/builtins.ts:280">
P1: Guard the `match` regex before compiling it; this currently allows request-time ReDoS patterns from CMS matcher data.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/sdk/workerEntry.ts Resolved
Comment thread src/matchers/builtins.ts Resolved
Comment thread src/matchers/builtins.ts Resolved
- workerEntry: include CF country in cache key to prevent geo-targeted
  content leaking across locations
- builtins: guard userAgent regex with isSafePattern to prevent ReDoS
- builtins: read __cf_geo_region_code (short code) with fallback to
  __cf_geo_region (full name) for location matcher regionCode matching

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

3 issues found across 3 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/sdk/workerEntry.ts">

<violation number="1" location="src/sdk/workerEntry.ts:432">
P2: Adding `__cf_country` to cache keys breaks cache purge for geo-targeted pages, because purge never deletes the country-specific variants.</violation>

<violation number="2" location="src/sdk/workerEntry.ts:432">
P1: `__cf_country` is skipped whenever `buildSegment` is enabled, so geo-targeted pages can still leak across countries for segmented caches.</violation>
</file>

<file name="src/matchers/builtins.ts">

<violation number="1" location="src/matchers/builtins.ts:254">
P2: Preferring `__cf_geo_region_code` here breaks existing location rules that were authored against the previous region-name value. Keep matching the legacy region name as well so old geo-targeted content does not stop rendering after deploy.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/sdk/workerEntry.ts Resolved
Comment thread src/sdk/workerEntry.ts Resolved
Comment thread src/matchers/builtins.ts Resolved
…gion compat

- Move CF country cache key injection before buildSegment early return
  so geo-targeted content is never leaked regardless of cache key strategy
- Accept optional countries[] in purge body to clear geo-specific variants
- Match regionCode rules against both short code and full name so existing
  rules authored against either format continue working after deploy

Co-Authored-By: Claude Opus 4.6 <[email protected]>

@cubic-dev-ai cubic-dev-ai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

2 issues found across 2 files (changes from recent commits).

Prompt for AI agents (unresolved issues)

Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.


<file name="src/sdk/workerEntry.ts">

<violation number="1" location="src/sdk/workerEntry.ts:420">
P1: Vary geo-targeted cache keys by region/city too, not just country.</violation>

<violation number="2" location="src/sdk/workerEntry.ts:490">
P1: Purge requests without `countries` no longer invalidate the live cache entries.</violation>
</file>

Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review.

Comment thread src/sdk/workerEntry.ts Resolved
Comment thread src/sdk/workerEntry.ts Resolved
- Cache key now includes full geo tuple (country|region|city) via __cf_geo
  param so location matcher results at any granularity do not leak
- Purge accepts geo strings matching the __cf_geo format and always
  purges the non-geo variant as baseline

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@JonasJesus42
JonasJesus42 merged commit 656123f into main Mar 13, 2026
1 check passed
@github-actions

Copy link
Copy Markdown

🎉 This PR is included in version 0.21.0 🎉

The release is available on:

Your semantic-release bot 📦🚀

guitavano added a commit that referenced this pull request Nov 17, 2026
…anStack Start, esbuild) (#832)

Closes the open Dependabot alerts in one PR, with the lockfile. The
Dependabot PRs (#811, #828, #747) only touch `package.json`, so they all
fail `bun install --frozen-lockfile` in CI.

| Package | From | To | Alerts |
|---|---|---|---|
| `react-server-dom-webpack` (tanstack-rsc-smoke) | 19.2.7 | 19.2.9 |
#19, critical: RSC RCE, GHSA-xqc2-xf4c-x3h3 |
| `react` / `react-dom` (all pinned workspaces) | 19.2.7 | 19.2.9 | peer
floor of the above |
| `next` (nextjs, compat-v7, nextjs-binding-smoke) | 16.3.8 | 16.4.6 |
#10–12, #14, #15, #17, #18, #20–22 |
| `@tanstack/react-start` (tanstack, compat-v7, smokes) | 1.168.58 |
1.168.61 | #2–4, #7, #9 |
| `@tanstack/react-router` | 1.170.39 | 1.170.42 | the version
react-start 1.168.61 pins, so it stays a single copy |
| `esbuild` (blocks, tanstack, compat-v7) | ^0.27.3 | ^0.28.2 | #5, #6,
#8 (low) |

`bun.lock` was regenerated with bun 1.3.5 (the `packageManager`). React
dedupes to a single 19.2.9 at the root, with no nested copies. Vite
still has its own transitive `[email protected]` (its own range); that is
outside our manifests.

Supersedes #811, #828 and #747.

### Verified locally (bun 1.3.5, node 24)
- `bun install --frozen-lockfile` ✅
- `bun run typecheck` ✅ · `bun run lint` ✅
- `bun x vitest run`: 3388 passed, 0 failed ✅ (includes
`tests/release.test.ts`)
- `examples/tanstack-worker-smoke`: build + smoke ✅
- `examples/nextjs-binding-smoke`: build + smoke ✅
- `examples/tanstack-rsc-smoke`: build + typecheck ✅

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Bumps several dependencies to clear open Dependabot security alerts,
including a critical RCE in `react-server-dom-webpack`
(GHSA-xqc2-xf4c-x3h3). The lockfile was regenerated so `bun install
--frozen-lockfile` passes — React dedupes to a single 19.2.9 copy.

**Dependencies**
- `react`, `react-dom`, and `react-server-dom-webpack` 19.2.7 → 19.2.9
- `next` 16.3.8 → 16.4.6
- `@tanstack/react-start` 1.168.58 → 1.168.61, with
`@tanstack/react-router` 1.170.42
- `esbuild` ^0.27.3 → ^0.28.2; Vite's own transitive `[email protected]` is
untouched
- Typecheck, lint, the full test suite (3388 passed), and the Next.js
and TanStack smoke builds all pass

<sup>Written for commit 123acc8.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/832?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/decocms/blocks/832?returnTo=https%3A%2F%2Fgithub.com%2Fdecocms%2Fblocks%2Fpull%2F832&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->

Co-authored-by: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant