Repository navigation
feat: pull-based draft preview - #409
Merged
Merged
Conversation
A site can now render its OWN pages against a Studio sandbox's working-tree draft, by fetching the merged decofile itself over a plain GET. This replaces pushing the decofile into a POST body at `/live/previews`. That only worked because deco's own runtime honours a POST render — Next.js and most frameworks render on GET only — and it could produce just one statically rendered component: no hydration, no navigation, and client components invoked server-side. Going through the site's real route fixes all three, and the payload is fetched once per version instead of re-sent on every navigation. Shape: `?__draft=<handle>@<version>` on any page URL. The site resolves the handle against a CONFIGURED origin suffix, so it never fetches a caller-supplied URL and there is no SSRF surface to defend. - `@decocms/blocks` — `draftSource`: pointer parsing, origin construction, fetch, and a bounded version cache. Framework-agnostic; binding a draft to a request is injected via `setDraftOverrideGetter`, the same shape as `setFastDeployKVGetter`, so the runtime keeps its zero-dependency direction. - `@decocms/nextjs` — `ensureDraft` (page-level) plus `prepareDraft`/`applyDraft` (middleware, on a `./middleware` subpath so the edge graph never imports the root barrel), wired into `createDecoPage`. Two findings worth stating, both measured rather than assumed: A layout's `await` does NOT gate its children — App Router renders them concurrently, so a layout-level resolve lands after sections have already read `loadBlocks()` and silently rendered published content. The resolve therefore belongs on the PAGE. Request scoping uses React `cache()`, not AsyncLocalStorage: `RequestContext.run` is never entered on Next, and ALS cannot wrap a component's children anyway. Verified with concurrent requests. Next reserves `Cache-Control` and `Vary` on dynamic responses and overwrites them from middleware AND from `next.config` `headers()`; the wire keeps `no-cache, must-revalidate`. Isolated with a marker header on the same rules, so this is Next owning those two names, not our rules failing to match. `no-cache` still forbids reuse without revalidating with the origin, so a shared cache cannot serve a draft to another visitor — but closing the gap fully needs a CDN-level rule at deploy time. `X-Robots-Tag` does get through. Inert unless BOTH `DECO_DRAFT_PREVIEW=1` and `DECO_SANDBOX_ORIGIN_SUFFIXES` are set, mirroring Fast Deploy's opt-in: upgrading the package must never be enough to start fetching from the network and rendering unpublished content. A test asserts `fetch` is never called when disabled, and that an unconfigured site never touches a dynamic API — otherwise every page would lose static/ISR rendering on upgrade.
Adds `rewriteToDraftRoute`, so a site can keep its real routes statically rendered while still serving drafts. `dynamic` and `revalidate` are STATIC route exports — a page cannot become dynamic for a single request. Without this, supporting drafts means making the real route dynamic, which costs every visitor their cached page and, worse, lets a statically rendered draft be cached and served to them. Rewriting sends only drafted requests to a route that is dynamic by construction; ordinary traffic gets null back and falls straight through, untouched. The prefix is `/_draft` at the URL level, but a site's directory for it must be URL-encoded (`app/%5Fdraft/...`). Next treats a literal `_` prefix as a private folder and excludes it from routing, so a rewrite to `/_draft/...` silently falls through to whatever catch-all follows and 404s. Verified the hard way. Documented on the constant so the next person doesn't repeat it. Guards against nesting the prefix if middleware re-runs on the rewritten URL, and does not rewrite when leaving draft mode. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… first A deployment can legitimately serve sandboxes from more than one origin (cluster and desktop-link), and a handle alone does not say which suffix it lives under. `resolveDraftDecofile` now tries the configured suffixes in order; a miss on one origin — unreachable, non-2xx, unparseable — falls through to the next instead of aborting the resolve. Previously only the first entry was consulted, silently, while the option read as a list. Also corrects the DRAFT_ROUTE_PREFIX doc, which claimed a literal `_draft` folder "cannot be exposed as a real page": true, but for the wrong reason — Next excludes `_`-prefixed folders from routing entirely, so the rewrite target must be mounted URL-encoded (`app/%5Fdraft/...`) or every drafted request 404s through the site's catch-all. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
`DECO_DRAFT_PREVIEW=1` becomes `DECO_DRAFT_PREVIEW_HOST=<host[,host…]>`. A boolean cannot express the common deployment shape: one build serving several domains, of which only the preview domain may render drafts. Host scoping makes the production domain structurally inert — `fila.com.br?__draft=` does nothing on the same build that previews on `fila.vtex.app` — while keeping the upgrade invariant: no host configured, feature completely inert, no dynamic API touched, static/ISR rendering untouched. The gate is enforced twice: middleware returns an inert decision on a non-allowed host (no cookie, no rewrite, no headers), and ensureDraft re-checks before binding — the header is read only once a pointer exists, so the check itself costs no dynamic rendering. Hosts match verbatim (port included) and case-insensitively against `x-forwarded-host ?? host ?? nextUrl.host`; the header is spoofable by direct-to-origin calls, but the sandbox handle remains the capability — host scoping bounds blast radius, it is not a secret. `DECO_SANDBOX_ORIGIN_SUFFIXES` now defaults to the deco-operated origins (.preview-studio.decocms.com, .local.studio.decocms.com, .localhost) and the env becomes an override. Shipping defaults adds no SSRF surface — the origin is still configuration, never caller input. BREAKING CHANGE: DECO_DRAFT_PREVIEW is removed; sites must set DECO_DRAFT_PREVIEW_HOST to enable draft preview. Beta-only surface. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
… env pair
Token v2: `?__draft=<host[:port]>@<version>` — the token now names WHERE the
draft lives, not just a bare label. Probing across configured suffixes is
gone: the authority is validated against `DECO_PREVIEW_API_DOMAINS`
(dot-prefixed suffix match, label-boundary safe) and the fetch goes to exactly
one origin. The token still never carries a scheme or path — a full URL would
be an SSRF vector — so `javascript:`/`file:`/URL-shaped tokens fail at parse
time; the scheme is derived from the matched domain, and an explicit port is
admitted only under localhost-ish domains, so a public-domain token cannot aim
at odd ports. This also dissolves the desktop-link dynamic-port problem:
Studio embeds the daemon origin's authority verbatim, no suffix override
needed. The version charset is now validated too (it is a cache key).
Env renames, detaching the sandbox vocabulary from the site-facing surface:
DECO_DRAFT_PREVIEW_HOST → DECO_ALLOWED_PREVIEW_HOSTS
DECO_SANDBOX_ORIGIN_SUFFIXES → DECO_PREVIEW_API_DOMAINS
Semantics unchanged: the host allowlist is the single opt-in (unset = fully
inert), the domains default to the deco-operated origins and an override
replaces the list. `handle` is gone from the public surface; DraftPointer is
`{ host, version }`.
BREAKING CHANGE: token format and both env names change. Beta-only surface.
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The opt-in moves into the repo: the global `site` block may declare `previewHosts` (e.g. ["fila.vtex.app", "localhost:3100"]), read once at setup from the BASE blocks and installed via setDraftPreviewHosts. Reviewed in a PR, versioned with branches, and shared with Studio — which reads the same block through the decofile it already fetches — so the value exists exactly once. Read at setup time on purpose, never via loadBlocks() at request time: the request path merges the draft override, and an allowlist readable through the override could be rewritten by the very draft it gates. DECO_ALLOWED_PREVIEW_HOSTS demotes to an operational escape hatch: when set it REPLACES the block hosts (kill a bad value without a deploy, add a machine-specific port); unset, the block is the source; neither → inert, so upgrading still enables nothing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
The first cut installed the site-block hosts lazily (inside ensureSetup) into plain module state — and the wire test failed both ways: pages call ensureDraft BEFORE they resolve CMS content, so the gate ran ahead of the install; and the middleware bundle is a separate module graph/runtime that never runs setup at all, so its copy of the allowlist stayed empty forever. Three-part fix, one lesson (module state does not travel): - hosts live on globalThis, the same pattern the block loader already uses against bundler-duplicated module instances; - createNextSetup installs them synchronously at module evaluation (the blocksDir mode still re-installs after its fs read); - prepareDraft hard-gates only when DECO_ALLOWED_PREVIEW_HOSTS is set — the env override keeps full kill-switch power — and otherwise passes through, leaving the page-side ensureDraft as the authoritative gate. Worst case on a non-preview host is a cookie the page gate then ignores. Verified on the wire with zero env: draft renders on the block-listed host, fila.com.br stays published on the same build. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
tlgimenes
force-pushed
the
feat/draft-preview
branch
from
July 29, 2026 13:24
a8e96e7 to
13704d1
Compare
A reviewer in a draft preview stays in preview across in-preview
navigation via the __deco_draft cookie, so after the first click the URL
no longer shows ?__draft= — it becomes easy to mistake unpublished
content for what is live. This adds an always-on floating badge whenever
a draft is bound, with the two actions a reviewer needs: leave preview,
or hand the exact draft version to someone else.
- DraftPreviewBadge ("use client"): self-contained pill (inline styles,
very high z-index, deco mark inlined as a data URI so it never 404s on
a consumer site). Opens a popover with "Exit preview" (navigates to
?__draft=off) and "Share preview" (copies the current URL carrying
?__draft=<host>@<version>, pinning the exact version). Pure URL
builders (buildShareUrl/buildExitUrl) are exported and unit-tested.
- DraftPreviewIndicator (Server Component): reads the request-scoped
pointer and mounts the badge ONLY when a draft is bound — nothing on a
published/unconfigured request.
- draft.ts: stash the active pointer in the request slot; new
getActiveDraftPointer(). draftConstants.ts holds DRAFT_PARAM/DRAFT_COOKIE
with zero server imports so the client badge can import them without
pulling next/headers into the client bundle.
- createDecoPage wires the indicator automatically (page subtree, after
bindDraftOnce — not a layout, whose children render concurrently).
Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ublished /deco/invoke is a separate request from the page render, so the page's request-scoped draft binding never reaches it. Client-fetched (lazy/ on-scroll) sections and self-fetched section loaders therefore resolved their loaders against PUBLISHED blocks while the page showed the draft — a reviewer would see a section "not update" and think their edit didn't take. Fix: handleInvoke re-resolves the draft from the request it received and binds it for the whole resolution. - blocks/draftSource: resolveDraftForRequest(request) — framework-agnostic, reads the pointer straight off the raw Request (?__draft= wins, the __deco_draft cookie carries navigation, off exits), applies the SAME gate as the page path (allowlist non-empty, request host allowed, pointer/origin valid, fetch ok). draftPointerFromRequest + the DRAFT_COOKIE_NAME/ DRAFT_QUERY_PARAM wire constants live here now. - blocks-admin/handleInvoke: wraps the resolution in withBlocksOverride when a draft resolves. AsyncLocalStorage-backed, so concurrent invokes each get their own override with no cross-request bleed (the layout-cache-race isolation, reused). Inert unless the gate passes — published path untouched, no network when disabled or cookieless. The __deco_draft cookie travels same-origin on the invoke fetch (SameSite=None; Secure), so the client-fetched path is covered. Tests: draftPointerFromRequest precedence, resolveDraftForRequest gating (off/ disabled/wrong-host/no-network), a handleInvoke integration test proving a loader sees draft vs published blocks, and a cross-package parity test pinning the cookie/param names (client-safe copy in nextjs vs the blocks owner). Co-Authored-By: Claude Opus 4.8 <[email protected]>
guitavano
approved these changes
Aug 3, 2026
|
🎉 This PR is included in version 8.0.0 🎉 The release is available on:
Your semantic-release bot 📦🚀 |
tlgimenes
added a commit
that referenced
this pull request
Aug 3, 2026
* feat: pull-based draft preview A site can now render its OWN pages against a Studio sandbox's working-tree draft, by fetching the merged decofile itself over a plain GET. This replaces pushing the decofile into a POST body at `/live/previews`. That only worked because deco's own runtime honours a POST render — Next.js and most frameworks render on GET only — and it could produce just one statically rendered component: no hydration, no navigation, and client components invoked server-side. Going through the site's real route fixes all three, and the payload is fetched once per version instead of re-sent on every navigation. Shape: `?__draft=<handle>@<version>` on any page URL. The site resolves the handle against a CONFIGURED origin suffix, so it never fetches a caller-supplied URL and there is no SSRF surface to defend. - `@decocms/blocks` — `draftSource`: pointer parsing, origin construction, fetch, and a bounded version cache. Framework-agnostic; binding a draft to a request is injected via `setDraftOverrideGetter`, the same shape as `setFastDeployKVGetter`, so the runtime keeps its zero-dependency direction. - `@decocms/nextjs` — `ensureDraft` (page-level) plus `prepareDraft`/`applyDraft` (middleware, on a `./middleware` subpath so the edge graph never imports the root barrel), wired into `createDecoPage`. Two findings worth stating, both measured rather than assumed: A layout's `await` does NOT gate its children — App Router renders them concurrently, so a layout-level resolve lands after sections have already read `loadBlocks()` and silently rendered published content. The resolve therefore belongs on the PAGE. Request scoping uses React `cache()`, not AsyncLocalStorage: `RequestContext.run` is never entered on Next, and ALS cannot wrap a component's children anyway. Verified with concurrent requests. Next reserves `Cache-Control` and `Vary` on dynamic responses and overwrites them from middleware AND from `next.config` `headers()`; the wire keeps `no-cache, must-revalidate`. Isolated with a marker header on the same rules, so this is Next owning those two names, not our rules failing to match. `no-cache` still forbids reuse without revalidating with the origin, so a shared cache cannot serve a draft to another visitor — but closing the gap fully needs a CDN-level rule at deploy time. `X-Robots-Tag` does get through. Inert unless BOTH `DECO_DRAFT_PREVIEW=1` and `DECO_SANDBOX_ORIGIN_SUFFIXES` are set, mirroring Fast Deploy's opt-in: upgrading the package must never be enough to start fetching from the network and rendering unpublished content. A test asserts `fetch` is never called when disabled, and that an unconfigured site never touches a dynamic API — otherwise every page would lose static/ISR rendering on upgrade. * feat(nextjs): divert drafted requests to a dynamic route Adds `rewriteToDraftRoute`, so a site can keep its real routes statically rendered while still serving drafts. `dynamic` and `revalidate` are STATIC route exports — a page cannot become dynamic for a single request. Without this, supporting drafts means making the real route dynamic, which costs every visitor their cached page and, worse, lets a statically rendered draft be cached and served to them. Rewriting sends only drafted requests to a route that is dynamic by construction; ordinary traffic gets null back and falls straight through, untouched. The prefix is `/_draft` at the URL level, but a site's directory for it must be URL-encoded (`app/%5Fdraft/...`). Next treats a literal `_` prefix as a private folder and excludes it from routing, so a rewrite to `/_draft/...` silently falls through to whatever catch-all follows and 404s. Verified the hard way. Documented on the constant so the next person doesn't repeat it. Guards against nesting the prefix if middleware re-runs on the rewritten URL, and does not rewrite when leaving draft mode. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(blocks): try every configured sandbox origin suffix, not only the first A deployment can legitimately serve sandboxes from more than one origin (cluster and desktop-link), and a handle alone does not say which suffix it lives under. `resolveDraftDecofile` now tries the configured suffixes in order; a miss on one origin — unreachable, non-2xx, unparseable — falls through to the next instead of aborting the resolve. Previously only the first entry was consulted, silently, while the option read as a list. Also corrects the DRAFT_ROUTE_PREFIX doc, which claimed a literal `_draft` folder "cannot be exposed as a real page": true, but for the wrong reason — Next excludes `_`-prefixed folders from routing entirely, so the rewrite target must be mounted URL-encoded (`app/%5Fdraft/...`) or every drafted request 404s through the site's catch-all. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat: gate draft preview by request host instead of a boolean `DECO_DRAFT_PREVIEW=1` becomes `DECO_DRAFT_PREVIEW_HOST=<host[,host…]>`. A boolean cannot express the common deployment shape: one build serving several domains, of which only the preview domain may render drafts. Host scoping makes the production domain structurally inert — `fila.com.br?__draft=` does nothing on the same build that previews on `fila.vtex.app` — while keeping the upgrade invariant: no host configured, feature completely inert, no dynamic API touched, static/ISR rendering untouched. The gate is enforced twice: middleware returns an inert decision on a non-allowed host (no cookie, no rewrite, no headers), and ensureDraft re-checks before binding — the header is read only once a pointer exists, so the check itself costs no dynamic rendering. Hosts match verbatim (port included) and case-insensitively against `x-forwarded-host ?? host ?? nextUrl.host`; the header is spoofable by direct-to-origin calls, but the sandbox handle remains the capability — host scoping bounds blast radius, it is not a secret. `DECO_SANDBOX_ORIGIN_SUFFIXES` now defaults to the deco-operated origins (.preview-studio.decocms.com, .local.studio.decocms.com, .localhost) and the env becomes an override. Shipping defaults adds no SSRF surface — the origin is still configuration, never caller input. Env change: DECO_DRAFT_PREVIEW is removed; sites must set DECO_DRAFT_PREVIEW_HOST to enable draft preview. Beta-only surface. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat: carry the content-API authority in the draft token; rename the env pair Token v2: `?__draft=<host[:port]>@<version>` — the token now names WHERE the draft lives, not just a bare label. Probing across configured suffixes is gone: the authority is validated against `DECO_PREVIEW_API_DOMAINS` (dot-prefixed suffix match, label-boundary safe) and the fetch goes to exactly one origin. The token still never carries a scheme or path — a full URL would be an SSRF vector — so `javascript:`/`file:`/URL-shaped tokens fail at parse time; the scheme is derived from the matched domain, and an explicit port is admitted only under localhost-ish domains, so a public-domain token cannot aim at odd ports. This also dissolves the desktop-link dynamic-port problem: Studio embeds the daemon origin's authority verbatim, no suffix override needed. The version charset is now validated too (it is a cache key). Env renames, detaching the sandbox vocabulary from the site-facing surface: DECO_DRAFT_PREVIEW_HOST → DECO_ALLOWED_PREVIEW_HOSTS DECO_SANDBOX_ORIGIN_SUFFIXES → DECO_PREVIEW_API_DOMAINS Semantics unchanged: the host allowlist is the single opt-in (unset = fully inert), the domains default to the deco-operated origins and an override replaces the list. `handle` is gone from the public surface; DraftPointer is `{ host, version }`. Env change: token format and both env names change. Beta-only surface. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(blocks): source the preview-host allowlist from the site block The opt-in moves into the repo: the global `site` block may declare `previewHosts` (e.g. ["fila.vtex.app", "localhost:3100"]), read once at setup from the BASE blocks and installed via setDraftPreviewHosts. Reviewed in a PR, versioned with branches, and shared with Studio — which reads the same block through the decofile it already fetches — so the value exists exactly once. Read at setup time on purpose, never via loadBlocks() at request time: the request path merges the draft override, and an allowlist readable through the override could be rewritten by the very draft it gates. DECO_ALLOWED_PREVIEW_HOSTS demotes to an operational escape hatch: when set it REPLACES the block hosts (kill a bad value without a deploy, add a machine-specific port); unset, the block is the source; neither → inert, so upgrading still enables nothing. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * fix(blocks): survive the middleware/server module-graph split The first cut installed the site-block hosts lazily (inside ensureSetup) into plain module state — and the wire test failed both ways: pages call ensureDraft BEFORE they resolve CMS content, so the gate ran ahead of the install; and the middleware bundle is a separate module graph/runtime that never runs setup at all, so its copy of the allowlist stayed empty forever. Three-part fix, one lesson (module state does not travel): - hosts live on globalThis, the same pattern the block loader already uses against bundler-duplicated module instances; - createNextSetup installs them synchronously at module evaluation (the blocksDir mode still re-installs after its fs read); - prepareDraft hard-gates only when DECO_ALLOWED_PREVIEW_HOSTS is set — the env override keeps full kill-switch power — and otherwise passes through, leaving the page-side ensureDraft as the authoritative gate. Worst case on a non-preview host is a cookie the page gate then ignores. Verified on the wire with zero env: draft renders on the block-listed host, fila.com.br stays published on the same build. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> * feat(nextjs): preview-mode badge for draft renders A reviewer in a draft preview stays in preview across in-preview navigation via the __deco_draft cookie, so after the first click the URL no longer shows ?__draft= — it becomes easy to mistake unpublished content for what is live. This adds an always-on floating badge whenever a draft is bound, with the two actions a reviewer needs: leave preview, or hand the exact draft version to someone else. - DraftPreviewBadge ("use client"): self-contained pill (inline styles, very high z-index, deco mark inlined as a data URI so it never 404s on a consumer site). Opens a popover with "Exit preview" (navigates to ?__draft=off) and "Share preview" (copies the current URL carrying ?__draft=<host>@<version>, pinning the exact version). Pure URL builders (buildShareUrl/buildExitUrl) are exported and unit-tested. - DraftPreviewIndicator (Server Component): reads the request-scoped pointer and mounts the badge ONLY when a draft is bound — nothing on a published/unconfigured request. - draft.ts: stash the active pointer in the request slot; new getActiveDraftPointer(). draftConstants.ts holds DRAFT_PARAM/DRAFT_COOKIE with zero server imports so the client badge can import them without pulling next/headers into the client bundle. - createDecoPage wires the indicator automatically (page subtree, after bindDraftOnce — not a layout, whose children render concurrently). Co-Authored-By: Claude Opus 4.8 <[email protected]> * fix(blocks): bind the draft on /deco/invoke so lazy sections aren't published /deco/invoke is a separate request from the page render, so the page's request-scoped draft binding never reaches it. Client-fetched (lazy/ on-scroll) sections and self-fetched section loaders therefore resolved their loaders against PUBLISHED blocks while the page showed the draft — a reviewer would see a section "not update" and think their edit didn't take. Fix: handleInvoke re-resolves the draft from the request it received and binds it for the whole resolution. - blocks/draftSource: resolveDraftForRequest(request) — framework-agnostic, reads the pointer straight off the raw Request (?__draft= wins, the __deco_draft cookie carries navigation, off exits), applies the SAME gate as the page path (allowlist non-empty, request host allowed, pointer/origin valid, fetch ok). draftPointerFromRequest + the DRAFT_COOKIE_NAME/ DRAFT_QUERY_PARAM wire constants live here now. - blocks-admin/handleInvoke: wraps the resolution in withBlocksOverride when a draft resolves. AsyncLocalStorage-backed, so concurrent invokes each get their own override with no cross-request bleed (the layout-cache-race isolation, reused). Inert unless the gate passes — published path untouched, no network when disabled or cookieless. The __deco_draft cookie travels same-origin on the invoke fetch (SameSite=None; Secure), so the client-fetched path is covered. Tests: draftPointerFromRequest precedence, resolveDraftForRequest gating (off/ disabled/wrong-host/no-network), a handleInvoke integration test proving a loader sees draft vs published blocks, and a cross-package parity test pinning the cookie/param names (client-safe copy in nextjs vs the blocks owner). Co-Authored-By: Claude Opus 4.8 <[email protected]> --------- Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: guitavano <[email protected]>
guitavano
added a commit
that referenced
this pull request
Aug 6, 2026
Ports the `?__draft=` **pull-based draft preview** — shipped for Next.js in #409 — to the **TanStack Start / Cloudflare Workers** binding. A site renders its own real pages against a Studio sandbox's working-tree draft, fetching the merged decofile itself over a plain `GET`, keyed by version. The framework-agnostic motor already lives in `@decocms/blocks`'s `draftSource` (token parsing, origin validation, fetch, version cache, host allowlist), and the `/deco/invoke` path already honours drafts via `blocks-admin`. This PR is the missing **page-render half** for TanStack. ## Why this is smaller than the Next port Two App Router constraints that #409 had to fight simply don't exist on Workers: 1. **Request scope.** Next backs the per-request draft slot with React `cache()` and has the awkward "await `ensureDraft` from the *page*, not a layout" rule. TanStack already wraps every request in `RequestContext.run`, so the resolved draft rides the request bag and `loadBlocks()` reads it back through the injected `getRequestDraftOverride` getter — no `cache()`, no page-vs-layout rule. 2. **Static-vs-dynamic rewrite.** Next rewrites drafted requests onto an encoded `app/%5Fdraft/…` route to escape ISR (`dynamic`/`revalidate` are static route exports). The worker decides cacheability per request, so a drafted request simply **bypasses the edge cache** — no rewrite. Deferred/lazy sections (`/deco/invoke`) already bind drafts through the shared `blocks-admin` handler, so that known-follow-up from #409 is covered here for free. ## What's in it New `packages/tanstack/src/sdk/draft.ts`: - `registerDraftOverride` — DI getter into `@decocms/blocks` reading the `RequestContext` bag - `installPreviewHostsFromBlocks` — sync the `site.previewHosts` allowlist from the base decofile (via `onChange`, never request-time merged blocks) - `requestCarriesDraft` — pure, network-free edge-cache-bypass predicate - `bindRequestDraft` — resolve + bind the draft to the request before render - `applyDraftCookieAndHeaders` — navigation cookie (`SameSite=None; Secure; HttpOnly; Partitioned`) + `no-store` / `Vary: Cookie` / `X-Robots-Tag: noindex` `workerEntry.ts` wiring: - install once in `createDecoWorkerEntry` (idempotent) - `bindRequestDraft` inside `RequestContext.run`, before the render, so every `loadBlocks()` in the call stack sees the merged decofile - stamp cookie + anti-leak headers on the final response - **bug fix in `isCacheable`**: it was bypassing on a `__deco_draft` *query param* that never exists — the entry param is `__draft` and `__deco_draft` is the *cookie*. Now uses `requestCarriesDraft` (param **or** cookie, host-gated). - bypass the POST `_serverFn` edge cache for drafted SPA navigation (its body-hash key doesn't vary on the cookie, so it would otherwise leak drafts / serve stale published) ## Gating Fully inert unless the site opts in — the `site` block's `previewHosts`, or the `DECO_ALLOWED_PREVIEW_HOSTS` override, must name the request's host. Upgrading the package can never start rendering unpublished content. A `?__draft=` on a non-preview host is structurally inert (no render, no cookie, not even a cache bypass). ## Tests - `sdk/draft.test.ts` — 16 unit tests: `requestCarriesDraft`, `bindRequestDraft` (entry / cookie-nav / resolve-failure-still-uncacheable / off / disallowed host), cookie + header application, host install. - `sdk/workerEntry.test.ts` — 4 end-to-end tests through `createDecoWorkerEntry` proving a drafted request binds the merged decofile into the render, bypasses the edge cache, and stamps the anti-leak cookie/headers — and stays inert on non-preview hosts and unconfigured builds. 157/157 tanstack tests pass; `typecheck` clean; new files pass `biome`. (Pre-existing `lint`/`knip` noise on `main` is untouched.) ## Follow-ups (not in this PR) - Preview badge/indicator (`DraftPreviewBadge`/`DraftPreviewIndicator`) still lives only in `@decocms/nextjs`; if we want the same visual "you're in preview" chip on TanStack it should be promoted to a shared spot. - No new site-facing docs yet; wiring is automatic inside `createDecoWorkerEntry`, so sites need no code changes beyond setting `previewHosts` / the env. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Adds pull-based draft preview to TanStack Start/Cloudflare Workers and promotes a shared preview badge used by both bindings. Drafts bind per request, persist via a secure cookie across navigation, bypass edge caches, and are never indexed. - **New Features** - Bind resolved drafts to the request via `RequestContext` so `loadBlocks()` reads the merged decofile. - Auto-install preview host allowlist from base blocks; also respects `DECO_ALLOWED_PREVIEW_HOSTS`. - Keep drafted requests out of edge cache using `requestCarriesDraft` (param or cookie, host-gated). - Apply secure cookie and headers on preview: `no-store`, `Vary: Cookie`, `X-Robots-Tag: noindex`. - Auto-wired in `createDecoWorkerEntry` (register getter, bind before render, stamp headers). - Shared preview badge moved to `@decocms/blocks/preview`; `@decocms/nextjs` re-exports it. - New TanStack `DraftPreviewIndicator` mounts in `DecoRootLayout`; hydration-safe and hidden in Studio iframes; provides share/exit actions. - Inert unless the request host is allowlisted; upgrading alone won’t expose drafts. - **Bug Fixes** - `isCacheable` now keys off `requestCarriesDraft` (real `?__draft` or `__deco_draft` cookie), not a non-existent `__deco_draft` param. - Drafted POST `_serverFn` calls bypass the edge cache to prevent leaks and stale responses. - Decode the `__deco_draft` cookie so the badge’s share link doesn’t double-encode the pointer. - Merge `Vary` non-destructively; append `Cookie` without dropping existing tokens (e.g. `Accept-Encoding`). <sup>Written for commit 3274a46. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/442?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]>
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]>
guitavano
added a commit
that referenced
this pull request
Aug 7, 2026
## Problem The pull-based `?__draft=` preview (TanStack #442, Next #409) merges the Studio sandbox decofile on top of the site's published blocks in `loadBlocks()`. But the two decofiles **disagree on how block keys spell special characters**: | | `/` (home) block key | |---|---| | Published (`/.decofile`, the base) | `pages-Home%20(principal)-287364` (percent-encoded) | | Studio draft sandbox (`_sandbox/decofile`, the override) | `pages-Home (principal)-287364` (raw) | The merge was a literal key-merge: ```js const merged = { ...blockData }; // base key: "...%20..." merged[key] = value; // override key: "... ..." → ADDS, never REPLACES ``` So the raw-keyed draft block was **added alongside** the encoded published block, leaving **two `pages-` blocks with the same `.path`**. `findPageByPath` returns the first match in `getAllPages()` order — the published block was already in `blockData`, the draft was appended after, so ties resolve to **published**. The draft edit silently never rendered: preview badge showed, `no-store`/`noindex`/cookie/edge-cache-bypass were all correct, but the page content stayed published. ## Impact Measured against casaevideo's live published vs sandbox decofiles: **78 of 107 pages (~73%)** were affected — every page whose block name contains a space or accent (`Home (principal)`, `Afiliados - Performance`, …). The 29 pages with plain ASCII keys (`disney`, `login`, `natal`, `ofertas`) worked, which is exactly why it looked intermittent. All 70 special-char blocks in the sandbox URL-decode to the published key 1:1 — a systematic encoding contract mismatch, not a fluke. ## Fix Canonicalise base keys with `decodeURIComponent` when applying an override, so an override block finds and displaces its differently-encoded twin (a `null` override removes it too). Defensive: a malformed `%` sequence falls back to the raw key rather than throwing. Exact-match keys — including the admin `withBlocksOverride` partial-render path — are byte-for-byte unchanged. ## Tests 3 new regression tests in `loader.test.ts` (home encoded-vs-raw twin collapses to one block rendering the draft; plain keys still replace; `null` draft removes the encoded twin). Full `@decocms/blocks` suite green: **1396/1396**, typecheck clean. ## Follow-up (not here, cross-repo) The root contract mismatch is that preview-studio emits raw block keys while the published decofile encodes them. Aligning the source is worth doing separately; this framework-side canonicalisation is the defensive fix at the deterministic merge chokepoint (and an override *should* always replace, never duplicate). 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated description by cubic. --> --- ## Summary by cubic Fixes draft preview merging by matching override blocks to base blocks using percent-decoded keys, so raw Studio keys replace their encoded published twins. Restores draft rendering for pages with spaces/accents without changing exact-match override behavior. - **Bug Fixes** - Decode base block keys when merging `?__draft=` overrides; fall back to raw key on decode errors. - Overrides replace or delete the encoded twin to avoid duplicate `pages-` entries. - Added regression tests for home (encoded vs raw), plain keys, and null delete. <sup>Written for commit e2f66ec. Summary will update on new commits.</sup> <a href="https://cubic.dev/pr/decocms/blocks/pull/450?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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Pull-based draft preview: a site renders its own pages against a Studio sandbox's working-tree draft, fetching the merged decofile itself over a plain GET.
Paired with
decocms/studio#5363(daemon servesGET /_sandbox/decofile, Studio builds the pointer) anddeco-sites/faststore-fila#271(first adopter). Published as7.28.0-beta.3under thebetadist-tag.Why
The old flow POSTed the decofile to
/live/previews. Three structural problems: only deco's own runtime honours a POST render (Next renders on GET); it produced one statically-rendered component — no hydration, no navigation, and client components invoked server-side (renderToStringcannot call Next's client-reference proxies); and it re-sent a multi-MB payload on every navigation. Pull fixes all three — the payload is fetched once per version.Shape
The token carries an authority, never a URL — no scheme, no path, so
javascript:/file:/URL-shaped tokens fail at parse time and the domain allowlist decides what may be fetched. Scheme is derived (http only for localhost-ish domains, where an explicit port is also admitted — which is how the desktop link's per-run port travels in the token).<version>is the daemon's content ETag; a save mints a new version, which is what refreshes the frame.Gating: host allowlist, not a boolean
DECO_ALLOWED_PREVIEW_HOSTS=fila.vtex.app,localhost:3100— only listed request hosts render drafts. One build commonly serves several domains; host scoping makes the production domain structurally inert:fila.com.br?__draft=does nothing on the same build that previews onfila.vtex.app. Verified on the wire — identical URL, same server: draft under an allowedHost, published (and no cookie) otherwise.ensureDraftre-checks before binding. The host header is spoofable direct-to-origin, but the sandbox handle is the capability — this bounds blast radius, it is not a secret.DECO_PREVIEW_API_DOMAINSnow defaults to the deco-operated origins (.preview-studio.decocms.com,.local.studio.decocms.com,.localhost); the env is an override (e.g. a ported local link.localhost:60534). Defaults add no SSRF surface — origins remain configuration, never caller input.Integration surface
ensureDraft(searchParams)is the primary API — await it in every entry point that resolves CMS content (page andgenerateMetadata; they race). It lives on the page, not a layout: a layout'sawaitdoes not gate its children (measured — App Router renders them concurrently). Request scoping is Reactcache();RequestContext.runis never entered on Next and ALS can't wrap a component's children.Middleware (
@decocms/nextjs/middleware, own subpath so the edge graph never pulls the root barrel):prepareDraft/applyDraft(cookie lifecycle —?__draft=enters, cookie carries navigation,offexits — plus no-store/noindex headers; cookie isSameSite=None; Secure; HttpOnly; Partitionedsince the preview iframe is cross-site), andrewriteToDraftRoutefor statically rendered routes only (a static draft render would be cached for real visitors). The rewrite target must be mounted URL-encoded (app/%5Fdraft/…) — a literal_draftfolder is a Next private folder, excluded from routing.createDecoPageis also wired, but a usage survey found its only consumer is this repo's smoke example — real sites hand-roll routes, which is whyensureDraftis the documented path.Safety & failure modes
Every failure path (malformed pointer incl.
a@b@c, disallowed host, unreachable origin, non-2xx, bad JSON) degrades to published. Version cache is bounded (3 entries; multi-MB payloads). Measured limit: Next reservesCache-Control/Varyon dynamic responses (overwrites middleware andnext.configheaders()); the wire keepsno-cache, must-revalidate, which still forbids reuse without revalidation — a CDN-level rule is recommended before production.X-Robots-Taggets through.Testing
673 tests across the two packages: host allow/deny, suffix defaults + fallback order, cookie, rewrite, gate-never-touches-dynamic-APIs. Verified end-to-end against a real sandbox daemon serving a real store's 440 blocks: entry, cookie navigation, stale-cookie override,
?__draft=off, concurrent distinct drafts, and the host gate above.Known follow-ups (not in this PR)
/deco/invoke, which does not bind drafts — client-fetched sections render published content..releaserc.jsonhas no prerelease channel; betas were published manually.bun run lintalready fails on cleanmain(unrelated files); this branch doesn't add to it.