Skip to content

fix(cms): bypass the layout-section cache during previews (draft/admin) - #444

Closed
guitavano wants to merge 1 commit into
mainfrom
guitavano/fix-layout-cache-draft
Closed

guitavano wants to merge 1 commit into
mainfrom
guitavano/fix-layout-cache-draft

Conversation

@guitavano

@guitavano guitavano commented Aug 6, 2026 •

Copy link
Copy Markdown
Contributor

Fixes the layout-section cache masking previews — a follow-up to the pull-based draft preview (#442), found while testing that PR against a real site (casaevideo-tanstack): main-content sections reflected the draft, but Header/Footer did not.

Root cause

resolveDecoPage / resolvePageSections cache the fully-resolved output of layout sections in a process-wide map (resolvedLayoutCache + an in-flight dedup map), so commerce loaders inside Header/Footer don't re-run on every navigation. The cache is keyed on published content by block name alone — it has no awareness of a request-scoped override. So during a preview:

  • the cache is served → the preview's own Header/Footer edits are masked; and
  • worse, a preview resolve could write unpublished layout content into the shared map → leaked to real visitors on the next published request.

This affects both override paths: pull-based draft preview (getRequestDraftOverride) and the admin POST-render preview (withBlocksOverride). It's a core (@decocms/blocks) issue, so it hit Next and TanStack alike.

Scope (answering "is it just Header/Footer or any global section?")

Only sections registered via registerLayoutSections([...]) — Header/Footer by convention, but whatever a site registers. Ordinary global sections are not affected: they re-resolve per request and already reflected the draft (which is exactly why the live test showed main content updating but the footer stale).

Fix

Skip the layout cache — read, write, and in-flight dedup — whenever hasActiveBlocksOverride() is true. Gating all three matters: bypassing only the read would let a preview resolve write into (or hand its in-flight promise to) the shared cache and leak. Previews are low-volume and uncached (no-store), so resolving layout sections fresh is cheap; published traffic keeps the cache untouched.

hasActiveBlocksOverride() (new, in loader.ts) reuses the exact signal loadBlocks() already uses to decide whether to merge: blocksOverrideStorage.getStore() ?? getRequestDraftOverride().

Tests

New layoutCacheDraft.test.ts: warms the layout cache with published content, then resolves the same cached layout section under both override signals (withBlocksOverride and a draft getter) and asserts it (a) reflects the override and (b) never poisons the published cache. Verified it fails without the fix (expected 'PUBLISHED' to be 'DRAFT').

blocks 1395 · nextjs 73 · tanstack 163 — all green. Typecheck clean; new file passes biome. (Pre-existing biome findings in loader.ts/resolve.ts are on main already, untouched.)

Not in this PR (related, separate)

The same resolvedLayoutCache is keyed only by block name and is not cleared on setBlocks (5-min TTL), so a content deploy can serve stale Header/Footer for up to the TTL. Out of scope here — flagging for a follow-up.

🤖 Generated with Claude Code


Summary by cubic

Fixes preview rendering for layout sections (Header/Footer) by bypassing the process-wide layout cache when a blocks override is active. Previews now show draft edits and never leak unpublished content into the published cache.

  • Bug Fixes
    • Add and export hasActiveBlocksOverride(); use it to bypass the layout cache (read/write/in-flight) during admin previews (withBlocksOverride) and pull-based drafts.
    • Update resolveDecoPage and resolvePageSections to resolve layout sections fresh when overrides are active.
    • Add layoutCacheDraft.test.ts to confirm previews reflect draft edits and the published cache remains untouched.

Written for commit d03063f. Summary will update on new commits.

Review in cubic

`resolveDecoPage`/`resolvePageSections` cache fully-resolved layout sections
(Header/Footer — anything registered via `registerLayoutSections`) in a
process-wide map keyed on published content by block name alone, with no
awareness of a request-scoped override. So during a preview the cache is
served (masking the preview's own Header/Footer edits) and, worse, a preview
resolve could write unpublished layout content into the shared map and leak it
to real visitors.

Surfaced while testing pull-based draft preview against a real site: main
sections reflected the draft, Header/Footer did not. The same gap affects the
admin POST-render preview (`withBlocksOverride`).

Fix: skip the layout cache (read, write, AND in-flight dedup) whenever
`hasActiveBlocksOverride()` is true — an admin override or a draft binding.
Previews are low-volume and uncached, so resolving layout sections fresh is
cheap; published traffic keeps the cache untouched. New
`hasActiveBlocksOverride()` reuses the exact signal `loadBlocks()` already uses
to decide whether to merge.

Scope note: only sections registered as layout sections are affected — ordinary
global sections already re-resolve per request and reflected the draft.

Regression test resolves a cached layout section under both override signals
(withBlocksOverride + draft getter), asserts it reflects the override and never
poisons the published cache. Verified it fails without the fix.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@guitavano
guitavano requested a review from a team August 6, 2026 12:33
@guitavano

Copy link
Copy Markdown
Contributor Author

Closing: this fixes the eager resolvedLayoutCache, but that is not what masks Header/Footer in previews on real sites.

Verified against two real sites:

  • casaevideo-tanstack: Header is explicitly unregisterLayoutSections'd and the Footer resolves through the deferred path, so neither hits the eager layout cache — the original "footer doesn't reflect" report was a measurement artifact (mutated "Atendimento", not the footer's actual "Central de Atendimento").
  • faststore-fila (Next): Header/Footer are resolved in the app shell (app/layout.tsx) via resolveValue, which does not touch resolvedLayoutCache. The masking is the App Router layout-vs-page override-scope issue (the shell resolves before the preview override is bound), not this cache.

The real fix lives in the Next binding / app-shell resolution. Tracking there instead.

@guitavano guitavano closed this Aug 6, 2026
guitavano added a commit that referenced this pull request Aug 6, 2026
)

Fixes Header/Footer not reflecting draft previews on Next.js sites —
reported on `faststore-fila` ("mudei o footer e não refletiu"). Replaces
#444 (closed: that fixed the resolved-layout cache, which is **not** on
this path).

## Root cause — scope, not caching

Sites resolve Header/Footer in the **app shell** (`app/layout.tsx`) via
`resolveValue`/`loadBlocks`, not as page sections. In App Router the
**root layout renders concurrently with the page**, and the draft
override is bound in the *page* scope (`createDecoPage` → `ensureDraft`
→ a React `cache()` slot). So when the shell resolves the Footer, the
override isn't bound yet → it renders **published** content, even though
page sections reflect the draft.

Verified by code-tracing on `faststore-fila`: `resolveFooterConfig()` →
`resolveValue({__resolveType:'Footer'})`, which calls `loadBlocks()` but
never touches the `resolvedLayoutCache` #444 targeted. It's the
layout-vs-page binding scope, exactly the caveat #409 documented — now
biting the shell.

## Fix — forward the pointer so the whole RSC tree can bind

A layout gets no `searchParams`, and on the entry request the
`__deco_draft` cookie has only just been set on the *response*. So
neither of `ensureDraft`'s existing sources works from a layout on
entry. This forwards the pointer as a **request header** the layout can
read:

- **`draftMiddleware`** forwards the active pointer on `x-deco-draft`
via `NextResponse.next({ request: { headers } })`. New
`draftRequestHeaders(request, decision)` helper for sites with their own
middleware. A client-forged header is stripped when the request isn't
previewing.
- **`ensureDraft()`** now reads the pointer from `param → forwarded
header → cookie`, so it binds correctly when called from a layout — on
both entry and navigation. Host gate unchanged.

`prepareDraft` still decides purely from param + cookie: the header is
an **output** of the gated decision, never an input. Not a new trust
surface — the pointer was never a secret (host-scoping bounds blast
radius; a forged header ≡ typing `?__draft=`).

## Site-side pattern (required)

The app shell must `await ensureDraft()` before resolving global
Header/Footer sections. It's idempotent and `cache()`-scoped, so calling
it in both the layout and the page is free:

```tsx
// app/layout.tsx
export default async function RootLayout({ children }) {
  await ensureSetup();
  if (isDraftPreviewEnabled()) await ensureDraft(); // binds from x-deco-draft
  const footer = await resolveValue({ __resolveType: "Footer" });
  return <Shell footer={<Footer {...footer} />}>{children}</Shell>;
}
```

## Tests

- `draftMiddleware.test.ts`: `draftRequestHeaders` forwards the pointer
(param + cookie cases) and strips a client-forged header when not
previewing.
- `draftShell.test.ts` (new): `ensureDraft()` binds from the forwarded
header with **no searchParams** (the layout case), still binds from the
cookie, no-ops with no source, and stays host-gated.

80 nextjs tests pass; typecheck clean; changed files pass biome (the
pre-existing `draftSlot` formatting nit on `main` is untouched).

## Honest validation caveats

- Verified via **unit tests + code-tracing**, not a full browser e2e:
the `nextjs-smoke` example is **pre-existingly broken** in this repo
state (unrelated — `packages/blocks/src/hooks/useLoadMore.ts` imports
React hooks without `"use client"`, so any server route pulling
`@decocms/blocks/hooks` 500s). Couldn't stand up a running Next harness
without first fixing that orthogonal bug.
- Targets the **pull-based draft** (`?__draft=`) flow. If a site
previews Header/Footer through the legacy **admin POST-render** flow
(`withBlocksOverride`, pre-#409), that's a different mechanism this
doesn't cover — the shell would need to render inside that override
scope. `faststore-fila`'s local checkout is on `7.20.7` (pre-#409);
worth confirming which preview its repro used.

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


<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Fixes Next.js app shell so Header/Footer reflect draft previews. We
forward the active draft pointer as `x-deco-draft` and let layouts bind
it via `ensureDraft`.

- **Bug Fixes**
- `draftMiddleware` now forwards the pointer on `x-deco-draft` using
`draftRequestHeaders`, and strips any forged header when not previewing.
- `ensureDraft` reads the pointer with precedence: param →
`x-deco-draft` → cookie; works from layouts with no `searchParams`. Host
gate remains enforced.
- Exported `DRAFT_HEADER` and added tests for header forwarding, layout
binding, and gating.

- **Migration**
- In `app/layout.tsx`, call `ensureDraft()` before resolving shell
sections (Header/Footer).
- If you have custom middleware, use `prepareDraft` →
`draftRequestHeaders` with `NextResponse.next({ request: { headers } })`
→ `applyDraft`.

<sup>Written for commit 663ae72.
Summary will update on new commits.</sup>

<a href="https://cubic.dev/pr/decocms/blocks/pull/445?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="Review in cubic"
src="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"></picture></a>

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

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant