@decocms/blocks 8.10.0 → 8.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (210) hide show
  1. package/dist/index.d.ts +1 -1
  2. package/dist/index.d.ts.map +1 -1
  3. package/dist/index.js.map +1 -1
  4. package/dist/protocol/conformance/blockMetaVectors.json +80 -0
  5. package/dist/protocol/index.d.ts +5 -2
  6. package/dist/protocol/index.d.ts.map +1 -1
  7. package/dist/protocol/index.js +5 -2
  8. package/dist/protocol/index.js.map +1 -1
  9. package/dist/v8/blockMeta.d.ts +33 -4
  10. package/dist/v8/blockMeta.d.ts.map +1 -1
  11. package/dist/v8/blockMeta.js +70 -13
  12. package/dist/v8/blockMeta.js.map +1 -1
  13. package/dist/v8/cli/index.d.ts +1 -0
  14. package/dist/v8/cli/index.d.ts.map +1 -1
  15. package/dist/v8/cli/index.js +1 -0
  16. package/dist/v8/cli/index.js.map +1 -1
  17. package/dist/v8/cli/run.d.ts +2 -0
  18. package/dist/v8/cli/run.d.ts.map +1 -1
  19. package/dist/v8/cli/run.js +30 -1
  20. package/dist/v8/cli/run.js.map +1 -1
  21. package/dist/v8/cli/skills.d.ts +25 -0
  22. package/dist/v8/cli/skills.d.ts.map +1 -0
  23. package/dist/v8/cli/skills.js +70 -0
  24. package/dist/v8/cli/skills.js.map +1 -0
  25. package/dist/v8/client.d.ts +6 -4
  26. package/dist/v8/client.d.ts.map +1 -1
  27. package/dist/v8/client.js +26 -70
  28. package/dist/v8/client.js.map +1 -1
  29. package/dist/v8/cms.d.ts.map +1 -1
  30. package/dist/v8/cms.js +1 -2
  31. package/dist/v8/cms.js.map +1 -1
  32. package/dist/v8/contentIndex.d.ts +18 -7
  33. package/dist/v8/contentIndex.d.ts.map +1 -1
  34. package/dist/v8/contentIndex.js +46 -17
  35. package/dist/v8/contentIndex.js.map +1 -1
  36. package/dist/v8/draftChanges.d.ts.map +1 -1
  37. package/dist/v8/draftChanges.js +4 -1
  38. package/dist/v8/draftChanges.js.map +1 -1
  39. package/dist/v8/index.d.ts +1 -1
  40. package/dist/v8/index.d.ts.map +1 -1
  41. package/dist/v8/remoteLoader.d.ts +4 -2
  42. package/dist/v8/remoteLoader.d.ts.map +1 -1
  43. package/dist/v8/remoteLoader.js +13 -3
  44. package/dist/v8/remoteLoader.js.map +1 -1
  45. package/dist/v8/types.d.ts +47 -7
  46. package/dist/v8/types.d.ts.map +1 -1
  47. package/package.json +3 -2
  48. package/skills/deco-apps/SKILL.md +82 -0
  49. package/skills/deco-apps/references/algolia.md +51 -0
  50. package/skills/deco-apps/references/commerce-types.md +132 -0
  51. package/skills/deco-apps/references/instrumented-fetch.md +144 -0
  52. package/skills/deco-apps/references/magento.md +55 -0
  53. package/skills/deco-apps/references/messaging.md +76 -0
  54. package/skills/deco-apps/references/shopify.md +69 -0
  55. package/skills/deco-apps/references/vendored-loaders.md +135 -0
  56. package/skills/deco-apps/references/vtex-cookies-auth.md +146 -0
  57. package/skills/deco-apps/references/vtex.md +150 -0
  58. package/skills/deco-apps/references/wake.md +75 -0
  59. package/skills/deco-cms-schema/SKILL.md +80 -0
  60. package/skills/deco-cms-schema/references/annotations.md +147 -0
  61. package/skills/deco-cms-schema/references/content-hygiene.md +91 -0
  62. package/skills/deco-cms-schema/references/formats-and-widgets.md +112 -0
  63. package/skills/deco-cms-schema/references/shapes-that-break-the-form.md +165 -0
  64. package/skills/deco-cms-schema/references/types-to-fields.md +112 -0
  65. package/skills/deco-go-live/SKILL.md +127 -0
  66. package/skills/deco-go-live/references/content-releases.md +90 -0
  67. package/skills/deco-go-live/references/process.md +106 -0
  68. package/skills/deco-go-live/references/proxy-headers-checkout.md +139 -0
  69. package/skills/deco-go-live/references/qa-checklist-template.md +150 -0
  70. package/skills/deco-go-live/references/qa-inventory.md +120 -0
  71. package/skills/deco-go-live/references/react-spa.md +183 -0
  72. package/skills/deco-go-live/references/seo-analytics.md +114 -0
  73. package/skills/deco-go-live/references/traffic-ramp.md +87 -0
  74. package/skills/deco-go-live/references/worker-runtime.md +93 -0
  75. package/skills/deco-go-live/scripts/preflight.sh +221 -0
  76. package/skills/deco-images-media/SKILL.md +64 -0
  77. package/skills/deco-images-media/references/asset-upload.md +191 -0
  78. package/skills/deco-images-media/references/components-per-binding.md +167 -0
  79. package/skills/deco-images-media/references/providers-and-cdn.md +145 -0
  80. package/skills/deco-images-media/references/quality-and-lcp.md +93 -0
  81. package/skills/deco-images-media/references/troubleshooting.md +147 -0
  82. package/skills/deco-images-media/references/video.md +122 -0
  83. package/skills/deco-make-editable/SKILL.md +94 -0
  84. package/skills/deco-make-editable/references/a11y-and-e2e.md +104 -0
  85. package/skills/deco-make-editable/references/content-shapes.md +203 -0
  86. package/skills/deco-make-editable/references/from-figma.md +110 -0
  87. package/skills/deco-make-editable/references/i18n-fields.md +112 -0
  88. package/skills/deco-make-editable/references/inventory.md +79 -0
  89. package/skills/deco-make-editable/references/pixel-parity.md +175 -0
  90. package/skills/deco-make-editable/references/seeding-content.md +119 -0
  91. package/skills/deco-nextjs-site/SKILL.md +74 -0
  92. package/skills/deco-nextjs-site/references/caching.md +116 -0
  93. package/skills/deco-nextjs-site/references/metadata-seo.md +100 -0
  94. package/skills/deco-nextjs-site/references/proxy-and-drafts.md +177 -0
  95. package/skills/deco-nextjs-site/references/rendering.md +172 -0
  96. package/skills/deco-nextjs-site/references/setup.md +190 -0
  97. package/skills/deco-nextjs-site/references/studio-bridge.md +130 -0
  98. package/skills/deco-site-authoring/SKILL.md +75 -0
  99. package/skills/deco-site-authoring/references/lazy-blocks.md +155 -0
  100. package/skills/deco-site-authoring/references/loaders.md +192 -0
  101. package/skills/deco-site-authoring/references/pages.md +158 -0
  102. package/skills/deco-site-authoring/references/review-before-publish.md +95 -0
  103. package/skills/deco-site-authoring/references/sections.md +158 -0
  104. package/skills/deco-site-authoring/references/seo.md +116 -0
  105. package/skills/deco-site-workflow/SKILL.md +101 -0
  106. package/skills/deco-site-workflow/references/check.md +116 -0
  107. package/skills/deco-site-workflow/references/cli-reference.md +106 -0
  108. package/skills/deco-site-workflow/references/content-layout.md +93 -0
  109. package/skills/deco-site-workflow/references/content-sync.md +146 -0
  110. package/skills/deco-site-workflow/references/delivery.md +51 -0
  111. package/skills/deco-site-workflow/references/deploy.md +87 -0
  112. package/skills/deco-site-workflow/references/schema.md +173 -0
  113. package/skills/deco-site-workflow/references/serve-and-studio.md +138 -0
  114. package/skills/deco-storefront-caching/SKILL.md +67 -0
  115. package/skills/deco-storefront-caching/references/cache-keys.md +129 -0
  116. package/skills/deco-storefront-caching/references/case-study.md +82 -0
  117. package/skills/deco-storefront-caching/references/egress-traps.md +153 -0
  118. package/skills/deco-storefront-caching/references/nextjs.md +60 -0
  119. package/skills/deco-storefront-caching/references/perf-guardrails-e2e.md +123 -0
  120. package/skills/deco-storefront-caching/references/verification.md +136 -0
  121. package/skills/deco-storefront-caching/references/worker-page-cache.md +160 -0
  122. package/skills/deco-storefront-caching/scripts/html-anatomy.mjs +97 -0
  123. package/skills/deco-storefront-performance/SKILL.md +81 -0
  124. package/skills/deco-storefront-performance/references/cls-third-party.md +90 -0
  125. package/skills/deco-storefront-performance/references/hydration.md +116 -0
  126. package/skills/deco-storefront-performance/references/loaders-n-plus-1.md +107 -0
  127. package/skills/deco-storefront-performance/references/navigation-ux.md +130 -0
  128. package/skills/deco-storefront-performance/references/payload-trim.md +163 -0
  129. package/skills/deco-storefront-performance/references/render-location.md +152 -0
  130. package/skills/deco-storefront-performance/references/request-dedupe.md +147 -0
  131. package/skills/deco-storefront-performance/references/trace-reading.md +79 -0
  132. package/skills/deco-storefront-performance/references/worker-memory.md +176 -0
  133. package/skills/deco-tanstack-site/SKILL.md +68 -0
  134. package/skills/deco-tanstack-site/references/document-and-security.md +155 -0
  135. package/skills/deco-tanstack-site/references/router-and-navigation.md +137 -0
  136. package/skills/deco-tanstack-site/references/routes-and-pages.md +183 -0
  137. package/skills/deco-tanstack-site/references/server-functions.md +123 -0
  138. package/skills/deco-tanstack-site/references/setup.md +153 -0
  139. package/skills/deco-tanstack-site/references/worker-entry.md +152 -0
  140. package/skills/deco-v7-to-v8-migration/SKILL.md +123 -0
  141. package/skills/deco-v7-to-v8-migration/references/caching-and-privacy.md +10 -0
  142. package/skills/deco-v7-to-v8-migration/references/content.md +25 -0
  143. package/skills/deco-v7-to-v8-migration/references/editor-forms.md +27 -0
  144. package/skills/deco-v7-to-v8-migration/references/faststore.md +40 -0
  145. package/skills/deco-v7-to-v8-migration/references/framework-code.md +53 -0
  146. package/skills/deco-v7-to-v8-migration/references/hosted-releases.md +16 -0
  147. package/skills/deco-v7-to-v8-migration/references/import-map.md +81 -0
  148. package/skills/deco-v7-to-v8-migration/references/legacy-names.md +33 -0
  149. package/skills/deco-v7-to-v8-migration/references/manual-steps.md +10 -0
  150. package/skills/deco-v7-to-v8-migration/references/native-apps.md +43 -0
  151. package/skills/deco-v7-to-v8-migration/references/nextjs.md +19 -0
  152. package/skills/deco-v7-to-v8-migration/references/parity.md +66 -0
  153. package/skills/deco-v7-to-v8-migration/references/rendering.md +13 -0
  154. package/skills/deco-v7-to-v8-migration/references/running-the-script.md +29 -0
  155. package/skills/deco-v7-to-v8-migration/references/script-steps.md +13 -0
  156. package/skills/deco-v7-to-v8-migration/references/server-functions.md +15 -0
  157. package/skills/deco-v7-to-v8-migration/references/sibling-port.md +11 -0
  158. package/skills/deco-v7-to-v8-migration/references/site-code.md +15 -0
  159. package/skills/deco-v7-to-v8-migration/references/telemetry.md +10 -0
  160. package/skills/deco-v7-to-v8-migration/references/verify.md +23 -0
  161. package/skills/deco-v7-to-v8-migration/scripts/apps.ts +297 -0
  162. package/skills/deco-v7-to-v8-migration/scripts/asyncRendering.ts +73 -0
  163. package/skills/deco-v7-to-v8-migration/scripts/blockMap.ts +584 -0
  164. package/skills/deco-v7-to-v8-migration/scripts/checkContentReads.ts +32 -0
  165. package/skills/deco-v7-to-v8-migration/scripts/ciSchemaCheck.ts +145 -0
  166. package/skills/deco-v7-to-v8-migration/scripts/compat.ts +357 -0
  167. package/skills/deco-v7-to-v8-migration/scripts/content.ts +121 -0
  168. package/skills/deco-v7-to-v8-migration/scripts/contentReads.ts +157 -0
  169. package/skills/deco-v7-to-v8-migration/scripts/experiments.ts +81 -0
  170. package/skills/deco-v7-to-v8-migration/scripts/framework.ts +61 -0
  171. package/skills/deco-v7-to-v8-migration/scripts/imageCopy.ts +276 -0
  172. package/skills/deco-v7-to-v8-migration/scripts/imageModule.ts +285 -0
  173. package/skills/deco-v7-to-v8-migration/scripts/imports.ts +942 -0
  174. package/skills/deco-v7-to-v8-migration/scripts/invoke.ts +624 -0
  175. package/skills/deco-v7-to-v8-migration/scripts/legacyNames.ts +45 -0
  176. package/skills/deco-v7-to-v8-migration/scripts/main.ts +59 -0
  177. package/skills/deco-v7-to-v8-migration/scripts/matchers.ts +41 -0
  178. package/skills/deco-v7-to-v8-migration/scripts/migrate.ts +180 -0
  179. package/skills/deco-v7-to-v8-migration/scripts/redirects.ts +455 -0
  180. package/skills/deco-v7-to-v8-migration/scripts/report.ts +50 -0
  181. package/skills/deco-v7-to-v8-migration/scripts/scaffold.ts +1119 -0
  182. package/skills/deco-v7-to-v8-migration/scripts/secrets.ts +35 -0
  183. package/skills/deco-v7-to-v8-migration/scripts/sectionLoaders.ts +216 -0
  184. package/skills/deco-v7-to-v8-migration/scripts/siteSettings.ts +261 -0
  185. package/skills/deco-v7-to-v8-migration/scripts/stubs.ts +388 -0
  186. package/skills/deco-v7-to-v8-migration/scripts/tsconfig.json +7 -0
  187. package/skills/deco-v7-to-v8-migration/scripts/vendor.ts +249 -0
  188. package/skills/deco-v7-to-v8-migration/scripts/vtexInvoke.ts +240 -0
  189. package/skills/deco-v7-to-v8-migration/scripts/walk.ts +30 -0
  190. package/skills/deco-variants/SKILL.md +57 -0
  191. package/skills/deco-variants/references/caching-variants.md +63 -0
  192. package/skills/deco-variants/references/custom-matchers.md +83 -0
  193. package/skills/deco-variants/references/draft-preview.md +59 -0
  194. package/skills/deco-variants/references/experiments-and-campaigns.md +104 -0
  195. package/skills/deco-variants/references/multivariate.md +85 -0
  196. package/skills/deco-variants/references/v7-matchers.md +71 -0
  197. package/src/index.ts +1 -1
  198. package/src/protocol/conformance/blockMetaVectors.json +80 -0
  199. package/src/protocol/index.ts +8 -1
  200. package/src/v8/blockMeta.ts +75 -11
  201. package/src/v8/cli/index.ts +1 -0
  202. package/src/v8/cli/run.ts +35 -1
  203. package/src/v8/cli/skills.ts +91 -0
  204. package/src/v8/client.ts +32 -77
  205. package/src/v8/cms.ts +1 -2
  206. package/src/v8/contentIndex.ts +49 -19
  207. package/src/v8/draftChanges.ts +5 -1
  208. package/src/v8/index.ts +1 -1
  209. package/src/v8/remoteLoader.ts +13 -3
  210. package/src/v8/types.ts +48 -7
@@ -0,0 +1,136 @@
1
+ # Verifying cache and egress changes
2
+
3
+ Run these after every change, in order. A page that is never stored (trap 1) makes the later
4
+ checks look better than they are.
5
+
6
+ The headers below are the ones the example worker entry sets. If your `pageCache` names them
7
+ differently, adapt the greps.
8
+
9
+ ## 0. Where to run
10
+
11
+ - Production or a preview deployment: the real thing. The Cache API is per data center, so a
12
+ second request from the same place is what tells you whether the first one stored.
13
+ - Locally: `pageCache` never runs in `vite dev`. Build and use `vite preview` (Miniflare runs the
14
+ Worker), as the example's `bun run build && bun run smoke` does.
15
+ - Always `GET`. `curl -I` sends `HEAD`, which never reaches `pageCache`. Use
16
+ `curl -s -o /dev/null -D -`.
17
+
18
+ ## 1. Is it stored?
19
+
20
+ ```bash
21
+ UA='Mozilla/5.0 (Macintosh) Chrome/140'
22
+ H='^(cache-control|cdn-cache-control|vary|x-cache|x-cache-reason|x-cache-profile|x-cache-segment|x-cache-version|x-cache-age|set-cookie)'
23
+ for p in / /some-category /some-product/p '/s?q=shirt'; do
24
+ echo "== $p"
25
+ for i in 1 2; do curl -s -o /dev/null -D - -A "$UA" "https://SITE$p" | grep -iE "$H"; echo; done
26
+ done
27
+ ```
28
+
29
+ Expect on the second request: `x-cache: HIT`, the profile you meant, `x-cache-version:
30
+ <build>.<revision>`, `vary: Accept-Encoding`, no `set-cookie` other than `deco_segment` on a first
31
+ visit (and the cookies in your `SAFE_COOKIES`, if a render set one). A `BYPASS` comes with `x-cache-reason`; `egress-traps.md` maps each reason to a cause.
32
+
33
+ After a deploy or a publish, `x-cache-version` changes and the first request is a `MISS` again.
34
+ That is expected.
35
+
36
+ ## 2. What must never be stored
37
+
38
+ ```bash
39
+ # A preview: no x-cache, revalidate header, noindex
40
+ curl -s -o /dev/null -D - "https://SITE/?__draft=off" | grep -iE '^(cache-control|vary|x-robots-tag|x-cache)'
41
+ # expect: cache-control: max-age=0, no-cache, must-revalidate ; vary: Cookie ; no x-cache
42
+
43
+ # A signed request
44
+ curl -s -o /dev/null -D - -H 'Authorization: Bearer x' "https://SITE/" | grep -i '^cache-control'
45
+ # expect: private, no-cache, no-store, must-revalidate
46
+
47
+ # A signed-in shopper (use the cookie your buildSegment reads)
48
+ curl -s -o /dev/null -D - -H 'Cookie: <sign-in-cookie>=1' "https://SITE/" | grep -iE '^x-cache'
49
+ # expect: x-cache: BYPASS, x-cache-reason: private
50
+
51
+ # Private paths
52
+ curl -s -o /dev/null -D - "https://SITE/cart" | grep -iE '^(cache-control|x-cache)'
53
+ # expect: private, no-cache, no-store, must-revalidate ; x-cache-reason: profile:private
54
+
55
+ # A missing page
56
+ curl -s -o /dev/null -D - "https://SITE/this-does-not-exist" | grep -iE '^(x-cache)'
57
+ # expect: x-cache-reason: status:404
58
+ ```
59
+
60
+ ## 3. Tracking params: shared entry, no poisoning
61
+
62
+ ```bash
63
+ curl -s -o /dev/null -D - -A "$UA" 'https://SITE/some-category?gclid=POISON42' | grep -iE '^x-cache'
64
+ curl -s -o /dev/null -D - -A "$UA" 'https://SITE/some-category?gclid=POISON42' | grep -iE '^x-cache'
65
+ curl -s -A "$UA" 'https://SITE/some-category' | grep -c POISON42 # must print 0
66
+ curl -s -o /dev/null -D - -A "$UA" 'https://SITE/some-category?utm_source=a&fbclid=b' | grep -iE '^x-cache:'
67
+ # expect HIT once the clean URL is warm, no redirect, same x-cache-segment
68
+ ```
69
+
70
+ A non-zero count means the stored HTML carries the raw URL. Fix it as trap 2 says.
71
+
72
+ ## 4. Same content, same entry
73
+
74
+ Different visitor profiles that should see the same page must land on the same entry. Compare a
75
+ fingerprint of the content (the ordered product ids on a listing) and the `x-cache-segment`:
76
+
77
+ ```bash
78
+ fp() { curl -s -A "$2" -H "Cookie: $3" "$1" | grep -oE 'data-product-id="[^"]*"' | md5sum; }
79
+ URL='https://SITE/some-category'
80
+ fp "$URL" "$UA" ""
81
+ fp "$URL?utm_source=test&gclid=abc" "$UA" ""
82
+ fp "$URL" "$UA" "<a marketing cookie your site sets>=x"
83
+ # all hashes equal; replace the grep with whatever marks a product card in your HTML
84
+ ```
85
+
86
+ Then change only what should split: a phone user agent must change `x-cache-segment`; a geo header
87
+ or region cookie must change it only if the content really differs by region.
88
+
89
+ ## 5. How big is what you store?
90
+
91
+ ```bash
92
+ curl -s --compressed -o /tmp/body -w '%{size_download} bytes compressed\n' 'https://SITE/some-category'
93
+ curl -s -o /tmp/body -w '%{size_download} bytes raw\n' -H 'Accept-Encoding: identity' 'https://SITE/some-category'
94
+ node .agents/skills/deco-storefront-caching/scripts/html-anatomy.mjs https://SITE/some-category
95
+ ```
96
+
97
+ `html-anatomy.mjs` prints the cache headers, the raw and gzip size, bytes per attribute, analytics
98
+ events in the markup, and every large blob repeated more than once. Repeated blobs are the usual
99
+ fix: emit once, reference by id. Set budgets from what you measure (see `perf-guardrails-e2e.md`).
100
+
101
+ ## 6. Failure mode: an empty page must not stick
102
+
103
+ Make the upstream fail on purpose (an env switch in your loader that returns `null`, or point the
104
+ client at a dead host on a preview deployment) and request a cacheable page twice.
105
+
106
+ - Expect `x-cache: BYPASS` with `x-cache-reason: degraded` (or `STALE-ERROR` if a good copy
107
+ existed), never `MISS` followed by `HIT`.
108
+ - Turn the switch off. The next request must render the full page at once, not after the fresh
109
+ window expires.
110
+
111
+ If the empty page was stored, the page does not set `x-deco-degraded` for that failure.
112
+
113
+ ## 7. Purge
114
+
115
+ ```bash
116
+ curl -s -X POST "https://SITE/_cache/purge" \
117
+ -H "Authorization: Bearer $PURGE_TOKEN" -H 'Content-Type: application/json' \
118
+ -d '{"paths":["/some-category"]}'
119
+ # expect {"purged":[...],"total":n}; the next GET of that path from the same data center is a MISS
120
+ ```
121
+
122
+ `total: 0` right after a HIT from the same data center means the purge's key differs from the
123
+ stored key.
124
+
125
+ ## 8. Telemetry, for 24 hours after the deploy
126
+
127
+ - `http.server.request.duration`, counted by `cache` and `http.route`: hit share per page template.
128
+ `BYPASS` growing on one route points at a new cookie or private header there.
129
+ - `http.client.request.duration` by `provider` and `operation`: upstream calls per page view should
130
+ drop. `cached=true` counts hits of your upstream `fetch` cache.
131
+ - 5xx share must not rise. A rise after "degraded" changes means a failure path now throws.
132
+ - CDN bandwidth per path (`deco-performance-audit` in decocms/skills).
133
+
134
+ The alert runbook is `docs/runbooks/cache-hit-drop.md`. Its diagnostic queries and its section on
135
+ loader caches name metrics and routes from the v7 line (`cache_hit_total`, `createCachedLoader`,
136
+ `/_cache/purge-loaders`); on v8 use the metrics above and the example's purge route.
@@ -0,0 +1,160 @@
1
+ # The worker page cache
2
+
3
+ `@decocms/tanstack/worker` gives you `createDecoWorker` and the helpers a cache needs. It stores
4
+ nothing itself. The cache is a function you pass as `pageCache`. The repo ships a complete one in
5
+ `examples/tanstack-worker-smoke/src/worker-entry.ts` (the package README links it): v7's edge
6
+ cache rebuilt on the Cloudflare Cache API. Copy it to `src/worker-entry.ts` and own it.
7
+
8
+ ## Wiring
9
+
10
+ ```ts
11
+ // src/worker-entry.ts — wrangler.jsonc "main": "./src/worker-entry.ts"
12
+ import { createDecoWorker } from "@decocms/tanstack/worker";
13
+ import handler, { createServerEntry } from "@tanstack/react-start/server-entry";
14
+ import { cms } from "./cms";
15
+
16
+ const worker = createDecoWorker<Env>({
17
+ serverEntry: createServerEntry({ fetch: handler.fetch }),
18
+ cms,
19
+ dev: import.meta.env.DEV,
20
+ pageCache, // your function; without it every request renders
21
+ });
22
+ ```
23
+
24
+ - `wrangler.jsonc` `main` must point at this file. If it points at TanStack Start's entry, the
25
+ worker and your cache never run.
26
+ - `__BUILD_HASH__` comes from `decoTanstack({ buildHash })` in `vite.config.ts`
27
+ (`@decocms/tanstack/vite`): the CI's sha when given, else `git`, else the time; `"dev"` in
28
+ `vite dev`.
29
+ - `pageCache` is never called in `vite dev`. Test caching on a build: `vite build`, then
30
+ `vite preview` (Miniflare). The example's `bun run smoke` does exactly that.
31
+ - `createStart(() => ({ serverFns: { fetch: decoServerFnFetch } }))` (`@decocms/tanstack/start`)
32
+ is what sends the `__cseg` token back on navigation data. See `deco-tanstack-site`.
33
+
34
+ ## What the worker already does
35
+
36
+ You do not write these. Do not add a second copy of them in `pageCache`.
37
+
38
+ | Behavior | Detail |
39
+ |---|---|
40
+ | Calls `pageCache` only for cacheable requests | `isCacheable`: `GET`, current release (`version === null`), no `?__draft=` (`off` included) and no draft cookie, no `Authorization`, not `/_build`, not dev. A `HEAD` never reaches it. |
41
+ | Previews | Always render. Answer `Cache-Control: max-age=0, no-cache, must-revalidate`, `Vary: Cookie`, `noindex`, and `CDN-Cache-Control: no-store`. |
42
+ | `Authorization` | The page renders and answers `private, no-cache, no-store, must-revalidate`, whatever the app set. |
43
+ | Default CDN header | Any response without `CDN-Cache-Control` leaves with `CDN-Cache-Control: no-store`. |
44
+ | Visitor cookie | `deco_segment` is set on a first visit only, and appended after `pageCache` answers. A stored copy never carries it; a visitor served from the cache still gets theirs. |
45
+ | `Set-Cookie` | One header per cookie (name + Domain + Path). |
46
+ | Fingerprinted assets | `public, max-age=31536000, immutable`, `Vary: Accept-Encoding`. Also under `/fonts/`. |
47
+ | CMS redirects | Answered before your `routes` and before `pageCache`. See `egress-traps.md`. |
48
+ | v7 admin paths | `/deco/*`, `/live/*`, `/.decofile` answer 404 with a private header. |
49
+ | Metric | `http.server.request.duration` with a `cache` label: `HIT` for your `HIT`, `STALE-HIT`, `STALE-ERROR`; `MISS`; `DRAFT` for previews (a draft signal or a Studio link's version); `BYPASS` otherwise, including every response `pageCache` did not answer. |
50
+
51
+ ## What `pageCache` receives
52
+
53
+ `PageCache<Env> = (page: PageRequest<Env>) => Promise<Response>`, where `page` has:
54
+
55
+ - `request`: as the app gets it (visitor and assignments on their headers).
56
+ - `url`, `device` (`detectDevice`: `mobile`, `tablet`, `desktop`), `env`, `ctx`.
57
+ - `visitor`: the visitor the worker read.
58
+ - `assignments`: each test and campaign on or off, as the page renders them.
59
+ - `render(scope?)`: renders the page, with `x-page-status` applied and without the visitor
60
+ cookie. Pass `{ csegToken }` so `DecoDocument` publishes the token.
61
+
62
+ Set `X-Cache` on your answer (`HIT`, `STALE-HIT`, `STALE-ERROR`, `MISS`, or anything else for a
63
+ bypass). The request metric reads it.
64
+
65
+ ## The helpers
66
+
67
+ All from `@decocms/tanstack/worker`:
68
+
69
+ | Helper | Use |
70
+ |---|---|
71
+ | `cacheVersion(cms, buildHash, url?)` | `<build>.<content revision>`. With the URL, the revision that page renders. Right after a publish a page whose new blocks are not loaded yet renders on the previous index, and this pins the same way, so a page is never stored under a revision it did not render. Without the URL (the purge), the current revision. Falls back to the build alone if the content can't be read. |
72
+ | `assignmentsKey(assignments)` | `x=<tests on>\|c=<campaigns running>`, names sorted and URL-encoded, empty parts left out, `""` for none (a `v=<version>` part comes first for a preview, which never reaches `pageCache`). Never the visitor id. |
73
+ | `liveAssignmentKeys(cms)` | Every assignments key a live request can carry now: each subset of the saved tests, with and without the running campaigns. For the purge. Grows as 2^tests. |
74
+ | `detectDevice(ua)`, `segmentKey(segment)` | Device class; a segment as one stable string (parts sorted, values URL-encoded, empty parts dropped). |
75
+ | `segmentToken(segment, version)` | The `__cseg` token (DJB2 hex of segment and version). `null` when the version is empty or `"dev"`. |
76
+ | `CSEG_PARAM` | `"__cseg"`, the query param `decoServerFnFetch` adds. Drop it from the key. |
77
+ | `isServerFnPath(pathname)`, `serverFnPagePath(url)` | Server-function URLs (`/_serverFn/`, `/_server/`) and the page a GET page load asks for (first local path in `payload`). |
78
+ | `isCacheable(request, { version, dev })`, `requestVersion(request)` | The worker's own gate and the version header. You rarely need them inside `pageCache`. |
79
+ | `DEGRADED_HEADER` | `"x-deco-degraded"`. Your page sets it to `true` when a loader it needs failed, on the document response (a route's `headers` reach it, as with `x-page-status`). Nothing in the framework sets it for you. Also exported from `@decocms/tanstack/server`. |
80
+
81
+ `markPrivate()` from `@decocms/tanstack/server` sets `Cache-Control: private, no-store` on a server
82
+ function called over HTTP (cart, user, wishlist). The example never stores such a response.
83
+
84
+ ## Profiles and TTLs (the example's values)
85
+
86
+ The example picks a profile per URL, first match wins. These are v7's numbers. Change them in
87
+ `PROFILES` and `pageProfile`.
88
+
89
+ | Profile | Matches | Edge fresh / swr / sie (s) | Browser `Cache-Control` |
90
+ |---|---|---|---|
91
+ | `private` | `/cart`, `/checkout`, `/account`, `/login`, `/my-account` | never stored | `private, no-cache, no-store, must-revalidate` |
92
+ | `none` | `/api/*`, `/deco/*` | never stored | same |
93
+ | `static` | `/`, `/sitemap.xml` | 900 / 7200 / 21600 | `public, max-age=120, s-maxage=900, stale-while-revalidate=1800, stale-if-error=7200` |
94
+ | `search` | `/s`, `/s/*`, any `?q=` | 60 / 300 / 1800 | `public, max-age=0, s-maxage=60, stale-while-revalidate=120, stale-if-error=600` |
95
+ | `product` | path ends in `/p` | 300 / 1800 / 7200 | `public, max-age=60, s-maxage=300, stale-while-revalidate=600, stale-if-error=3600` |
96
+ | `listing` | everything else | 120 / 900 / 3600 | `public, max-age=30, s-maxage=120, stale-while-revalidate=300, stale-if-error=1800` |
97
+
98
+ A GET server function takes its page's profile (`serverFnPagePath`). Any other server function
99
+ is `private`.
100
+
101
+ Why profiles at all (the v7 rationale still holds): product pages change on price and stock, so
102
+ they get a short fresh window and a long stale one; listings change with the catalog; search is
103
+ long-tail and mostly unique, so it gets the shortest window; `/` is the hottest URL and safest to
104
+ keep longest. `listing` is the default because it is the cautious middle.
105
+
106
+ ## How the example serves
107
+
108
+ - Fresh copy (age < `fresh`): `X-Cache: HIT`.
109
+ - Stale copy (age < `fresh + swr`): served as `STALE-HIT` with `X-Cache-Age`, and the page renders
110
+ again in `ctx.waitUntil`. The new render is stored only if it is a clean 200.
111
+ - The render throws, or answers 5xx or 429, or is degraded, and a copy younger than `fresh + sie`
112
+ exists: `STALE-ERROR` with `X-Cache-Reason`.
113
+ - Otherwise it renders: a clean 200 is stored and answered `MISS`; anything else is `BYPASS`.
114
+
115
+ The stored copy gets `Cache-Control: public, max-age=<fresh + max(swr, sie)>` so the Cache API
116
+ keeps it through the stale windows; the age comes from an `X-Deco-Stored-At` header that is
117
+ removed before the answer goes out. `HIT`, `STALE-*` and `MISS` answers carry
118
+ `X-Cache-Profile`, `X-Cache-Segment`, `X-Cache-Version` and `Vary: Accept-Encoding`. `BYPASS`
119
+ answers carry `X-Cache` and `X-Cache-Reason` and none of those. A `status:` bypass keeps the
120
+ render's own `Cache-Control`; the other bypasses set `private, no-cache, no-store, must-revalidate`.
121
+
122
+ What the example never stores:
123
+
124
+ | `X-Cache-Reason` on a `BYPASS` | Cause |
125
+ |---|---|
126
+ | `private` | `buildSegment` returned `loggedIn: true` |
127
+ | `profile:<name>` | The URL's profile is not public, or its edge `fresh` is 0 |
128
+ | `status:<code>` | The render was not a 200 (a CMS 404 page included) |
129
+ | `private-response` | `Cache-Control` has `private` or `no-store`, or a `Set-Cookie` outside `SAFE_COOKIES` (`_deco_bucket` in the example) |
130
+ | `degraded` | `x-deco-degraded: true` on the render |
131
+
132
+ A cookie in `SAFE_COOKIES` is stripped from the stored copy, so another visitor never gets it.
133
+
134
+ ## Server functions and the CDN (`__cseg`)
135
+
136
+ Client-side navigation loads page data with a GET server function. The example keys it like the
137
+ page (its payload canonicalized, variant params `skuId` and `idsku` dropped) and stores it in the
138
+ Cache API like any page.
139
+
140
+ It also lets the CDN in front keep that response, which is the only `CDN-Cache-Control: public`
141
+ the example sends. That happens only when the request's `__cseg` equals the token recomputed from
142
+ this request's segment, version and assignments. `decoServerFnFetch` adds the token the page
143
+ published. A stale or forged token gets `CDN-Cache-Control: no-store`. HTML pages always get
144
+ `CDN-Cache-Control: no-store` in the example: they are cached in the Worker's Cache API only.
145
+
146
+ ## Purge
147
+
148
+ The example answers `POST /_cache/purge` with `Authorization: Bearer <PURGE_TOKEN>` (a Worker
149
+ secret) and a body `{ "paths": ["/", "/shoes"], "segments"?: [{ "device": "desktop" }] }`.
150
+
151
+ - It drops each exact path (`/shoes` never drops `/shoes?page=2`) under the current version, for
152
+ each segment (each device when the body names none), each live assignments key, as a navigation
153
+ and as a programmatic fetch. Answer: `{ "purged": [...], "total": n }`.
154
+ - It reuses the same `cacheKey` function as the lookup, so the keys match byte for byte. Keep it
155
+ that way when you change the key.
156
+ - The Cache API is per data center. A purge reaches the copies in the data center that serves it.
157
+ - Each delete is a Cache API call; a request has a limit (the example's comment: 50 on Workers
158
+ Free, 1,000 on Paid). Past it the example answers 503 with `notPurged` to send again.
159
+ - You rarely need it for content: a publish changes the content revision, so every key moves.
160
+ Purge is for upstream data (a price change) on pages whose fresh window is long.
@@ -0,0 +1,97 @@
1
+ #!/usr/bin/env node
2
+ // Where do the bytes of a storefront page go? Zero dependencies (Node 18+).
3
+ //
4
+ // node .agents/skills/deco-storefront-caching/scripts/html-anatomy.mjs https://www.example.com/category
5
+ // node .agents/skills/deco-storefront-caching/scripts/html-anatomy.mjs ./saved-page.html
6
+ //
7
+ // Prints: raw/gzip size, cache headers (URL mode), bytes per attribute, the
8
+ // analytics `data-event` / `data-dt-event` breakdown, and every large blob
9
+ // (attribute value or inline script) that appears more than once — the usual
10
+ // culprit is the same payload emitted per card, per size or per instance.
11
+
12
+ import { readFileSync } from "node:fs";
13
+ import { gzipSync } from "node:zlib";
14
+
15
+ const target = process.argv[2];
16
+ if (!target) {
17
+ console.error("usage: node html-anatomy.mjs <url|file>");
18
+ process.exit(1);
19
+ }
20
+
21
+ let html;
22
+ if (/^https?:\/\//.test(target)) {
23
+ const res = await fetch(target, {
24
+ headers: { "user-agent": "Mozilla/5.0 (Macintosh) Chrome/140", accept: "text/html" },
25
+ });
26
+ html = await res.text();
27
+ // The worker's and the example page cache's headers (v8): what was decided and why.
28
+ const shown = [
29
+ "cache-control", "cdn-cache-control", "vary", "cf-cache-status", "age",
30
+ "x-cache", "x-cache-reason", "x-cache-profile", "x-cache-segment", "x-cache-version",
31
+ "x-cache-age", "x-deco-degraded", "set-cookie",
32
+ ];
33
+ console.log(`status: ${res.status}`);
34
+ for (const h of shown) {
35
+ const v = res.headers.get(h);
36
+ if (v) console.log(`${h}: ${v.slice(0, 120)}`);
37
+ }
38
+ } else {
39
+ html = readFileSync(target, "utf8");
40
+ }
41
+
42
+ const kb = (n) => `${(n / 1024).toFixed(0).padStart(7)} KB`;
43
+ const raw = Buffer.byteLength(html);
44
+ console.log(`\ntotal ${kb(raw)} raw, ${kb(gzipSync(html).length)} gzip\n`);
45
+
46
+ const byAttr = new Map();
47
+ const blobs = new Map();
48
+ // Group by the first 200 chars: repeated payloads usually differ only in a
49
+ // trailing id/props (e.g. the same script inlined per instance with its rootId).
50
+ const note = (key, value) => {
51
+ if (value.length < 1024) return;
52
+ const sig = `${key}|${value.slice(0, 200)}`;
53
+ const e = blobs.get(sig) ?? { key, n: 0, bytes: 0, sample: value };
54
+ e.n++;
55
+ e.bytes += value.length;
56
+ blobs.set(sig, e);
57
+ };
58
+ for (const m of html.matchAll(/\s([a-zA-Z:@\-]+)="([^"]*)"/g)) {
59
+ byAttr.set(m[1], (byAttr.get(m[1]) ?? 0) + m[2].length);
60
+ note(m[1], m[2]);
61
+ }
62
+ for (const m of html.matchAll(/<script[^>]*>([\s\S]*?)<\/script>/g)) {
63
+ byAttr.set("<script> body", (byAttr.get("<script> body") ?? 0) + m[1].length);
64
+ note("<script> body", m[1]);
65
+ }
66
+
67
+ console.log("bytes by attribute (top 12):");
68
+ for (const [k, v] of [...byAttr].sort((a, b) => b[1] - a[1]).slice(0, 12)) {
69
+ console.log(` ${k.padEnd(24)}${kb(v)} ${((v / raw) * 100).toFixed(0)}%`);
70
+ }
71
+
72
+ const events = new Map();
73
+ for (const m of html.matchAll(/\sdata-(?:dt-)?event="([^"]*)"/g)) {
74
+ let name = "?";
75
+ try {
76
+ const d = JSON.parse(decodeURIComponent(m[1].replace(/&quot;/g, '"')));
77
+ name = d.name ?? d.event ?? "?";
78
+ } catch {}
79
+ const e = events.get(name) ?? { n: 0, bytes: 0 };
80
+ e.n++;
81
+ e.bytes += m[1].length;
82
+ events.set(name, e);
83
+ }
84
+ if (events.size) {
85
+ console.log("\nanalytics events in markup:");
86
+ for (const [k, e] of [...events].sort((a, b) => b[1].bytes - a[1].bytes).slice(0, 8)) {
87
+ console.log(` ${String(k).padEnd(24)}${String(e.n).padStart(5)}x ${kb(e.bytes)}`);
88
+ }
89
+ }
90
+
91
+ const dupes = [...blobs.values()].filter((e) => e.n > 1).sort((a, b) => b.bytes - a.bytes);
92
+ if (dupes.length) {
93
+ console.log("\nlarge blobs repeated (same first 200 chars) — fix: emit once, reference it:");
94
+ for (const e of dupes.slice(0, 8)) {
95
+ console.log(` ${String(e.n).padStart(4)}x ~${kb(e.bytes / e.n)} each = ${kb(e.bytes)} [${e.key}] ${e.sample.slice(0, 60).replace(/\s+/g, " ")}…`);
96
+ }
97
+ }
@@ -0,0 +1,81 @@
1
+ ---
2
+ name: deco-storefront-performance
3
+ description: "Server and render performance for storefronts on @decocms/blocks 8 (mostly @decocms/tanstack on Cloudflare Workers; @decocms/nextjs where noted), indexed by symptom. Covers N+1 and duplicate upstream calls in block functions (the client's per-request memo, currentClient(), counting calls with createInstrumentedFetch's metric or a logging fetch), trimming schema.org Product graphs before they reach the HTML, render location (the built-in lazy block, streamed vs awaited blocks, the cost of a large Redirects block), hydration mismatches and flashes, CLS from third-party scripts, instant variant switching, scroll and navigation feedback, reading Chrome traces, and Worker memory (measuring per deploy, large tables out of the bundle, streaming big proxied bodies). Use when TTFB is slow but the HTML is small, the HTML is several MB, one VTEX operation runs many times per page, React logs a hydration error, a section flashes or shifts, a variant click refetches the page, or a Worker hits its 128 MB limit."
4
+ ---
5
+
6
+ # Storefront performance on v8
7
+
8
+ You have a v8 storefront that is slow or unstable in a specific way. This skill is
9
+ organised by symptom. Find the symptom below and load the one reference it names.
10
+
11
+ It is about server work, payload and render behaviour. It does not cover:
12
+
13
+ - **Edge and page caching** (`pageCache`, cache keys, hit rate, upstream caches): see
14
+ the skill `deco-storefront-caching`.
15
+ - **How blocks, sections and `lazy` are written**: see `deco-site-authoring`.
16
+ - **Wiring the TanStack site** (worker entry, page route, server functions): see
17
+ `deco-tanstack-site`. For Next.js, `deco-nextjs-site`.
18
+ - **The thin clients** (`createVtexClient` and its options): see `deco-apps`.
19
+ - **Generic browser-side craft** (Core Web Vitals, JS budgets, HTML size, PageSpeed
20
+ scoring): the decocms/skills skills `improving-web-vitals-tanstack`,
21
+ `client-js-budget`, `html-size-optimizer` and `pagespeed-score-model`.
22
+
23
+ ## When to load what
24
+
25
+ | Reference | Load it when |
26
+ |---|---|
27
+ | [`references/render-location.md`](./references/render-location.md) | TTFB is seconds but the HTML is small; a page resolves data it never shows; you are not sure which block is slow; the site has thousands of redirects |
28
+ | [`references/loaders-n-plus-1.md`](./references/loaders-n-plus-1.md) | One upstream call per product in a block function; SSR gets slower with shelf size; VTEX answers 429 |
29
+ | [`references/request-dedupe.md`](./references/request-dedupe.md) | The same upstream operation runs several times for one page; two sections fetch the same product; you want to count calls before and after |
30
+ | [`references/payload-trim.md`](./references/payload-trim.md) | The HTML or a `/_serverFn/` response is several MB; the HTML is full of `UnitPriceSpecification`; JSON-LD is huge |
31
+ | [`references/hydration.md`](./references/hydration.md) | React logs a hydration mismatch; a section shows server markup but never becomes interactive; a section flashes on load |
32
+ | [`references/cls-third-party.md`](./references/cls-third-party.md) | CLS is high; a widget, seal or chat script pushes content after load |
33
+ | [`references/navigation-ux.md`](./references/navigation-ux.md) | A variant click takes >500 ms or refetches the page; forward navigation keeps the old scroll position; clicks give no feedback; hover prefetch loads the upstream |
34
+ | [`references/trace-reading.md`](./references/trace-reading.md) | You need to find which element shifted, why the screen went blank, or where a slow navigation spends its time; local numbers disagree with production |
35
+ | [`references/worker-memory.md`](./references/worker-memory.md) | The Worker logs "exceeded memory limit" or its memory P90 grew after a deploy; a proxied sitemap or feed is large |
36
+
37
+ ## First, split the cost
38
+
39
+ Two numbers tell you which half of the skill you need:
40
+
41
+ ```bash
42
+ curl -s -o /dev/null -A "Mozilla/5.0 Chrome/120" "$URL" \
43
+ -w 'bytes %{size_download} ttfb %{time_starttransfer}s total %{time_total}s\n'
44
+ ```
45
+
46
+ - **Small body, long wait**: the server did work. Go to `render-location.md`,
47
+ then `loaders-n-plus-1.md` and `request-dedupe.md`. Trimming payload will not move
48
+ this number. One product page measured 29 KB on the wire and 4.6 s of wait.
49
+ - **Large body, short wait**: payload. Go to `payload-trim.md`.
50
+ - **Fast server, bad experience in the browser** (flash, shift, slow click): go to
51
+ `hydration.md`, `cls-third-party.md`, `navigation-ux.md` and `trace-reading.md`.
52
+
53
+ Measure the same URL two or three times. If one run is 0.2 s and the next is 3.6 s,
54
+ that is a cold isolate or a cache miss, not the page. Read `deco-storefront-caching`
55
+ before you optimise anything.
56
+
57
+ ## How v8 runs a page, in one paragraph
58
+
59
+ The worker (`createDecoWorker`) checks the CMS redirects on every `GET` or `HEAD` that is not an
60
+ asset or a server-function call, then calls the site's `pageCache` if it has one, then
61
+ renders. The page route of the example app (`examples/tanstack-worker-smoke`; wiring in
62
+ `deco-tanstack-site`) asks
63
+ one client (`contentClient(cms, request)`) for the page with `{ run: false }`, starts
64
+ one promise per section block with `client.resolve(block)`, awaits only the SEO block,
65
+ and streams the sections through `<Suspense>`/`<Await>`. A client runs each block
66
+ function once per distinct input, so equal blocks in one request share a result. Nothing
67
+ is shared between requests: the client never caches. A client-side navigation calls
68
+ the page server function (a `/_serverFn/` request), which does the same work.
69
+
70
+ The references build on that model. When a fix depends on it, they say so.
71
+
72
+ ## Rules for this skill
73
+
74
+ - **Measure, then attribute.** Count calls and time blocks before you change code.
75
+ Guessing from payload size pointed at the wrong section three times on one site.
76
+ - **Do not move above-the-fold or crawler-relevant content to the client to win a
77
+ number.** The goal is to stop work that is thrown away, not to hide work users need.
78
+ - **Prove a fix with a control.** Same URL, same device, same cache state, before and
79
+ after. A single before/after pair on a busy day is a guess.
80
+ - **Copy a block result before you change it.** Equal blocks in one request share the
81
+ same object. Mutating one in place changes the others.
@@ -0,0 +1,90 @@
1
+ # CLS from third-party scripts and late content
2
+
3
+ Load when: CLS is above 0.1 (poor above 0.25); a review widget, trust seal, chat bubble or
4
+ banner script pushes content after load; the footer jumps.
5
+
6
+ Nothing here is specific to v8. Third-party scripts are the usual cause on storefronts,
7
+ followed by section fallbacks that are shorter than the section they stand in for.
8
+
9
+ ## 1. Find the element that moved
10
+
11
+ Quickest: paste this in the console, then reload with the console open.
12
+
13
+ ```js
14
+ new PerformanceObserver((list) => {
15
+ for (const entry of list.getEntries()) {
16
+ if (entry.hadRecentInput) continue;
17
+ console.log("shift", entry.value.toFixed(4), entry.sources?.map((s) =>
18
+ `${s.node?.nodeName}#${s.node?.id}.${s.node?.className}`));
19
+ }
20
+ }).observe({ type: "layout-shift", buffered: true });
21
+ ```
22
+
23
+ Each line is one shift, with its score and the nodes that moved. Then find what happened
24
+ just before it: a script, a stylesheet, a font, an image without dimensions. A Performance
25
+ trace shows that directly ([`trace-reading.md`](./trace-reading.md)). Lighthouse lists the
26
+ largest shifts under "Avoid large layout shifts".
27
+
28
+ Real case: a trace showed one shift of **0.59** at 1.2 s. The node was a trust-seal
29
+ container in the footer. Just before it, the seal's script loaded and injected CSS that
30
+ grew the container from 0 to ~60 px. Reserving the height and loading the script after
31
+ hydration removed the shift.
32
+
33
+ ## 2. Usual offenders and fixes
34
+
35
+ | Source | What it does | Fix |
36
+ |---|---|---|
37
+ | Review or trust-seal widget | Injects markup and CSS after load | Reserve its height; load the script when idle |
38
+ | Chat or WhatsApp bubble | Adds a floating element | Fixed position only; load after hydration |
39
+ | Inline `<script>` that loads CSS | Restyles content already painted | Move it into a component that loads it after hydration |
40
+ | A section fallback | Shorter than the section that replaces it | Give the fallback the section's height |
41
+ | Images without size | Height unknown until the image loads | `width` and `height` on every image (`Image` from `@decocms/tanstack/react` takes them) |
42
+ | Web fonts | Text reflows when the font swaps | Preload the main font (`createDecoWorker({ preload: { fonts } })` sends `Link` preload headers) and use a fallback font with close metrics |
43
+
44
+ ## 3. A deferred script component
45
+
46
+ Load a third-party script after hydration, when the browser is idle, into a container
47
+ with reserved height:
48
+
49
+ ```tsx
50
+ import { useEffect, useRef } from "react";
51
+
52
+ export function DeferredScript({ id, src, dataset = {}, minHeight = 60 }: {
53
+ id: string; src: string; dataset?: Record<string, string>; minHeight?: number;
54
+ }) {
55
+ const ref = useRef<HTMLDivElement>(null);
56
+ useEffect(() => {
57
+ if (!ref.current || document.getElementById(id)) return;
58
+ const load = () => {
59
+ const script = document.createElement("script");
60
+ script.id = id;
61
+ script.async = true;
62
+ script.src = src;
63
+ for (const [k, v] of Object.entries(dataset)) script.dataset[k] = v;
64
+ ref.current?.appendChild(script);
65
+ };
66
+ if ("requestIdleCallback" in window) {
67
+ const handle = requestIdleCallback(load, { timeout: 3000 });
68
+ return () => cancelIdleCallback(handle);
69
+ }
70
+ const timer = setTimeout(load, 2000);
71
+ return () => clearTimeout(timer);
72
+ }, [id, src]);
73
+ return <div ref={ref} id={`${id}-container`} style={{ minHeight }} />;
74
+ }
75
+ ```
76
+
77
+ - Measure the widget's final height on mobile and desktop and use it as `minHeight`.
78
+ - The `id` check stops a second copy after a client-side navigation.
79
+ - If the script must run before first paint (consent, some analytics), it cannot be
80
+ deferred. Reserve the space instead.
81
+ - A site with a strict CSP must allow the script's origin.
82
+
83
+ ## 4. Verify
84
+
85
+ - The console observer shows no shift above ~0.01 for the widget's container.
86
+ - Lighthouse mobile CLS on the page, before and after, on the same build of the rest.
87
+ - Check a page where the widget is below the fold: a shift there still counts if it
88
+ happens in the viewport while the visitor scrolls.
89
+
90
+ For Core Web Vitals work beyond CLS, see `improving-web-vitals-tanstack` (decocms/skills).