@shopify/hydrogen 2026.10.1 → 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.
- package/README.md +3 -5
- package/dist/cli/index.mjs +8 -5
- package/dist/client/client.mjs +45 -12
- package/dist/client/client.mjs.map +1 -1
- package/dist/client/i18n-variables.d.mts +13 -0
- package/dist/client/i18n-variables.mjs +92 -0
- package/dist/client/i18n-variables.mjs.map +1 -0
- package/dist/client/types.d.mts +21 -8
- package/dist/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/core/cart/cart.mjs +111 -24
- package/dist/core/cart/cart.mjs.map +1 -1
- package/dist/core/cart/cookie.mjs +6 -1
- package/dist/core/cart/cookie.mjs.map +1 -1
- package/dist/core/cart/form.d.mts +17 -5
- package/dist/core/cart/form.mjs +5 -0
- package/dist/core/cart/form.mjs.map +1 -1
- package/dist/core/cart/index.d.mts +1 -1
- package/dist/core/cart/queries.d.mts +57 -57
- package/dist/core/collection/url.mjs +8 -1
- package/dist/core/collection/url.mjs.map +1 -1
- package/dist/core/constants.mjs +2 -1
- package/dist/core/constants.mjs.map +1 -1
- package/dist/core/csp/index.d.mts +56 -0
- package/dist/core/csp/index.mjs +117 -0
- package/dist/core/csp/index.mjs.map +1 -0
- package/dist/core/csp/types.d.mts +52 -0
- package/dist/core/headers.mjs +2 -2
- package/dist/core/headers.mjs.map +1 -1
- package/dist/core/i18n/define.d.mts +54 -0
- package/dist/core/i18n/define.mjs +135 -0
- package/dist/core/i18n/define.mjs.map +1 -0
- package/dist/core/i18n/errors.d.mts +18 -0
- package/dist/core/i18n/errors.mjs +24 -0
- package/dist/core/i18n/errors.mjs.map +1 -0
- package/dist/core/i18n/href.d.mts +28 -0
- package/dist/core/i18n/href.mjs +45 -0
- package/dist/core/i18n/href.mjs.map +1 -0
- package/dist/core/i18n/locale.d.mts +21 -0
- package/dist/core/i18n/locale.mjs +36 -0
- package/dist/core/i18n/locale.mjs.map +1 -0
- package/dist/core/i18n/match.d.mts +37 -0
- package/dist/core/i18n/match.mjs +82 -0
- package/dist/core/i18n/match.mjs.map +1 -0
- package/dist/core/i18n/types.d.mts +80 -0
- package/dist/core/index.d.mts +14 -5
- package/dist/core/index.mjs +9 -2
- package/dist/core/predictive-search/index.d.mts +2 -2
- package/dist/core/predictive-search/queries.d.mts +2 -2
- package/dist/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/core/predictive-search/url.d.mts +2 -2
- package/dist/core/predictive-search/url.mjs.map +1 -1
- package/dist/core/product/accept-variant-id.mjs +1 -1
- package/dist/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/core/request-context.d.mts +61 -35
- package/dist/core/request-context.mjs +11 -7
- package/dist/core/request-context.mjs.map +1 -1
- package/dist/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/proxy.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/core/request-routing/registered-routes.d.mts +13 -2
- package/dist/core/request-routing/registered-routes.mjs +33 -9
- package/dist/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/core/request-routing/route-types.d.mts +18 -8
- package/dist/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/core/shopify-scripts/constants.mjs +3 -1
- package/dist/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/core/shopify-scripts/global.mjs +13 -11
- package/dist/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/core/shopify-scripts/index.d.mts +1 -0
- package/dist/core/shopify-scripts/index.mjs +12 -9
- package/dist/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/core/shopify-scripts/perfkit.mjs +8 -2
- package/dist/core/shopify-scripts/perfkit.mjs.map +1 -1
- package/dist/core/shopify-scripts/types.d.mts +4 -2
- package/dist/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/core/standard-routes/build.d.mts +7 -2
- package/dist/core/standard-routes/build.mjs +10 -3
- package/dist/core/standard-routes/build.mjs.map +1 -1
- package/dist/core/standard-routes/match.mjs +11 -1
- package/dist/core/standard-routes/match.mjs.map +1 -1
- package/dist/core/standard-routes/path.mjs +14 -3
- package/dist/core/standard-routes/path.mjs.map +1 -1
- package/dist/core/standard-routes/types.d.mts +6 -1
- package/dist/core/url.mjs +5 -3
- package/dist/core/url.mjs.map +1 -1
- package/dist/core/utils/load-script.mjs +6 -6
- package/dist/core/utils/load-script.mjs.map +1 -1
- package/dist/customer-account/client.d.mts +14 -10
- package/dist/customer-account/client.mjs +4 -5
- package/dist/customer-account/client.mjs.map +1 -1
- package/dist/customer-account/graphql.d.mts +7 -1
- package/dist/customer-account/graphql.mjs +6 -7
- package/dist/customer-account/graphql.mjs.map +1 -1
- package/dist/customer-account/session.mjs +3 -4
- package/dist/customer-account/session.mjs.map +1 -1
- package/dist/development/client/client.mjs +45 -12
- package/dist/development/client/client.mjs.map +1 -1
- package/dist/development/client/i18n-variables.d.mts +13 -0
- package/dist/development/client/i18n-variables.mjs +92 -0
- package/dist/development/client/i18n-variables.mjs.map +1 -0
- package/dist/development/client/types.d.mts +21 -8
- package/dist/development/core/cache/fetch-with-cache.mjs +8 -1
- package/dist/development/core/cache/fetch-with-cache.mjs.map +1 -1
- package/dist/development/core/cart/cart.mjs +111 -24
- package/dist/development/core/cart/cart.mjs.map +1 -1
- package/dist/development/core/cart/cookie.mjs +6 -1
- package/dist/development/core/cart/cookie.mjs.map +1 -1
- package/dist/development/core/cart/form.d.mts +17 -5
- package/dist/development/core/cart/form.mjs +5 -0
- package/dist/development/core/cart/form.mjs.map +1 -1
- package/dist/development/core/cart/index.d.mts +1 -1
- package/dist/development/core/cart/queries.d.mts +57 -57
- package/dist/development/core/collection/url.mjs +8 -1
- package/dist/development/core/collection/url.mjs.map +1 -1
- package/dist/development/core/constants.mjs +2 -1
- package/dist/development/core/constants.mjs.map +1 -1
- package/dist/development/core/csp/index.d.mts +56 -0
- package/dist/development/core/csp/index.mjs +128 -0
- package/dist/development/core/csp/index.mjs.map +1 -0
- package/dist/development/core/csp/types.d.mts +52 -0
- package/dist/development/core/development.d.mts +14 -5
- package/dist/development/core/development.mjs +9 -2
- package/dist/development/core/headers.mjs +2 -2
- package/dist/development/core/headers.mjs.map +1 -1
- package/dist/development/core/i18n/define.d.mts +54 -0
- package/dist/development/core/i18n/define.mjs +135 -0
- package/dist/development/core/i18n/define.mjs.map +1 -0
- package/dist/development/core/i18n/errors.d.mts +18 -0
- package/dist/development/core/i18n/errors.mjs +24 -0
- package/dist/development/core/i18n/errors.mjs.map +1 -0
- package/dist/development/core/i18n/href.d.mts +28 -0
- package/dist/development/core/i18n/href.mjs +45 -0
- package/dist/development/core/i18n/href.mjs.map +1 -0
- package/dist/development/core/i18n/locale.d.mts +21 -0
- package/dist/development/core/i18n/locale.mjs +36 -0
- package/dist/development/core/i18n/locale.mjs.map +1 -0
- package/dist/development/core/i18n/match.d.mts +37 -0
- package/dist/development/core/i18n/match.mjs +82 -0
- package/dist/development/core/i18n/match.mjs.map +1 -0
- package/dist/development/core/i18n/types.d.mts +80 -0
- package/dist/development/core/index.d.mts +13 -4
- package/dist/development/core/predictive-search/index.d.mts +2 -2
- package/dist/development/core/predictive-search/queries.d.mts +2 -2
- package/dist/development/core/predictive-search/server-handlers.d.mts +27 -6
- package/dist/development/core/predictive-search/server-handlers.mjs +1 -4
- package/dist/development/core/predictive-search/server-handlers.mjs.map +1 -1
- package/dist/development/core/predictive-search/url.d.mts +2 -2
- package/dist/development/core/predictive-search/url.mjs.map +1 -1
- package/dist/development/core/product/accept-variant-id.mjs +1 -1
- package/dist/development/core/product/accept-variant-id.mjs.map +1 -1
- package/dist/development/core/request-context.d.mts +61 -35
- package/dist/development/core/request-context.mjs +11 -7
- package/dist/development/core/request-context.mjs.map +1 -1
- package/dist/development/core/request-routing/handle-shopify-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs +9 -1
- package/dist/development/core/request-routing/interceptors/api-proxy.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/checkout.mjs +11 -5
- package/dist/development/core/request-routing/interceptors/checkout.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/proxy.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs +1 -1
- package/dist/development/core/request-routing/interceptors/standard-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs +2 -1
- package/dist/development/core/request-routing/interceptors/url-redirects.mjs.map +1 -1
- package/dist/development/core/request-routing/registered-routes.d.mts +13 -2
- package/dist/development/core/request-routing/registered-routes.mjs +33 -9
- package/dist/development/core/request-routing/registered-routes.mjs.map +1 -1
- package/dist/development/core/request-routing/route-types.d.mts +18 -8
- package/dist/development/core/shop-pay/shop-pay.mjs +5 -4
- package/dist/development/core/shop-pay/shop-pay.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/analytics.mjs +3 -5
- package/dist/development/core/shopify-scripts/analytics.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/constants.mjs +3 -1
- package/dist/development/core/shopify-scripts/constants.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/global.mjs +13 -11
- package/dist/development/core/shopify-scripts/global.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/hashes.d.mts +17 -0
- package/dist/development/core/shopify-scripts/hashes.mjs +12 -0
- package/dist/development/core/shopify-scripts/hashes.mjs.map +1 -0
- package/dist/development/core/shopify-scripts/index.d.mts +1 -0
- package/dist/development/core/shopify-scripts/index.mjs +12 -9
- package/dist/development/core/shopify-scripts/index.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/page-view.mjs +4 -1
- package/dist/development/core/shopify-scripts/page-view.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/perfkit.mjs +8 -2
- package/dist/development/core/shopify-scripts/perfkit.mjs.map +1 -1
- package/dist/development/core/shopify-scripts/types.d.mts +4 -2
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs +4 -1
- package/dist/development/core/shopify-scripts/utils/inline-script.mjs.map +1 -1
- package/dist/development/core/standard-routes/build.d.mts +7 -2
- package/dist/development/core/standard-routes/build.mjs +10 -3
- package/dist/development/core/standard-routes/build.mjs.map +1 -1
- package/dist/development/core/standard-routes/match.mjs +11 -1
- package/dist/development/core/standard-routes/match.mjs.map +1 -1
- package/dist/development/core/standard-routes/path.mjs +14 -3
- package/dist/development/core/standard-routes/path.mjs.map +1 -1
- package/dist/development/core/standard-routes/types.d.mts +6 -1
- package/dist/development/core/url.mjs +5 -3
- package/dist/development/core/url.mjs.map +1 -1
- package/dist/development/core/utils/load-script.mjs +6 -6
- package/dist/development/core/utils/load-script.mjs.map +1 -1
- package/dist/development/customer-account/session.mjs.map +1 -1
- package/dist/development/globals.d.mts +8 -4
- package/dist/development/graphql/type-resolver.d.mts +39 -1
- package/dist/development/react/cart.mjs +79 -25
- package/dist/development/react/cart.mjs.map +1 -1
- package/dist/development/react/index.d.mts +2 -2
- package/dist/globals.d.mts +8 -4
- package/dist/graphql/type-resolver.d.mts +39 -1
- package/dist/react/cart.mjs +79 -25
- package/dist/react/cart.mjs.map +1 -1
- package/dist/react/index.d.mts +2 -2
- package/dist/vite/index.d.mts +11 -1
- package/dist/vite/index.mjs +21 -1
- package/dist/vite/index.mjs.map +1 -0
- package/package.json +13 -3
- package/skills/hydrogen-analytics/SKILL.md +2 -2
- package/skills/hydrogen-analytics/references/react.md +2 -2
- package/skills/hydrogen-cart-ui/SKILL.md +2 -2
- package/skills/hydrogen-markets/SKILL.md +127 -93
- package/skills/hydrogen-markets/references/nextjs.md +77 -87
- package/skills/hydrogen-oxygen/references/react-router.md +1 -2
- package/skills/hydrogen-predictive-search/SKILL.md +18 -1
- package/skills/hydrogen-request-handlers/SKILL.md +24 -6
- package/skills/hydrogen-request-handlers/references/content-security-policy.md +103 -0
- package/skills/hydrogen-request-handlers/references/frameworks.md +9 -12
- package/skills/hydrogen-request-handlers/references/nextjs.md +7 -3
- package/skills/hydrogen-request-handlers/references/nuxt.md +7 -7
- package/skills/hydrogen-robots-txt/SKILL.md +87 -0
- package/skills/hydrogen-routing/SKILL.md +36 -14
- package/skills/hydrogen-setup/SKILL.md +2 -2
- package/skills/hydrogen-setup/references/analytics.md +5 -5
- package/skills/hydrogen-setup/steps/2-scaffold.md +3 -0
- package/skills/hydrogen-setup/steps/7-shopify-runtime-scripts.md +4 -3
- package/skills/hydrogen-setup/steps/9-account-page.md +1 -1
- package/skills/hydrogen-smoke-test/SKILL.md +9 -2
- package/skills/hydrogen-storefront-client/SKILL.md +29 -9
- package/skills/hydrogen-storefront-client/references/astro.md +8 -3
- package/skills/hydrogen-storefront-client/references/caching.md +2 -0
- package/skills/hydrogen-storefront-client/references/nextjs.md +8 -3
- package/skills/hydrogen-storefront-client/references/nuxt.md +9 -5
- package/skills/hydrogen-storefront-client/references/react-router.md +6 -3
- package/skills/hydrogen-storefront-client/references/solidstart.md +6 -2
- package/skills/hydrogen-storefront-client/references/sveltekit.md +10 -4
- package/skills/migrate-to-hydrogen-2026-10/SKILL.md +20 -22
- package/skills/migrate-to-hydrogen-2026-10/references/sitemap-and-seo.md +1 -0
- package/skills/migrate-to-hydrogen-2026-10/references/typescript-and-gql-tada.md +1 -1
|
@@ -77,7 +77,7 @@ const predictiveSearchFragments = {
|
|
|
77
77
|
`),
|
|
78
78
|
};
|
|
79
79
|
|
|
80
|
-
const predictiveSearchHandlers = createPredictiveSearchServerHandlers({
|
|
80
|
+
export const predictiveSearchHandlers = createPredictiveSearchServerHandlers({
|
|
81
81
|
fragments: predictiveSearchFragments,
|
|
82
82
|
});
|
|
83
83
|
|
|
@@ -94,6 +94,23 @@ const data = await queryPredictiveSearch({
|
|
|
94
94
|
|
|
95
95
|
Use the route-handler form for browser-backed autocomplete. Use `makePredictiveSearchQueries()` when querying directly from server code. Keep fragment names as documented by the API types. Hydrogen composes these with required base fields such as IDs, handles, titles, prices, images, and tracking parameters.
|
|
96
96
|
|
|
97
|
+
Type client state from the same handlers so the UI sees the custom fields:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import type { PredictiveSearchDataFromHandlers } from "@shopify/hydrogen";
|
|
101
|
+
import { usePredictiveSearch } from "@shopify/hydrogen/react"; // or "@shopify/hydrogen/vue"
|
|
102
|
+
import type { predictiveSearchHandlers } from "./predictive-search-handlers";
|
|
103
|
+
|
|
104
|
+
type SearchData = PredictiveSearchDataFromHandlers<typeof predictiveSearchHandlers>;
|
|
105
|
+
|
|
106
|
+
// Call inside a component or setup().
|
|
107
|
+
export function usePredictiveSearchState() {
|
|
108
|
+
return usePredictiveSearch<SearchData>();
|
|
109
|
+
}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
Import the handlers with `import type` so server code stays out of the client bundle. Derive the type from the handlers rather than writing it by hand, and point the provider at those handlers' route: the client doesn't validate responses, and when there's no response to show, the result only holds empty item arrays.
|
|
113
|
+
|
|
97
114
|
## Rules
|
|
98
115
|
|
|
99
116
|
- Use the packaged route handler as the default browser transport.
|
|
@@ -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.
|
|
@@ -44,14 +48,13 @@ Serve the storefront over HTTPS and wire `handleShopifyRoutes` before framework
|
|
|
44
48
|
const shopifyRoute = handleShopifyRoutes({
|
|
45
49
|
request,
|
|
46
50
|
requestContext,
|
|
47
|
-
sessionManager,
|
|
48
51
|
storefrontClient,
|
|
49
52
|
routeTemplates,
|
|
50
53
|
handlers: [cartHandlers],
|
|
51
54
|
});
|
|
52
55
|
```
|
|
53
56
|
|
|
54
|
-
Pass `routeTemplates` to `handleShopifyRoutes` so product `?variant=` links can be recognized before framework routing. `pathPrefix` is inferred from `requestContext.
|
|
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.
|
|
55
58
|
|
|
56
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.
|
|
57
60
|
|
|
@@ -72,8 +75,9 @@ const redirect = await handleShopifyRedirects({
|
|
|
72
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.
|
|
73
76
|
- Route handlers, cart server handlers, and `handleShopifyRedirects` accept any provided Storefront client.
|
|
74
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.
|
|
75
|
-
- 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.
|
|
76
|
-
- Pass the same request-scoped `requestContext
|
|
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.
|
|
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.
|
|
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.
|
|
117
|
-
10.
|
|
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
|
|
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`, `
|
|
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,9 +51,8 @@ const predictiveSearchHandlers = createPredictiveSearchServerHandlers();
|
|
|
50
51
|
export async function handleRequest(request: Request, next: () => Promise<Response>) {
|
|
51
52
|
const requestContext = createShopifyRequestContext({
|
|
52
53
|
request,
|
|
53
|
-
i18n
|
|
54
|
+
i18n,
|
|
54
55
|
});
|
|
55
|
-
const sessionManager = await createSessionManager(request);
|
|
56
56
|
const storefrontClient = createStorefrontClient({
|
|
57
57
|
type: "public",
|
|
58
58
|
requestContext,
|
|
@@ -65,7 +65,6 @@ export async function handleRequest(request: Request, next: () => Promise<Respon
|
|
|
65
65
|
const shopifyRoute = handleShopifyRoutes({
|
|
66
66
|
request,
|
|
67
67
|
requestContext,
|
|
68
|
-
sessionManager,
|
|
69
68
|
storefrontClient,
|
|
70
69
|
routeTemplates,
|
|
71
70
|
handlers: [cartHandlers, predictiveSearchHandlers],
|
|
@@ -83,11 +82,11 @@ export async function handleRequest(request: Request, next: () => Promise<Respon
|
|
|
83
82
|
}
|
|
84
83
|
```
|
|
85
84
|
|
|
86
|
-
## React Router
|
|
85
|
+
## React Router
|
|
87
86
|
|
|
88
87
|
React Router framework mode needs:
|
|
89
88
|
|
|
90
|
-
-
|
|
89
|
+
- Make sure middleware is enabled for your version of React Router.
|
|
91
90
|
- A final splat route such as `route("*", "routes/catchall.tsx")`.
|
|
92
91
|
- Root-route middleware that creates the Storefront client, runs Hydrogen routes, stores the client in context, and applies response headers after `next()`.
|
|
93
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`.
|
|
@@ -101,6 +100,7 @@ import {
|
|
|
101
100
|
handleShopifyRedirects,
|
|
102
101
|
handleShopifyRoutes,
|
|
103
102
|
} from "@shopify/hydrogen";
|
|
103
|
+
import { i18n } from "~/lib/i18n";
|
|
104
104
|
|
|
105
105
|
const cartHandlers = createCartServerHandlers();
|
|
106
106
|
const predictiveSearchHandlers = createPredictiveSearchServerHandlers();
|
|
@@ -109,9 +109,8 @@ export const middleware: Route.MiddlewareFunction[] = [
|
|
|
109
109
|
async ({ context, request }, next) => {
|
|
110
110
|
const requestContext = createShopifyRequestContext({
|
|
111
111
|
request,
|
|
112
|
-
i18n
|
|
112
|
+
i18n,
|
|
113
113
|
});
|
|
114
|
-
const sessionManager = await createSessionManager(request);
|
|
115
114
|
const storefrontClient = createStorefrontClient({
|
|
116
115
|
type: "public",
|
|
117
116
|
requestContext,
|
|
@@ -124,7 +123,6 @@ export const middleware: Route.MiddlewareFunction[] = [
|
|
|
124
123
|
const shopifyRoute = handleShopifyRoutes({
|
|
125
124
|
request,
|
|
126
125
|
requestContext,
|
|
127
|
-
sessionManager,
|
|
128
126
|
storefrontClient,
|
|
129
127
|
routeTemplates,
|
|
130
128
|
handlers: [cartHandlers, predictiveSearchHandlers],
|
|
@@ -148,13 +146,12 @@ export const middleware: Route.MiddlewareFunction[] = [
|
|
|
148
146
|
|
|
149
147
|
SolidStart middleware can short-circuit before routing, but cannot reliably observe the final 404 after SSR streaming starts. Put `handleShopifyRoutes` in middleware and `handleShopifyRedirects` in a last-priority catch-all route.
|
|
150
148
|
|
|
151
|
-
In middleware,
|
|
149
|
+
In middleware, call `handleShopifyRoutes`. Create an app-owned request-scoped `sessionManager` first only if a registered handler reads the session:
|
|
152
150
|
|
|
153
151
|
```ts
|
|
154
152
|
const shopifyRoute = handleShopifyRoutes({
|
|
155
153
|
request: event.request,
|
|
156
154
|
requestContext,
|
|
157
|
-
sessionManager,
|
|
158
155
|
storefrontClient,
|
|
159
156
|
routeTemplates,
|
|
160
157
|
handlers: [cartHandlers, predictiveSearchHandlers],
|
|
@@ -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 `
|
|
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
|
|
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 app-owned `
|
|
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,15 +39,13 @@ export default defineEventHandler(async (event) => {
|
|
|
38
39
|
const request = toWebRequest(event);
|
|
39
40
|
const requestContext = createShopifyRequestContext({
|
|
40
41
|
request,
|
|
41
|
-
i18n
|
|
42
|
+
i18n,
|
|
42
43
|
});
|
|
43
|
-
const sessionManager = await createSessionManager(request);
|
|
44
44
|
const storefrontClient = createPublicStorefrontClient(requestContext);
|
|
45
45
|
|
|
46
46
|
const shopifyRoute = handleShopifyRoutes({
|
|
47
47
|
request,
|
|
48
48
|
requestContext,
|
|
49
|
-
sessionManager,
|
|
50
49
|
storefrontClient,
|
|
51
50
|
routeTemplates,
|
|
52
51
|
handlers: [cartHandlers],
|
|
@@ -168,16 +167,17 @@ if (import.meta.server && props.error.statusCode === 404) {
|
|
|
168
167
|
|
|
169
168
|
## Client Storefront Plugin
|
|
170
169
|
|
|
171
|
-
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:
|
|
172
171
|
|
|
173
172
|
```ts
|
|
174
173
|
import { createStorefrontClient, createShopifyRequestContext } from "@shopify/hydrogen";
|
|
174
|
+
import { i18n } from "~/lib/i18n";
|
|
175
175
|
|
|
176
176
|
export default defineNuxtPlugin(() => {
|
|
177
177
|
const config = useRuntimeConfig().public;
|
|
178
178
|
const requestContext = createShopifyRequestContext({
|
|
179
|
-
request: { headers: new Headers() },
|
|
180
|
-
i18n
|
|
179
|
+
request: { headers: new Headers(), url: window.location.href },
|
|
180
|
+
i18n,
|
|
181
181
|
});
|
|
182
182
|
const storefrontClient = createStorefrontClient({
|
|
183
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
|
|
5
|
+
adding, modifying, or reviewing defineShopifyRouteTemplates, routeTemplates,
|
|
6
6
|
custom Shopify resource or utility-page paths, handleShopifyRoutes,
|
|
7
|
-
standard route redirects, ShopifyScripts routes,
|
|
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 {
|
|
26
|
+
import { defineShopifyRouteTemplates } from "@shopify/hydrogen";
|
|
26
27
|
|
|
27
|
-
export const routeTemplates =
|
|
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 =
|
|
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={
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
140
|
+
defineShopifyRouteTemplates({
|
|
141
141
|
product: "/en-us/p/:productHandle",
|
|
142
142
|
});
|
|
143
143
|
```
|
|
144
144
|
|
|
145
|
-
Hydrogen applies `
|
|
145
|
+
Hydrogen applies `requestContext.locale.pathPrefix` separately:
|
|
146
146
|
|
|
147
|
-
- `handleShopifyRoutes()` reads it from `requestContext.
|
|
148
|
-
- `handleShopifyRedirects()` reads it from `storefrontClient.
|
|
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.
|