@shopify/hydrogen 2026.10.2 → 2026.10.3

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 (245) hide show
  1. package/README.md +3 -5
  2. package/dist/cli/index.mjs +2 -2
  3. package/dist/client/client.mjs +44 -9
  4. package/dist/client/client.mjs.map +1 -1
  5. package/dist/client/i18n-variables.d.mts +1 -1
  6. package/dist/client/i18n-variables.mjs +14 -6
  7. package/dist/client/i18n-variables.mjs.map +1 -1
  8. package/dist/client/types.d.mts +12 -6
  9. package/dist/core/cache/fetch-with-cache.mjs +8 -1
  10. package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
  11. package/dist/core/cart/cart.mjs +1 -1
  12. package/dist/core/cart/cookie.mjs +6 -1
  13. package/dist/core/cart/cookie.mjs.map +1 -1
  14. package/dist/core/cart/form.d.mts +17 -5
  15. package/dist/core/cart/form.mjs +5 -0
  16. package/dist/core/cart/form.mjs.map +1 -1
  17. package/dist/core/cart/index.d.mts +1 -1
  18. package/dist/core/collection/url.mjs +8 -1
  19. package/dist/core/collection/url.mjs.map +1 -1
  20. package/dist/core/constants.mjs +2 -1
  21. package/dist/core/constants.mjs.map +1 -1
  22. package/dist/core/csp/index.d.mts +56 -0
  23. package/dist/core/csp/index.mjs +117 -0
  24. package/dist/core/csp/index.mjs.map +1 -0
  25. package/dist/core/csp/types.d.mts +52 -0
  26. package/dist/core/headers.mjs +2 -2
  27. package/dist/core/headers.mjs.map +1 -1
  28. package/dist/core/i18n/define.d.mts +54 -0
  29. package/dist/core/i18n/define.mjs +135 -0
  30. package/dist/core/i18n/define.mjs.map +1 -0
  31. package/dist/core/i18n/errors.d.mts +18 -0
  32. package/dist/core/i18n/errors.mjs +24 -0
  33. package/dist/core/i18n/errors.mjs.map +1 -0
  34. package/dist/core/i18n/href.d.mts +28 -0
  35. package/dist/core/i18n/href.mjs +45 -0
  36. package/dist/core/i18n/href.mjs.map +1 -0
  37. package/dist/core/i18n/locale.d.mts +21 -0
  38. package/dist/core/i18n/locale.mjs +36 -0
  39. package/dist/core/i18n/locale.mjs.map +1 -0
  40. package/dist/core/i18n/match.d.mts +37 -0
  41. package/dist/core/i18n/match.mjs +82 -0
  42. package/dist/core/i18n/match.mjs.map +1 -0
  43. package/dist/core/i18n/types.d.mts +80 -0
  44. package/dist/core/index.d.mts +14 -5
  45. package/dist/core/index.mjs +9 -2
  46. package/dist/core/predictive-search/index.d.mts +2 -2
  47. package/dist/core/predictive-search/server-handlers.d.mts +27 -6
  48. package/dist/core/predictive-search/server-handlers.mjs +1 -4
  49. package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
  50. package/dist/core/predictive-search/url.d.mts +2 -2
  51. package/dist/core/predictive-search/url.mjs.map +1 -1
  52. package/dist/core/product/accept-variant-id.mjs +1 -1
  53. package/dist/core/product/accept-variant-id.mjs.map +1 -1
  54. package/dist/core/request-context.d.mts +61 -35
  55. package/dist/core/request-context.mjs +11 -7
  56. package/dist/core/request-context.mjs.map +1 -1
  57. package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  58. package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
  59. package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  60. package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
  61. package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
  62. package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
  63. package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  64. package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
  65. package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  66. package/dist/core/request-routing/registered-routes.d.mts +10 -3
  67. package/dist/core/request-routing/registered-routes.mjs +13 -3
  68. package/dist/core/request-routing/registered-routes.mjs.map +1 -1
  69. package/dist/core/request-routing/route-types.d.mts +2 -2
  70. package/dist/core/shop-pay/shop-pay.mjs +5 -4
  71. package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
  72. package/dist/core/shopify-scripts/analytics.mjs +3 -5
  73. package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
  74. package/dist/core/shopify-scripts/constants.mjs +3 -1
  75. package/dist/core/shopify-scripts/constants.mjs.map +1 -1
  76. package/dist/core/shopify-scripts/global.mjs +13 -11
  77. package/dist/core/shopify-scripts/global.mjs.map +1 -1
  78. package/dist/core/shopify-scripts/hashes.d.mts +17 -0
  79. package/dist/core/shopify-scripts/hashes.mjs +12 -0
  80. package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
  81. package/dist/core/shopify-scripts/index.d.mts +1 -0
  82. package/dist/core/shopify-scripts/index.mjs +12 -9
  83. package/dist/core/shopify-scripts/index.mjs.map +1 -1
  84. package/dist/core/shopify-scripts/page-view.mjs +4 -1
  85. package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
  86. package/dist/core/shopify-scripts/types.d.mts +4 -2
  87. package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
  88. package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  89. package/dist/core/standard-routes/build.d.mts +7 -2
  90. package/dist/core/standard-routes/build.mjs +10 -3
  91. package/dist/core/standard-routes/build.mjs.map +1 -1
  92. package/dist/core/standard-routes/match.mjs +11 -1
  93. package/dist/core/standard-routes/match.mjs.map +1 -1
  94. package/dist/core/standard-routes/path.mjs +14 -3
  95. package/dist/core/standard-routes/path.mjs.map +1 -1
  96. package/dist/core/standard-routes/types.d.mts +6 -1
  97. package/dist/core/url.mjs +5 -3
  98. package/dist/core/url.mjs.map +1 -1
  99. package/dist/customer-account/client.d.mts +14 -10
  100. package/dist/customer-account/client.mjs +4 -5
  101. package/dist/customer-account/client.mjs.map +1 -1
  102. package/dist/customer-account/graphql.d.mts +7 -1
  103. package/dist/customer-account/graphql.mjs +6 -7
  104. package/dist/customer-account/graphql.mjs.map +1 -1
  105. package/dist/customer-account/session.mjs +3 -4
  106. package/dist/customer-account/session.mjs.map +1 -1
  107. package/dist/development/client/client.mjs +44 -9
  108. package/dist/development/client/client.mjs.map +1 -1
  109. package/dist/development/client/i18n-variables.d.mts +1 -1
  110. package/dist/development/client/i18n-variables.mjs +13 -5
  111. package/dist/development/client/i18n-variables.mjs.map +1 -1
  112. package/dist/development/client/types.d.mts +12 -6
  113. package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
  114. package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
  115. package/dist/development/core/cart/cart.mjs +1 -1
  116. package/dist/development/core/cart/cookie.mjs +6 -1
  117. package/dist/development/core/cart/cookie.mjs.map +1 -1
  118. package/dist/development/core/cart/form.d.mts +17 -5
  119. package/dist/development/core/cart/form.mjs +5 -0
  120. package/dist/development/core/cart/form.mjs.map +1 -1
  121. package/dist/development/core/cart/index.d.mts +1 -1
  122. package/dist/development/core/cart/queries.d.mts +57 -57
  123. package/dist/development/core/collection/url.mjs +8 -1
  124. package/dist/development/core/collection/url.mjs.map +1 -1
  125. package/dist/development/core/constants.mjs +2 -1
  126. package/dist/development/core/constants.mjs.map +1 -1
  127. package/dist/development/core/csp/index.d.mts +56 -0
  128. package/dist/development/core/csp/index.mjs +128 -0
  129. package/dist/development/core/csp/index.mjs.map +1 -0
  130. package/dist/development/core/csp/types.d.mts +52 -0
  131. package/dist/development/core/development.d.mts +14 -5
  132. package/dist/development/core/development.mjs +9 -2
  133. package/dist/development/core/headers.mjs +2 -2
  134. package/dist/development/core/headers.mjs.map +1 -1
  135. package/dist/development/core/i18n/define.d.mts +54 -0
  136. package/dist/development/core/i18n/define.mjs +135 -0
  137. package/dist/development/core/i18n/define.mjs.map +1 -0
  138. package/dist/development/core/i18n/errors.d.mts +18 -0
  139. package/dist/development/core/i18n/errors.mjs +24 -0
  140. package/dist/development/core/i18n/errors.mjs.map +1 -0
  141. package/dist/development/core/i18n/href.d.mts +28 -0
  142. package/dist/development/core/i18n/href.mjs +45 -0
  143. package/dist/development/core/i18n/href.mjs.map +1 -0
  144. package/dist/development/core/i18n/locale.d.mts +21 -0
  145. package/dist/development/core/i18n/locale.mjs +36 -0
  146. package/dist/development/core/i18n/locale.mjs.map +1 -0
  147. package/dist/development/core/i18n/match.d.mts +37 -0
  148. package/dist/development/core/i18n/match.mjs +82 -0
  149. package/dist/development/core/i18n/match.mjs.map +1 -0
  150. package/dist/development/core/i18n/types.d.mts +80 -0
  151. package/dist/development/core/index.d.mts +13 -4
  152. package/dist/development/core/predictive-search/index.d.mts +2 -2
  153. package/dist/development/core/predictive-search/queries.d.mts +2 -2
  154. package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
  155. package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
  156. package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
  157. package/dist/development/core/predictive-search/url.d.mts +2 -2
  158. package/dist/development/core/predictive-search/url.mjs.map +1 -1
  159. package/dist/development/core/product/accept-variant-id.mjs +1 -1
  160. package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
  161. package/dist/development/core/request-context.d.mts +61 -35
  162. package/dist/development/core/request-context.mjs +11 -7
  163. package/dist/development/core/request-context.mjs.map +1 -1
  164. package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
  165. package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
  166. package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
  167. package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
  168. package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
  169. package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
  170. package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
  171. package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
  172. package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
  173. package/dist/development/core/request-routing/registered-routes.d.mts +10 -3
  174. package/dist/development/core/request-routing/registered-routes.mjs +13 -3
  175. package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
  176. package/dist/development/core/request-routing/route-types.d.mts +2 -2
  177. package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
  178. package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
  179. package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
  180. package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
  181. package/dist/development/core/shopify-scripts/constants.mjs +3 -1
  182. package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
  183. package/dist/development/core/shopify-scripts/global.mjs +13 -11
  184. package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
  185. package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
  186. package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
  187. package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
  188. package/dist/development/core/shopify-scripts/index.d.mts +1 -0
  189. package/dist/development/core/shopify-scripts/index.mjs +12 -9
  190. package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
  191. package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
  192. package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
  193. package/dist/development/core/shopify-scripts/types.d.mts +4 -2
  194. package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
  195. package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
  196. package/dist/development/core/standard-routes/build.d.mts +7 -2
  197. package/dist/development/core/standard-routes/build.mjs +10 -3
  198. package/dist/development/core/standard-routes/build.mjs.map +1 -1
  199. package/dist/development/core/standard-routes/match.mjs +11 -1
  200. package/dist/development/core/standard-routes/match.mjs.map +1 -1
  201. package/dist/development/core/standard-routes/path.mjs +14 -3
  202. package/dist/development/core/standard-routes/path.mjs.map +1 -1
  203. package/dist/development/core/standard-routes/types.d.mts +6 -1
  204. package/dist/development/core/url.mjs +5 -3
  205. package/dist/development/core/url.mjs.map +1 -1
  206. package/dist/development/customer-account/session.mjs.map +1 -1
  207. package/dist/development/globals.d.mts +8 -4
  208. package/dist/development/graphql/type-resolver.d.mts +13 -1
  209. package/dist/development/react/index.d.mts +2 -2
  210. package/dist/globals.d.mts +8 -4
  211. package/dist/graphql/type-resolver.d.mts +13 -1
  212. package/dist/react/index.d.mts +2 -2
  213. package/dist/vite/index.mjs +1 -1
  214. package/dist/vue/shopify-scripts.d.mts +1 -1
  215. package/package.json +13 -3
  216. package/skills/hydrogen-analytics/SKILL.md +2 -2
  217. package/skills/hydrogen-analytics/references/react.md +2 -2
  218. package/skills/hydrogen-markets/SKILL.md +127 -93
  219. package/skills/hydrogen-markets/references/nextjs.md +77 -87
  220. package/skills/hydrogen-oxygen/references/react-router.md +1 -2
  221. package/skills/hydrogen-predictive-search/SKILL.md +18 -1
  222. package/skills/hydrogen-request-handlers/SKILL.md +23 -5
  223. package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
  224. package/skills/hydrogen-request-handlers/references/frameworks.md +8 -6
  225. package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
  226. package/skills/hydrogen-request-handlers/references/nuxt.md +7 -5
  227. package/skills/hydrogen-robots-txt/SKILL.md +87 -0
  228. package/skills/hydrogen-routing/SKILL.md +36 -14
  229. package/skills/hydrogen-setup/SKILL.md +2 -2
  230. package/skills/hydrogen-setup/references/analytics.md +5 -5
  231. package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
  232. package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
  233. package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
  234. package/skills/hydrogen-smoke-test/SKILL.md +9 -2
  235. package/skills/hydrogen-storefront-client/SKILL.md +27 -9
  236. package/skills/hydrogen-storefront-client/references/astro.md +8 -3
  237. package/skills/hydrogen-storefront-client/references/caching.md +2 -0
  238. package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
  239. package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
  240. package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
  241. package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
  242. package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
  243. package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
  244. package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
  245. package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
@@ -18,6 +18,8 @@ Hydrogen request handlers are framework-neutral, but the framework wiring is not
18
18
 
19
19
  Before wiring middleware or route handlers, check whether this skill has a reference file for the app's framework in `references/`. If one exists, read it and preserve that framework's routing gate. If there is no matching reference, use `references/frameworks.md` as the generic adaptation guide and map its pre-routing and post-404 phases onto the app's server lifecycle.
20
20
 
21
+ For CSP header application, nonce propagation, and the Next proxy-to-renderer handoff, read [Content Security Policy](./references/content-security-policy.md).
22
+
21
23
  ## Core Gate
22
24
 
23
25
  ```
@@ -30,6 +32,8 @@ Request
30
32
 
31
33
  `handleShopifyRoutes` owns Hydrogen routes the framework should never see: SFAPI proxy URLs, the generic `/__shopify/*` API proxy, `/.well-known/ucp`, `/checkout`, cart permalinks like `/cart/{variantId}:{quantity}`, UCP buy permalinks like `/buy/{itemId}:{quantity}`, AJAX cart URLs like `/cart.js` and `/cart/add.js`, `/api/mcp`, `/api/ucp/mcp`, `/graphiql` in development, Liquid-style `?variant=<numeric id>` product URLs, and app-registered handler groups such as `createCartServerHandlers()` or `createCustomerAccountServerHandlers()`.
32
34
 
35
+ Most of these paths aren't pages, so they need a crawler policy in the app's `robots.txt`. Disallow the checkout, cart, proxy, and agent endpoints, and keep discovery paths such as `/.well-known/ucp` reachable. Invoke the `hydrogen-robots-txt` skill for the rules.
36
+
33
37
  ## UCP Business Profile
34
38
 
35
39
  `GET /.well-known/ucp` serves Shopify's managed UCP business profile from the headless storefront origin; `HEAD` returns the response headers without a body. Hydrogen forwards `If-None-Match` and `If-Modified-Since`, but not shopper cookies or authorization, and preserves `304 Not Modified` responses. Response headers are filtered through the small `UCP_RESPONSE_HEADERS` allowlist in the profile interceptor; upstream `Vary` is omitted because Hydrogen always requests JSON.
@@ -50,7 +54,7 @@ const shopifyRoute = handleShopifyRoutes({
50
54
  });
51
55
  ```
52
56
 
53
- Pass `routeTemplates` to `handleShopifyRoutes` so product `?variant=` links can be recognized before framework routing. `pathPrefix` is inferred from `requestContext.i18n.pathPrefix`, so localized product URLs stay in the localized tree.
57
+ Pass `routeTemplates` to `handleShopifyRoutes` so product `?variant=` links can be recognized before framework routing. `pathPrefix` is inferred from `requestContext.locale.pathPrefix`, so localized product URLs stay in the localized tree. Registered handler groups are matched with that prefix stripped, so `/fr-ca/api/cart` reaches the `/api/cart` handler without per-locale registration.
54
58
 
55
59
  `handleShopifyRedirects` is a post-routing 404 check for `/admin`, configured standard route redirects, Storefront URL redirects, and same-origin `return_to`/`redirect` query params. Do not run it on every request.
56
60
 
@@ -71,9 +75,9 @@ const redirect = await handleShopifyRedirects({
71
75
  - Default to one request-scoped public Storefront client per request; `publicStorefrontToken` may be undefined for tokenless access (all mock.shop supports). Recommend a token-backed client once the app targets a real store, and upgrade to a private client when a private token and trusted buyer context exist.
72
76
  - Route handlers, cart server handlers, and `handleShopifyRedirects` accept any provided Storefront client.
73
77
  - When creating a private client, resolve trusted `buyerIp` first and pass it to `createShopifyRequestContext`. Use the `hydrogen-storefront-client` buyer-IP guidance for the app's deployment.
74
- - Create `requestContext` with `createShopifyRequestContext({ request, i18n, buyerIp })` where buyer context exists and the framework exposes a real `Request`; use `request: { headers }` only when no `Request` exists.
78
+ - Create `requestContext` with `createShopifyRequestContext({ request, i18n, buyerIp })` where buyer context exists and the framework exposes a real `Request`; use `request: { headers }` only when no `Request` exists. `i18n` is the module-scope `defineShopifyI18n` definition; the locale is matched from `request.url` (or the forwarded `x-storefront-url` header with headers-only requests). Pass `locale` only for contexts with no meaningful URL.
75
79
  - Pass the same request-scoped `requestContext` and `storefrontClient` into `handleShopifyRoutes` and registered handler groups, plus the same request-scoped `sessionManager` when a handler needs one.
76
- - `handleShopifyRoutes` requires `sessionManager` only when a registered handler reads the session: Customer Account handlers, cart handlers created with `customerSession`, or custom handlers whose context includes it. Apps whose handlers never read the session, such as cart and predictive search only, can omit it. The requirement comes from the handler types, so a handler list that conditionally includes Customer Account handlers still needs a session manager on every request; when the account handlers are not registered, an in-memory session manager is enough, as in the starter templates. Annotate custom `createShopifyRouteHandler` contexts as `Omit<ShopifyRouteHandlerContext, "sessionManager">` when they do not use the session; a context that declares `sessionManager`, even as optional, requires one.
80
+ - `handleShopifyRoutes` requires `sessionManager` only when a registered handler reads the session: Customer Account handlers, cart handlers created with `customerSession`, or custom handlers whose context includes it. Apps whose handlers never read the session, such as cart and predictive search only, can omit it. The requirement comes from the handler types, so a handler list that conditionally includes Customer Account handlers still needs a session manager on every request; when the account handlers are not registered, an in-memory session manager is enough, as in the starter templates. Annotate custom `createShopifyRouteHandler` contexts as `Omit<ShopifyRouteHandlerContext, "sessionManager">` when they do not use the session. Hydrogen infers the context only from an annotated parameter: a handler with no parameter or an unannotated destructured parameter gets the full context and still requires `sessionManager`. A context that declares `sessionManager`, even as optional, requires one. Optional gives no runtime fallback: when an untyped caller omits it, the handler receives a stand-in that throws on use, so `if (sessionManager)` is always true.
77
81
  - Call `handleShopifyRoutes` without awaiting it immediately. It returns `null` synchronously when no route matches; only return or await the promise after checking that it is truthy.
78
82
  - If the app has a request-level `try/catch` that converts errors into a `Response`, use `return await shopifyRoute` inside that boundary so rejected route promises reach the same error handling as synchronous setup failures. If the framework owns request error handling, return `shopifyRoute` directly. Do not add an inline `.catch()` unless the matched route intentionally needs different error handling.
79
83
  - Pass `request` and `storefrontClient` into `handleShopifyRedirects`; it does not receive a session manager.
@@ -95,12 +99,25 @@ import {
95
99
  createPredictiveSearchServerHandlers,
96
100
  createShopifyRequestContext,
97
101
  createStorefrontClient,
102
+ defineShopifyI18n,
98
103
  handleShopifyRedirects,
99
104
  handleShopifyRoutes,
100
105
  } from "@shopify/hydrogen";
101
106
  import { createCustomerAccountServerHandlers } from "@shopify/hydrogen/customer-account";
102
107
  ```
103
108
 
109
+ `define*` exports (`defineShopifyI18n`, `defineShopifyRouteTemplates`) return module-scope, serializable configuration. `create*` exports return stateful objects or handler groups; the request-scoped ones (`createShopifyRequestContext`, `createStorefrontClient`) belong inside the request lifecycle.
110
+
111
+ The examples in `references/` assume an app-owned `lib/i18n.ts`:
112
+
113
+ ```ts
114
+ import { defineShopifyI18n } from "@shopify/hydrogen";
115
+
116
+ export const i18n = defineShopifyI18n({
117
+ defaultLocale: { language: "EN", country: "US" },
118
+ });
119
+ ```
120
+
104
121
  ## Verify
105
122
 
106
123
  Run the app in dev and production modes, then check:
@@ -113,5 +130,6 @@ Run the app in dev and production modes, then check:
113
130
  6. `GET /admin` returns a redirect to the shop admin URL.
114
131
  7. An unknown path returns the framework 404 when no Shopify redirect exists.
115
132
  8. `GET /products/{handle}?variant={numeric id}` returns a 302 to the option-params URL when `routeTemplates` is passed to `handleShopifyRoutes`; `?variant=garbage` falls through to the product page.
116
- 9. Cart, Customer Account, and consent responses preserve eligible `Set-Cookie` headers. Consent responses remain private and non-cacheable even when personal state is returned only in the body.
117
- 10. Authenticated Customer Account responses do not preserve public or CDN cache-control headers.
133
+ 9. With pathname routing in `defineShopifyI18n`, `GET /{prefix}/api/cart` returns the same cart handler JSON as `GET /api/cart`.
134
+ 10. Cart, Customer Account, and consent responses preserve eligible `Set-Cookie` headers. Consent responses remain private and non-cacheable even when personal state is returned only in the body.
135
+ 11. Authenticated Customer Account responses do not preserve public or CDN cache-control headers.
@@ -0,0 +1,103 @@
1
+ # Content Security Policy
2
+
3
+ Call `const csp = createContentSecurityPolicy({shop})` before rendering a document. Pass `csp.nonce` to the framework renderer, framework script components, and `ShopifyScripts` (or the core script-tag helpers). Call `csp.applyResponseHeaders(response.headers)` to send the policy and prevent caching of nonce-bearing HTML. CSP is independent of Shopify request contexts; apply it only to responses that need the policy.
4
+
5
+ Each call creates a fresh policy. Reuse that object throughout one document response; applying it repeatedly is safe and overwrites any existing enforcing CSP. The policy also exposes `header` for framework-native configuration or forwarding to a separate renderer. A stable policy created with `nonce: false` can accompany cached HTML.
6
+
7
+ Keep the normal `requestContext.applyResponseHeaders(response.headers)` call for Shopify cookies and personalized-response caching. It and `csp.applyResponseHeaders()` can run in either order; neither undoes the other's cache restrictions. Commit session cookies before applying the request-context headers.
8
+
9
+ ## Customization
10
+
11
+ `directives` arrays extend defaults, as in classic Hydrogen. Custom sources come first and duplicate sources are removed. If a default consists only of `'none'`, the supplied array replaces it, so `frameAncestors: ["'self'"]` works without combining incompatible sources. `null` omits a directive; `undefined` retains its default. An empty array adds no sources to ordinary defaults. In nonce mode, the nonce is always included in `scriptSrc` and, when configured, `scriptSrcElem`, so these directives cannot contain `'none'`. Don't put nonce tokens in directive arrays; the creator owns nonce generation. Defaults allow inline styles for storefront components, but not inline script execution, event handlers, or script evaluation.
12
+
13
+ Pass only the additional sources your app needs:
14
+
15
+ ```ts
16
+ const csp = createContentSecurityPolicy({
17
+ shop,
18
+ directives: {
19
+ connectSrc: ['https://analytics.example.com'],
20
+ },
21
+ });
22
+ // Render using csp.nonce, then apply the document policy.
23
+ csp.applyResponseHeaders(response.headers);
24
+ ```
25
+
26
+ `getShopifyCspDirectives(shop)` supplies the same defaults used by the creator, including development connections, for framework-native CSP configuration. Adapt its camelCase directive names and quoted source keywords to the framework's format. It does not generate nonces or authorize inline scripts by default. Pass `getShopifyCspDirectives(shop, { hashes: true })` to include the [Shopify bootstrap hashes](#shopify-bootstrap-hashes) in `scriptSrc`. For frameworks with a separate hashes field that expects unquoted values, use `getShopifyScriptHashes({ quoted: false })` instead. Use framework-native configuration or construct your own header when you need exact replacement of the creator's defaults, such as removing its inline-style allowance.
27
+
28
+ Hydrogen's development build automatically adds local HTTP/HTTPS and WebSocket connections for `localhost` and `127.0.0.1`, plus WebSocket connections for `*.tryhydrogen.dev`, to the getter's `connectSrc` defaults. The creator inherits these defaults. The production build omits these sources. For framework config files loaded directly by Node, add `--conditions=development` to the Node command in development scripts; keep build and production commands without that flag. Custom `connectSrc` arrays retain these development defaults. Add other development origins explicitly, and add `'unsafe-eval'` to `scriptSrc` only if the framework's development runtime requires it. Keep framework-specific development allowances out of production. Add third-party resources and their network endpoints to the appropriate directives. Verify enabled Shopify features and third-party integrations with browser CSP enforcement active.
29
+
30
+ ## Migrating from classic Hydrogen
31
+
32
+ Source arrays extend defaults in both versions, but the creator is not a drop-in replacement:
33
+
34
+ | Area | Classic | Current API |
35
+ | --- | --- | --- |
36
+ | Options | Directives are top-level properties alongside `shop`. | Move directive properties under `directives`; keep `shop` alongside `nonce`. |
37
+ | Directive values | Accepts arrays, strings, and booleans. | Source directives accept arrays or `null`; use `null` to omit. `[]` adds nothing to existing defaults, and gives an empty directive only where there is no default or the default is only `'none'`. Booleans are only for `upgradeInsecureRequests`. |
38
+ | Default policy | Relies on `defaultSrc` for scripts, images, fonts, media, and frames. | Uses `defaultSrc: ["'self'"]` and defines these directives separately, adds `objectSrc: ["'none'"]` and `scriptSrcAttr: ["'none'"]`, allows `data:` images, and adds Shopify connection/frame origins. A `defaultSrc` customization no longer authorizes these separately configured resource types. |
39
+ | Nonce placement | Adds the nonce to `scriptSrc` when an array is supplied, otherwise to `defaultSrc`. | Always adds it to `scriptSrc`, and also to a configured `scriptSrcElem`. Incoming headers never determine the nonce; manually supplied nonce sources are rejected. |
40
+ | React helpers | Returns a bound `NonceProvider`; exports `useNonce` and `Script`. | Exposes `nonce` and `header`; React context stays in the app. Pass the nonce explicitly to framework scripts and `ShopifyScripts`. |
41
+ | Response lifecycle | The app applies the returned header. | The policy owns `applyResponseHeaders()`, which overwrites existing enforcing CSP and prevents nonce reuse through caching. `nonce: false` supports cached documents. |
42
+ | Development | Checks runtime `NODE_ENV`; adds localhost to style, default, and connection sources. | Uses the package's development export; adds local origins only to connection sources, including secure WebSockets. |
43
+
44
+ The current directive type adds `scriptSrcAttr`, `styleSrcElem`, and `styleSrcAttr`; it does not include classic's `pluginTypes`, `prefetchSrc`, `navigateTo`, or `blockAllMixedContent`. Malformed source tokens and contradictory `'none'` combinations throw instead of being passed through. Shop domains accept the same values as the storefront client: bare hosts get `https://`, and trailing slashes are removed. Nonces remain 128-bit random values, now encoded as base64 instead of hexadecimal; Web Crypto is required, with no `Math.random()` fallback. Treat the nonce as an opaque string.
45
+
46
+ ## CSP without nonces
47
+
48
+ Use `nonce: false` for a stable policy that can accompany cached HTML or a prerendered shell. This returns `nonce: undefined`, adds no nonce sources, and leaves cache headers unchanged. The request context's normal cookie and personalization rules still apply.
49
+
50
+ Inline scripts still need authorization. For a policy that permits inline scripts while restricting external origins, opt in explicitly:
51
+
52
+ ```ts
53
+ const csp = createContentSecurityPolicy({
54
+ shop,
55
+ nonce: false,
56
+ directives: {
57
+ scriptSrc: ["'unsafe-inline'"],
58
+ },
59
+ });
60
+ csp.applyResponseHeaders(response.headers);
61
+ ```
62
+
63
+ This allows injected inline JavaScript as well as the app's scripts. Hash-based CSP is a stricter alternative, but the framework must authorize every emitted inline script, including [Shopify's bootstraps](#shopify-bootstrap-hashes). If `scriptSrcElem` is configured, it controls script elements instead of `scriptSrc`. Adding nonce/hash sources or `'strict-dynamic'` can make browsers ignore `'unsafe-inline'`; do not mix these without accounting for all inline scripts.
64
+
65
+ ## Shopify bootstrap hashes
66
+
67
+ `ShopifyScripts` and the core tag helpers render static inline JavaScript with dynamic configuration in escaped `data-config` attributes. To authorize those bootstraps without nonces, add the sources returned by `getShopifyScriptHashes()` to `scriptSrc`:
68
+
69
+ ```ts
70
+ const csp = createContentSecurityPolicy({
71
+ shop,
72
+ nonce: false,
73
+ directives: { scriptSrc: getShopifyScriptHashes() },
74
+ });
75
+ ```
76
+
77
+ These hashes are generated from the packaged script contents and include CSP quotes by default. Pass `getShopifyScriptHashes({ quoted: false })` for framework-native configurations that expect unquoted hashes. They authorize only Hydrogen's inline bootstraps; the framework must also authorize its own scripts. Hashes are opt-in because adding them causes browsers to ignore `'unsafe-inline'` in the same directive. Read the hashes from the installed package instead of copying literal hashes, and preserve the script text when rendering.
78
+
79
+ Prefer per-response nonces when the framework supports them: they authorize individual script elements for each response. Hashes authorize matching script code regardless of its `data-config` attributes.
80
+
81
+ ## Next.js App Router
82
+
83
+ For a prerendered shell, use the `'unsafe-inline'` configuration from [CSP without nonces](#csp-without-nonces) in `proxy.ts`, after handling Hydrogen-owned routes. Delete `Content-Security-Policy` and `Content-Security-Policy-Report-Only` from the headers returned by `getForwardedRequestHeaders()` so a client-supplied policy cannot supply Next's nonce. Render `ShopifyScripts` without a nonce and avoid reading request headers solely for CSP in the layout. This preserves the shell's rendering model. See [Next's CSP guide](https://nextjs.org/docs/app/guides/content-security-policy).
84
+
85
+ Nonce CSP requires dynamic document rendering. Next cannot nonce scripts in a prerendered shell; putting only `ShopifyScripts` under Suspense does not solve this. Data can remain cached independently of the document.
86
+
87
+ For dynamic documents, create one policy with `createContentSecurityPolicy({shop})` in the proxy after handling Hydrogen-owned routes. Set `Content-Security-Policy` to `csp.header` on the request headers returned by `getForwardedRequestHeaders()` so Next can nonce its own scripts. Also forward `csp.nonce` in an app-owned request header such as `x-nonce`, then read that header in the dynamic layout and pass it to `ShopifyScripts`. Apply the response headers with `requestContext.applyResponseHeaders(response.headers)` followed by `csp.applyResponseHeaders(response.headers)`. See [Next's CSP guide](https://nextjs.org/docs/app/guides/content-security-policy) for the proxy and layout pattern.
88
+
89
+ The proxy must overwrite both forwarded headers on every document-rendering path, including error pages. Incoming header values are not trusted nonce sources. Do not call the creator again in the layout: that would generate a different nonce. Server Component contexts cannot modify the proxy's response after it returns.
90
+
91
+ ## Other renderers
92
+
93
+ Create and apply the policy where the framework renders the document. For React Router, both operations belong in `entry.server`; no Shopify request context is needed there. Pass the nonce to `renderToReadableStream` / `renderToPipeableStream`, `ServerRouter`, `Scripts`, `ScrollRestoration`, and Shopify's scripts. React context helpers remain app-owned. During hydration preserve the server nonce; read a script element's `.nonce` property, not `getAttribute('nonce')`. Don't generate another client nonce or replace the document's nonce during client navigation.
94
+
95
+ When rendering and response finalization happen in separate hooks, carry the policy object in framework request-local state and apply it in the finalizer.
96
+
97
+ For framework-native CSP, use the defaults getter with the framework's own nonce/hash lifecycle. Never generate one nonce at build time and reuse it across responses.
98
+
99
+ ## Verification
100
+
101
+ In nonce mode, check that hydration and navigation work, framework/streaming and Shopify scripts share a nonce, and an unauthorized inline script is blocked. Separate document requests must get different nonces and return `Cache-Control: private, no-store`.
102
+
103
+ In nonce-free mode, verify the production shell remains prerendered, CSP leaves cache headers unchanged, authorized scripts execute, and scripts from disallowed external origins are blocked. In both modes, confirm incoming CSP headers cannot change the proxy's policy.
@@ -3,7 +3,7 @@
3
3
  ## Contents
4
4
 
5
5
  - Single-Hook Shape
6
- - React Router 7
6
+ - React Router
7
7
  - SolidStart
8
8
  - Unknown Framework Decision Tree
9
9
  - Gotchas
@@ -32,7 +32,7 @@ Prefer this over adding `.catch()` only to the returned promise: the request-lev
32
32
 
33
33
  The scaffold defaults to a public client; `PUBLIC_STOREFRONT_API_TOKEN` may be unset, which means tokenless access (all mock.shop supports). Once the app has a private token and trusted buyer context, switch to `type: "private"` and resolve `buyerIp` per the `hydrogen-storefront-client` buyer-IP guidance.
34
34
 
35
- This shape assumes app-owned `getBuyerIp` and `routeTemplates` values. Cart and predictive search handlers do not read the session, so no `sessionManager` is passed; add a request-scoped one when registering Customer Account handlers or cart handlers created with `customerSession`.
35
+ This shape assumes app-owned `getBuyerIp`, `routeTemplates`, and `i18n` (the `defineShopifyI18n` definition from `SKILL.md`) values. Cart and predictive search handlers do not read the session, so no `sessionManager` is passed; add a request-scoped one when registering Customer Account handlers or cart handlers created with `customerSession`.
36
36
 
37
37
  ```ts
38
38
  import {
@@ -43,6 +43,7 @@ import {
43
43
  handleShopifyRedirects,
44
44
  handleShopifyRoutes,
45
45
  } from "@shopify/hydrogen";
46
+ import { i18n } from "./lib/i18n";
46
47
 
47
48
  const cartHandlers = createCartServerHandlers();
48
49
  const predictiveSearchHandlers = createPredictiveSearchServerHandlers();
@@ -50,7 +51,7 @@ const predictiveSearchHandlers = createPredictiveSearchServerHandlers();
50
51
  export async function handleRequest(request: Request, next: () => Promise<Response>) {
51
52
  const requestContext = createShopifyRequestContext({
52
53
  request,
53
- i18n: { country: "US", language: "EN" },
54
+ i18n,
54
55
  });
55
56
  const storefrontClient = createStorefrontClient({
56
57
  type: "public",
@@ -81,11 +82,11 @@ export async function handleRequest(request: Request, next: () => Promise<Respon
81
82
  }
82
83
  ```
83
84
 
84
- ## React Router 7
85
+ ## React Router
85
86
 
86
87
  React Router framework mode needs:
87
88
 
88
- - Verify `future.v8_middleware: true` is set in `react-router.config.ts`.
89
+ - Make sure middleware is enabled for your version of React Router.
89
90
  - A final splat route such as `route("*", "routes/catchall.tsx")`.
90
91
  - Root-route middleware that creates the Storefront client, runs Hydrogen routes, stores the client in context, and applies response headers after `next()`.
91
92
  - A public Storefront client by default; when upgrading to `type: "private"`, resolve trusted `buyerIp` before `createStorefrontClient` per the buyer-IP guidance from `hydrogen-storefront-client`.
@@ -99,6 +100,7 @@ import {
99
100
  handleShopifyRedirects,
100
101
  handleShopifyRoutes,
101
102
  } from "@shopify/hydrogen";
103
+ import { i18n } from "~/lib/i18n";
102
104
 
103
105
  const cartHandlers = createCartServerHandlers();
104
106
  const predictiveSearchHandlers = createPredictiveSearchServerHandlers();
@@ -107,7 +109,7 @@ export const middleware: Route.MiddlewareFunction[] = [
107
109
  async ({ context, request }, next) => {
108
110
  const requestContext = createShopifyRequestContext({
109
111
  request,
110
- i18n: { country: "US", language: "EN" },
112
+ i18n,
111
113
  });
112
114
  const storefrontClient = createStorefrontClient({
113
115
  type: "public",
@@ -2,13 +2,15 @@
2
2
 
3
3
  Next splits Hydrogen routing across `proxy.ts` and `app/not-found.tsx`.
4
4
 
5
+ For CSP, see [Content Security Policy](./content-security-policy.md). Call `csp.applyResponseHeaders()` on the response. In nonce mode, also set `Content-Security-Policy` to `csp.header` on the headers returned by `getForwardedRequestHeaders()` so Next's renderer can nonce its own scripts. Nonce mode requires dynamic document rendering. Forward `csp.nonce` in an app-owned request header such as `x-nonce`, overwriting any incoming value, and read it in the layout for Shopify's scripts. Use `nonce: false` with explicit inline-script authorization to preserve a prerendered shell; in that mode, remove incoming CSP and report-only CSP request headers instead of forwarding a policy.
6
+
5
7
  ## `proxy.ts`
6
8
 
7
9
  `proxy.ts` can short-circuit before routing, so put `handleShopifyRoutes` there. In Next 16+, the file is `proxy.ts` and the exported function is named `proxy`; older Next projects may use `middleware.ts` with an exported `middleware` function. It cannot inspect the routed response, so forward the original URL to not-found UI.
8
10
 
9
11
  The scaffold defaults to a public client; `NEXT_PUBLIC_STOREFRONT_API_TOKEN` may be unset, which means tokenless access (all mock.shop supports). Once the app has a private token and trusted buyer context, switch to `type: "private"` and resolve `buyerIp` from the app's trusted deployment headers per the buyer-IP guidance from `hydrogen-storefront-client`.
10
12
 
11
- This shape assumes app-owned server-only helpers and values for `customerSession`, `createSessionManager`, and `routeTemplates`. Do not import those names from Hydrogen.
13
+ This shape assumes app-owned server-only helpers and values for `customerSession`, `createSessionManager`, `routeTemplates`, and `i18n` (the `defineShopifyI18n` definition in `lib/i18n.ts`). Do not import those names from Hydrogen.
12
14
 
13
15
  ```ts
14
16
  import {
@@ -20,6 +22,8 @@ import {
20
22
  import { createCustomerAccountServerHandlers } from "@shopify/hydrogen/customer-account";
21
23
  import { NextResponse, type NextRequest } from "next/server";
22
24
 
25
+ import { i18n } from "@/lib/i18n";
26
+
23
27
  const cartHandlers = createCartServerHandlers({ customerSession });
24
28
  const customerAccountHandlers = createCustomerAccountServerHandlers({
25
29
  customerSession,
@@ -29,7 +33,7 @@ const customerAccountHandlers = createCustomerAccountServerHandlers({
29
33
  export async function proxy(request: NextRequest) {
30
34
  const requestContext = createShopifyRequestContext({
31
35
  request,
32
- i18n: { country: "US", language: "EN" },
36
+ i18n,
33
37
  });
34
38
  const storefrontClient = createStorefrontClient({
35
39
  type: "public",
@@ -115,7 +119,7 @@ With `cacheComponents: true`, keep request-time work in an async child under `<S
115
119
 
116
120
  ## Storefront Client
117
121
 
118
- In server components, use a cached server-only factory that reads `headers()` and creates a request-scoped client (public by default). In `proxy.ts`, use the actual `NextRequest` so URL, signal, and forwarded headers are preserved. `requestContext.getForwardedRequestHeaders()` carries the original URL through `x-storefront-url` for `not-found.tsx`.
122
+ In server components, use a cached server-only factory that reads `headers()` and creates a request-scoped client (public by default). In `proxy.ts`, use the actual `NextRequest` so URL, signal, and forwarded headers are preserved. `requestContext.getForwardedRequestHeaders()` carries the original URL through `x-storefront-url` for `not-found.tsx`, and `createShopifyRequestContext({ request: { headers }, i18n })` reads that same header to resolve `requestContext.locale` in Server Components. Module-scope static clients have no URL; pass `locale: i18n.defaultLocale` there.
119
123
 
120
124
  When a Server Component or layout reads Customer Account session state under Cache Components, put that read below an explicit dynamic boundary (`connection()` + `<Suspense>`). Do not rely on static route-segment config that Cache Components rejects.
121
125
 
@@ -21,7 +21,7 @@ Create `server/middleware/shopify.ts`:
21
21
 
22
22
  The scaffold defaults to a public client; `PUBLIC_STOREFRONT_API_TOKEN` may be unset, which means tokenless access (all mock.shop supports). Once the app has a private token and trusted buyer context, switch to `type: "private"` and resolve `buyerIp` from the app's trusted deployment headers per the buyer-IP guidance from `hydrogen-storefront-client`.
23
23
 
24
- Create an app-owned `routeTemplates` value before `handleShopifyRoutes`. Cart handlers do not read the session, so this example passes no `sessionManager`; add a request-scoped one when registering Customer Account handlers or cart handlers created with `customerSession`.
24
+ Create app-owned `routeTemplates` and `i18n` (the `defineShopifyI18n` definition from `SKILL.md`) values before `handleShopifyRoutes`. Cart handlers do not read the session, so this example passes no `sessionManager`; add a request-scoped one when registering Customer Account handlers or cart handlers created with `customerSession`.
25
25
 
26
26
  ```ts
27
27
  import {
@@ -31,6 +31,7 @@ import {
31
31
  handleShopifyRoutes,
32
32
  type ShopifyRequestContext,
33
33
  } from "@shopify/hydrogen";
34
+ import { i18n } from "~/lib/i18n";
34
35
 
35
36
  const cartHandlers = createCartServerHandlers();
36
37
 
@@ -38,7 +39,7 @@ export default defineEventHandler(async (event) => {
38
39
  const request = toWebRequest(event);
39
40
  const requestContext = createShopifyRequestContext({
40
41
  request,
41
- i18n: { country: "US", language: "EN" },
42
+ i18n,
42
43
  });
43
44
  const storefrontClient = createPublicStorefrontClient(requestContext);
44
45
 
@@ -166,16 +167,17 @@ if (import.meta.server && props.error.statusCode === 404) {
166
167
 
167
168
  ## Client Storefront Plugin
168
169
 
169
- For client-side refetches, use a public client whose `fetch` rewrites Storefront API URLs to the same-origin Hydrogen SFAPI proxy:
170
+ For client-side refetches, use a public client whose `fetch` rewrites Storefront API URLs to the same-origin Hydrogen SFAPI proxy. Pass the page URL as `request.url` so the browser client resolves the same locale as the server did:
170
171
 
171
172
  ```ts
172
173
  import { createStorefrontClient, createShopifyRequestContext } from "@shopify/hydrogen";
174
+ import { i18n } from "~/lib/i18n";
173
175
 
174
176
  export default defineNuxtPlugin(() => {
175
177
  const config = useRuntimeConfig().public;
176
178
  const requestContext = createShopifyRequestContext({
177
- request: { headers: new Headers() },
178
- i18n: { country: "US", language: "EN" },
179
+ request: { headers: new Headers(), url: window.location.href },
180
+ i18n,
179
181
  });
180
182
  const storefrontClient = createStorefrontClient({
181
183
  type: "public",
@@ -0,0 +1,87 @@
1
+ ---
2
+ name: hydrogen-robots-txt
3
+ description: >
4
+ Guide for serving robots.txt from a Hydrogen storefront. Use when adding,
5
+ modifying, or reviewing robots.txt, crawler allow/disallow rules, the Sitemap
6
+ directive, or crawl policy for cart, account, checkout, search, collection
7
+ sort/filter, and Hydrogen endpoint URLs.
8
+ ---
9
+
10
+ # Hydrogen robots.txt
11
+
12
+ A headless storefront serves its own `robots.txt`. Hydrogen ships no helper for it. Without one, `/robots.txt` falls through to the framework's 404 page, and crawlers treat a missing robots.txt as permission to crawl everything: carts, account pages, checkout handoffs, and every sort and filter combination of every collection.
13
+
14
+ robots.txt is not access control. Well-behaved crawlers honor it; nothing else has to. Account pages, API endpoints, and cart data must stay protected by authentication and server-side checks.
15
+
16
+ ## Default Rules
17
+
18
+ Start from this file and adjust it to the app's routes (see "Adjust To The App").
19
+
20
+ ```
21
+ User-agent: *
22
+ Disallow: /admin
23
+ Disallow: /cart
24
+ Disallow: /account
25
+ Disallow: /checkout
26
+ Disallow: /buy/
27
+ Disallow: /api/
28
+ Disallow: /__shopify
29
+ Disallow: /search
30
+ Disallow: /collections/*sort_by*
31
+ Disallow: /collections/*filter*&*filter*
32
+
33
+ # Google AdsBot ignores the "*" group and follows only groups that name it.
34
+ User-agent: adsbot-google
35
+ Disallow: /cart
36
+ Disallow: /account
37
+ Disallow: /checkout
38
+ Disallow: /search
39
+ ```
40
+
41
+ | Rule | Why |
42
+ | --- | --- |
43
+ | `/admin` | `handleShopifyRedirects` redirects it to the Shopify admin. |
44
+ | `/cart` | Buyer-specific. The prefix also covers cart permalinks (`/cart/{variantId}:{quantity}`) and AJAX cart URLs (`/cart.js`, `/cart/add.js`). |
45
+ | `/account` | Customer account pages and the login, logout, and OAuth handlers. |
46
+ | `/checkout`, `/buy/` | Checkout redirect and UCP buy permalinks. They redirect into Shopify checkout and aren't content. |
47
+ | `/api/` | Storefront API proxy, registered handlers such as `/api/cart`, and the agent endpoints `/api/mcp` and `/api/ucp/mcp`. Agents discover those through `/.well-known/ucp`, which stays reachable. |
48
+ | `/__shopify` | The generic Shopify API proxy. |
49
+ | `/search` | Search result pages are thin, unbounded duplicates of catalog pages. |
50
+ | `/collections/*sort_by*` | Every sort order duplicates the collection. |
51
+ | `/collections/*filter*&*filter*` | Blocks URLs with two or more `filter.*` params, which includes a price range with both a minimum and a maximum. Single-filter pages stay crawlable so they can work as landing pages. Use canonical tags, not robots.txt, to control duplicates among them. |
52
+
53
+ AdsBot gets its own short list because it ignores the `*` group and needs to reach ad landing pages, which can be sorted or filtered collection URLs.
54
+
55
+ ## Adjust To The App
56
+
57
+ - **Keep reachable:** `/.well-known/` (the UCP business profile and Apple Pay domain verification), and every product, collection, page, blog, and article route.
58
+ - **Path-prefixed markets:** when routes carry a locale prefix such as `/en-ca/`, repeat the page rules for each prefix the app serves (`Disallow: /en-ca/cart`, `Disallow: /en-ca/account`, `Disallow: /en-ca/search`). AJAX cart URLs accept a locale prefix too. Don't write `/*/cart` or `/*/search`: `*` matches across slashes, so `/*/cart` also blocks `/products/cart-organizer`. The collection rules can use `/*/collections/*sort_by*` and `/*/collections/*filter*&*filter*`, because the query parameter in the pattern keeps them from matching product pages.
59
+ - **Custom route templates:** when `routeTemplates` moves a Shopify route, such as collections at `/c/:handle`, rewrite the matching rules to the app's pathnames. Add a rule only for a path the app actually serves.
60
+ - **Other listings:** if the app serves blog tag URLs that combine tags with `+` (`/blogs/news/tag1+tag2`), add `Disallow: /blogs/*+*`, `/blogs/*%2B*`, and `/blogs/*%2b*`.
61
+ - **Sitemap:** add `Sitemap: <origin>/sitemap.xml` only when the app serves a sitemap. The URL must be absolute, so build it from the request origin. A `Sitemap:` line that points at a 404 shows up as an error in search consoles.
62
+
63
+ ## Serve It
64
+
65
+ Return `200` with `Content-Type: text/plain; charset=utf-8` and a public `Cache-Control`, such as `public, max-age=86400`. Make sure no catch-all route shadows it.
66
+
67
+ | Framework | Route |
68
+ | --- | --- |
69
+ | React Router | A resource route with only a `loader` that returns a `Response`, registered as `route("robots.txt", "routes/robots.ts")`, or `app/routes/[robots.txt].ts` with file-based routes. |
70
+ | Next.js App Router | `app/robots.ts` returning `MetadataRoute.Robots`, with one `rules` entry for `*` and one for `adsbot-google`. Next.js sends it with `public, max-age=0, must-revalidate`; for a longer cache, use a route handler at `app/robots.txt/route.ts` instead. |
71
+ | Nuxt | `server/routes/robots.txt.ts` with `defineEventHandler`, setting the content type. |
72
+ | SvelteKit | `src/routes/robots.txt/+server.ts` exporting `GET`. |
73
+ | Astro | `src/pages/robots.txt.ts` exporting `GET`. |
74
+ | SolidStart | `src/routes/robots.txt.ts` exporting `GET`. |
75
+
76
+ Middleware that runs on every request can still touch this response. When the Hydrogen request context applies response headers, it switches the response to private caching if the response carries `Set-Cookie` or the request used the customer session or Customer Account API. Don't read or write the session in the robots route. If the check below shows `Set-Cookie` or private caching, serve `/robots.txt` in the server entry, before the framework router and its middleware.
77
+
78
+ ## Verify
79
+
80
+ ```bash
81
+ curl -sD - http://localhost:<port>/robots.txt
82
+ ```
83
+
84
+ - [ ] Status is `200` and `Content-Type` is `text/plain`, not the framework's HTML 404 page
85
+ - [ ] `Cache-Control` is public and no `Set-Cookie` header is present
86
+ - [ ] Every path rule matches a route or handler the app serves, and no rule blocks `/.well-known/`
87
+ - [ ] A `Sitemap:` line is present only when the sitemap URL returns 200
@@ -2,9 +2,10 @@
2
2
  name: hydrogen-routing
3
3
  description: >
4
4
  Guide for Hydrogen route templates and Shopify storefront URL routing. Use when
5
- adding, modifying, or reviewing createShopifyRouteTemplates, routeTemplates,
5
+ adding, modifying, or reviewing defineShopifyRouteTemplates, routeTemplates,
6
6
  custom Shopify resource or utility-page paths, handleShopifyRoutes,
7
- standard route redirects, ShopifyScripts routes, or predictive search result URLs.
7
+ standard route redirects, ShopifyScripts routes, predictive search result URLs,
8
+ or localized path prefixes from defineShopifyI18n.
8
9
  ---
9
10
 
10
11
  # Hydrogen Routing
@@ -22,9 +23,9 @@ Only add template keys for Shopify standard routes the app actually handles or i
22
23
  Create one `routeTemplates` object and pass the same object to every Hydrogen primitive that builds, redirects, or exposes Shopify storefront URLs:
23
24
 
24
25
  ```ts
25
- import { createShopifyRouteTemplates } from "@shopify/hydrogen";
26
+ import { defineShopifyRouteTemplates } from "@shopify/hydrogen";
26
27
 
27
- export const routeTemplates = createShopifyRouteTemplates({
28
+ export const routeTemplates = defineShopifyRouteTemplates({
28
29
  product: "/p/:productHandle",
29
30
  collection: "/c/:collectionHandle",
30
31
  article: "/journal/:blogHandle/:articleHandle",
@@ -39,7 +40,7 @@ If the app currently uses Shopify's default resource paths, create an empty mani
39
40
  ```ts
40
41
  // Shopify standard storefront routes are currently handled at their default paths.
41
42
  // Add entries here if the app changes to custom Shopify resource or utility-page paths.
42
- export const routeTemplates = createShopifyRouteTemplates({});
43
+ export const routeTemplates = defineShopifyRouteTemplates({});
43
44
  ```
44
45
 
45
46
  Each key is a Shopify standard route identity. Each value is the app's custom pathname template for that identity. Templates must start with `/` and include the required named placeholders for that key. Add a key only when the app handles that route at a non-standard pathname, or when the app intentionally canonicalizes a standard Shopify variant such as `productInCollection`.
@@ -73,7 +74,6 @@ Pass `routeTemplates` to `handleShopifyRoutes()` before framework routing so Liq
73
74
  const shopifyRoute = handleShopifyRoutes({
74
75
  request,
75
76
  requestContext,
76
- sessionManager,
77
77
  storefrontClient,
78
78
  routeTemplates,
79
79
  handlers: [cartHandlers],
@@ -101,7 +101,7 @@ Pass route templates to `ShopifyScripts` so browser-side Shopify modules and age
101
101
  ```tsx
102
102
  <ShopifyScripts
103
103
  shop={shop}
104
- i18n={i18n}
104
+ i18n={requestContext.locale}
105
105
  routes={routeTemplates}
106
106
  />
107
107
  ```
@@ -116,7 +116,7 @@ Pass route templates to `getPredictiveSearchItemUrl()` so predictive result link
116
116
  const href = getPredictiveSearchItemUrl(item, {
117
117
  term,
118
118
  routes: routeTemplates,
119
- pathPrefix: i18n.pathPrefix,
119
+ pathPrefix: requestContext.locale.pathPrefix,
120
120
  });
121
121
  ```
122
122
 
@@ -129,7 +129,7 @@ For query suggestions, pass the same route templates so a custom `search` route
129
129
  Do not include locale or market prefixes in route template values. Keep templates resource-relative:
130
130
 
131
131
  ```ts
132
- createShopifyRouteTemplates({
132
+ defineShopifyRouteTemplates({
133
133
  product: "/p/:productHandle",
134
134
  });
135
135
  ```
@@ -137,18 +137,40 @@ createShopifyRouteTemplates({
137
137
  not:
138
138
 
139
139
  ```ts
140
- createShopifyRouteTemplates({
140
+ defineShopifyRouteTemplates({
141
141
  product: "/en-us/p/:productHandle",
142
142
  });
143
143
  ```
144
144
 
145
- Hydrogen applies `i18n.pathPrefix` separately:
145
+ Hydrogen applies `requestContext.locale.pathPrefix` separately:
146
146
 
147
- - `handleShopifyRoutes()` reads it from `requestContext.i18n.pathPrefix` for product `?variant=` redirects.
148
- - `handleShopifyRedirects()` reads it from `storefrontClient.requestContext.i18n.pathPrefix`.
149
- - `ShopifyScripts` receives it through the `i18n` prop or option.
147
+ - `handleShopifyRoutes()` reads it from `requestContext.locale.pathPrefix` for product `?variant=` redirects, and matches registered handler groups with the prefix stripped, so `/fr-ca/api/cart` reaches the `/api/cart` handler.
148
+ - `handleShopifyRedirects()` reads it from `storefrontClient.locale.pathPrefix`.
149
+ - `ShopifyScripts` receives it through the `i18n` prop or option; pass `requestContext.locale` there.
150
150
  - `getPredictiveSearchItemUrl()` receives it through `pathPrefix`.
151
151
 
152
+ ### Localized routing
153
+
154
+ The prefix comes from the storefront's i18n definition, not from app code. Declare locales once with `defineShopifyI18n` and pass the definition to `createShopifyRequestContext({ request, i18n })`; the request context resolves `locale` from `request.url`:
155
+
156
+ ```ts
157
+ import { defineShopifyI18n } from "@shopify/hydrogen";
158
+
159
+ export const i18n = defineShopifyI18n({
160
+ defaultLocale: { language: "EN", country: "US" },
161
+ routing: {
162
+ type: "pathname",
163
+ locales: [{ language: "FR", country: "CA" }],
164
+ },
165
+ });
166
+ ```
167
+
168
+ - `type: "pathname"` serves each listed locale under `/{language}-{country}` (lowercased, or a custom `pathSegment`); the default locale is served unprefixed and must not be listed.
169
+ - `type: "domain"` serves each locale from its own `hostname`; the default locale must be listed so it has a canonical host. `pathPrefix` is always `""`.
170
+ - Omit `routing` for a single-locale storefront.
171
+
172
+ Build locale switchers and `hreflang` links with `getLocalizedHref(href, { i18n, locale })`; it swaps the path prefix or hostname according to the routing type and throws for locales the definition does not contain. Enumerate locales with `getSupportedLocales(i18n)`. Naming follows the package convention: `define*` returns module-scope serializable configuration, `create*` returns stateful objects. Read the local `hydrogen-markets` skill for the full definition contract.
173
+
152
174
  ## Rules
153
175
 
154
176
  - Identify the framework and router before deciding which Shopify standard routes are handled.
@@ -21,7 +21,7 @@ Read each step file and complete it fully before opening the next. Every step en
21
21
  - Setup is **not complete** until the final verify step's commands have been executed in this session and passed. If you are about to summarize results and have not just run them, stop and run them. Reporting success with failing or unrun checks is a failed setup, not a finished one.
22
22
 
23
23
  1. `steps/1-inspect-app.md` — verify basic compatibility, identify the styling approach, detect the framework and its reference files.
24
- 2. `steps/2-scaffold.md` — route conventions, environment variable names, server-side env access, Storefront API client with `hydrogen gql check`, API route handlers, Customer Account API.
24
+ 2. `steps/2-scaffold.md` — route conventions, environment variable names, server-side env access, Storefront API client with `hydrogen gql check`, API route handlers, `robots.txt`, Customer Account API.
25
25
  3. `steps/3-build-home-page.md` — server-rendered home page listing collections and products.
26
26
  4. `steps/4-collection-and-search.md` — collection and search browsing with URL-synced filters.
27
27
  5. `steps/5-cart.md` — the `/cart` route with progressive enhancement.
@@ -38,7 +38,7 @@ Read each step file and complete it fully before opening the next. Every step en
38
38
 
39
39
  - **Account UI / session storage** — the `hydrogen-customer-account` skill wires sessions and OAuth handlers during scaffold, and the account-page step builds the minimal profile + logout UI, but the app owns the framework session adapter, richer account pages, and order history UI. Keep account tokens server-side or in encrypted HttpOnly cookies, and do not retry account mutations after a timeout unless the operation is externally idempotent.
40
40
  - **Image optimization** — use the framework's image component (or `<img srcset>`) with Shopify CDN URL transforms; do not expect a Hydrogen `Image` component.
41
- - **SEO** — render meta/Open Graph tags and JSON-LD `Product`/`BreadcrumbList` structured data with the framework's head/metadata API using Storefront API data.
41
+ - **SEO** — render meta/Open Graph tags and JSON-LD `Product`/`BreadcrumbList` structured data with the framework's head/metadata API using Storefront API data. Serve `/robots.txt` with the `hydrogen-robots-txt` skill during scaffold.
42
42
 
43
43
  Mention these to the user when they are relevant to the storefront being built rather than skipping them silently.
44
44
 
@@ -212,7 +212,7 @@ Destinations are consent-gated and receive retained history once tracking is all
212
212
 
213
213
  Each framework should derive `shop` and `i18n` on the server and render ShopifyScripts before publishing. The exact env API varies by framework; these examples show the data flow, not a requirement to use these file names.
214
214
 
215
- Do not query `localization.language` just to echo the language already passed to `@inContext`. If the app only knows country/language and does not have a market currency code, add `currencyCode` to the app's market config or query `localization { country { currency { isoCode } } }` as a fallback.
215
+ Read the locale from `requestContext.locale` (or `storefrontClient.locale`), the `{ language, country, pathPrefix }` resolved for the request from the `defineShopifyI18n` definition. Do not query `localization.language` just to echo the language already passed to `@inContext`. If the app does not have a currency code for the locale, add `currency` to the locale entries in `defineShopifyI18n` (extra fields survive on `requestContext.locale`) or query `localization { country { currency { isoCode } } }` as a fallback.
216
216
 
217
217
  React root layout:
218
218
 
@@ -223,7 +223,7 @@ React root layout:
223
223
  storefrontId: env.PUBLIC_STOREFRONT_ID ?? "0",
224
224
  myshopifyDomain: env.PUBLIC_STORE_DOMAIN,
225
225
  }}
226
- i18n={{ country: market.country, language: market.language, currency: market.currencyCode }}
226
+ i18n={{ ...storefrontClient.locale, currency: currencyCode }}
227
227
  consent={{ mode: "default-banner" }}
228
228
  />
229
229
  ```
@@ -237,7 +237,7 @@ const shopifyTags = renderShopifyScriptTags({
237
237
  storefrontId: env.PUBLIC_STOREFRONT_ID ?? "0",
238
238
  myshopifyDomain: env.PUBLIC_STORE_DOMAIN,
239
239
  },
240
- i18n: { country: market.country, language: market.language, currency: market.currencyCode },
240
+ i18n: { ...requestContext.locale, currency: currencyCode },
241
241
  consent: { mode: "default-banner" },
242
242
  });
243
243
  ```
@@ -583,7 +583,7 @@ analytics?.addDestination({
583
583
 
584
584
  Register all event consumers with `addDestination()` and subscribe inside its setup callback. Consent gating happens at the bus level before destination callbacks see the payload.
585
585
 
586
- Removing and re-adding a destination, even with the same name, creates a fresh registration and replays retained history again. This can duplicate deliveries on component remounts, including React Strict Mode's development effect replay. Keep destinations registered for the page's lifetime; use the returned cleanup when intentionally removing an integration.
586
+ The bus tracks replay progress by destination name. Re-adding a removed name resumes after the last event the bus processed for that name, including events it did not subscribe to, so component remounts and React Strict Mode's development effect replay do not redeliver retained events. If a re-added destination subscribes to additional event types, earlier retained events of those types are not replayed. A re-added name does receive retained events published while it was removed. A new name starts from the beginning of retained history. Still prefer registering destinations for the page's lifetime; use the returned cleanup when intentionally removing an integration.
587
587
 
588
588
  Destinations that need Shopify visitor IDs can call `getTrackingValues()` from the callback's second argument: `subscribe(event, (payload, { getTrackingValues }) => { ... })`. It reads current `uniqueToken` and `visitToken` values from the consent API when called, including during replay, and requests fallback generation with the tag `hydrogen:<destination name>`. Unavailable tokens are empty strings, and the getter also returns empty strings whenever analytics tracking is not currently allowed, so a retained getter cannot read or generate tokens after consent is revoked. Call it inside the destination callback; registration itself does not read or generate tokens.
589
589
 
@@ -615,7 +615,7 @@ For production, re-verify against the production bundle. Several gotchas only ap
615
615
  - **Astro page-view fires only on full loads.** Astro is MPA-by-default. If you adopt View Transitions, listen for `astro:after-swap` instead of relying on the inline-script-runs-on-load behavior — otherwise SPA-nav transitions skip `page_viewed`.
616
616
  - **Required product fields silently drop the Monorail leg.** Missing `id`/`title`/`vendor`/`variantId`/`variantTitle`/`price` causes the Shopify analytics subscriber to skip Monorail dispatch and log a field-specific error. The bus event still fires for your subscribers — the loss is only in Shopify analytics. Watch the console.
617
617
  - **A product event without a currency logs a warning. Shopify analytics still sends it.** `[shopify:warn:analytics] product_added_to_cart was sent without a currency` means the cart fragment's `cost.amountPerQuantity` has no `currencyCode` and `window.Shopify.currency.active` is unset. Select `currencyCode` in the fragment or pass `i18n.currency`. `product_viewed` cannot reach this warning through the typed `ProductPayload`, whose `price` is `MoneyV2`.
618
- - **Register destinations once per page lifetime.** Hydrogen owns the shared bus. Removing and re-adding a destination resets its replay position, so component remounts can deliver retained events again.
618
+ - **Replay progress is keyed by destination name.** Re-adding a removed name resumes where it left off, but a new name (for example one that includes a random suffix or a route key) receives all retained history again. Use a stable name per integration.
619
619
  - **Lighthouse skip is silent.** Monorail dispatch is skipped for Chrome Lighthouse user-agents. If your synthetic monitoring runs Lighthouse, you will see no Monorail requests in those runs — this is intentional.
620
620
 
621
621
  ---