hydrogen-request-handlers
Skill218 starsChanged 10 days agoMITView on GitHub
Guide for wiring Hydrogen request handlers in server frameworks. Use when adding, modifying, or reviewing handleShopifyRoutes, handleShopifyRedirects, SFAPI proxy routes, cart, predictive search, and Customer Account server handlers, UCP business profiles, checkout redirects, cart and UCP buy permalinks, AJAX cart proxy routes, /admin redirects, Storefront URL redirects, requestContext response-header propagation, or framework middleware, not-found, and catch-all integration.
1 other project uses a version of this, 1 of them edited.
Adopted by
Most recently taken up by
- Shopify/hydrogenedited, first seen Oct 13, 2026
Other versions1 project uses a version of this.
Word for word · 0
None found.
Edited · 1
- Shopify/hydrogen★ 2.2k66% same
Wrote their own version · 0
None found.
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository21 other files it gives its agents.
- AGENTS.mdAGENTS.md
- hydrogen-analyticsSkill
- hydrogen-cart-drawerSkill
- hydrogen-cart-metafieldsSkill
- hydrogen-cart-uiSkill
- hydrogen-collection-browserSkill
- hydrogen-customer-accountSkill
- hydrogen-imageSkill
- hydrogen-local-httpsSkill
- hydrogen-marketsSkill
- hydrogen-moneySkill
- hydrogen-oxygenSkill
- hydrogen-predictive-searchSkill
- hydrogen-routingSkill
- hydrogen-setupSkill
- hydrogen-shop-paySkill
- hydrogen-smoke-testSkill
- hydrogen-storefront-clientSkill
- hydrogen-variant-formSkill
- remix-storeSkill
- testing-practicesSkill
The file
We split this skill into the rules it gives an agent
7 rules. About 0 are common, 2 are distinctive, and 5 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈2
Distinctive · estimate
This author's own choices. Worth a look.
5
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 64
Use the local hydrogen-routing skill to create the shared routeTemplates manifest.
- Very specific: line 76
Default to one request-scoped public Storefront client per request.
- Very specific: line 78
When creating a private client, resolve trusted buyerIp first and pass it to createShopifyRequestContext.
- Very specific: line 79
Create requestContext with createShopifyRequestContext({ request, i18n, buyerIp }) where buyer context exists and the framework exposes a …
- Very specific: line 81
Call handleShopifyRoutes without awaiting it immediately.
- Distinctive: line 94
Use public package exports:
- Distinctive: line 110
Run the app in dev and production modes, then check:
≈ “Common” is an estimate: at least 1 in 5 of the 364,980 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Hydrogen Request Handlers
Hydrogen request handlers are framework-neutral, but the framework wiring is not. Always choose the reference for the host framework and preserve its routing gate.
Framework References
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.
Core Gate
Request
-> handleShopifyRoutes() before framework routing
-> framework router
-> handleShopifyRedirects() only after a 404
-> framework 404 pagehandleShopifyRoutes 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().
UCP Business Profile
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.
Successful profiles and 304 responses use public caching with a 60-second freshness lifetime and a 300-second stale-if-error window. Unpublished profiles return a JSON 404, and other non-JSON upstream errors become JSON errors with the upstream status. Redirects and non-JSON successes return 502; fetch timeouts return 504. All errors use Cache-Control: no-store. Methods other than GET and HEAD continue to framework routing.
Serve the storefront over HTTPS and wire handleShopifyRoutes before framework routing so the profile is available without an app-owned route. Return the matched response directly without adding session headers or applying request-context headers again.
Variant Id Redirects
const shopifyRoute = handleShopifyRoutes({
request,
requestContext,
sessionManager,
storefrontClient,
routeTemplates,
handlers: [cartHandlers],
});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.
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.
Standard Route Redirects
Use the local hydrogen-routing skill to create the shared routeTemplates manifest. Wire that object into both handleShopifyRoutes before routing and handleShopifyRedirects after the app router returns a 404.
const redirect = await handleShopifyRedirects({
request,
storefrontClient,
routeTemplates,
});Rules
- Default to one request-scoped public Storefront client per request;
publicStorefrontTokenmay 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. - Route handlers, cart server handlers, and
handleShopifyRedirectsaccept any provided Storefront client. - When creating a private client, resolve trusted
buyerIpfirst and pass it tocreateShopifyRequestContext. Use thehydrogen-storefront-clientbuyer-IP guidance for the app's deployment. - Create
requestContextwithcreateShopifyRequestContext({ request, i18n, buyerIp })where buyer context exists and the framework exposes a realRequest; userequest: { headers }only when noRequestexists. - Pass the same request-scoped
requestContext,storefrontClient, andsessionManagerintohandleShopifyRoutesand registered handler groups. - Call
handleShopifyRouteswithout awaiting it immediately. It returnsnullsynchronously when no route matches; only return or await the promise after checking that it is truthy. - If the app has a request-level
try/catchthat converts errors into aResponse, usereturn await shopifyRouteinside that boundary so rejected route promises reach the same error handling as synchronous setup failures. If the framework owns request error handling, returnshopifyRoutedirectly. Do not add an inline.catch()unless the matched route intentionally needs different error handling. - Pass
requestandstorefrontClientintohandleShopifyRedirects; it does not receive a session manager. - Pass registered handler groups explicitly, for example
handlers: [cartHandlers, customerAccountHandlers]. - Pass
routeTemplatesintohandleShopifyRoutesso Liquid-parity?variant=product links resolve to canonical option params instead of passing through as ordinary product-page requests. handleShopifyRoutesandhandleShopifyRedirectsapply request-context response headers before returning matched Shopify responses. Return those responses directly without callingrequestContext.applyResponseHeaders()again.- Link and submit to Customer Account routes (
/account/login,/account/authorize,/account/refresh,/account/logout) with plain HTML<a>/<form>, never the framework's client-side navigation component (<Form>/<Link>in React Router,next/linkin Next.js,NuxtLinkin Nuxt). The login and logout handlers return raw HTTP redirects to external Shopify URLs, which client-nav cannot process. - Apps authoring Customer Account API documents use the same packed Hydrogen TypeScript plugin as Storefront API documents. Add
@shopify/hydrogen/ts-plugintotsconfig.jsoncompilerOptions.pluginsand chainhydrogen gql checkinto a package script. Applies to every framework. - For custom or framework-routed responses, commit session headers once at the final response boundary, append those headers, then call
requestContext.applyResponseHeaders(response.headers)so eligible SFAPI cookies and personalized-response cache safety are applied. - Wire this in production runtime code, not dev-only hooks. Only GraphiQL is dev-only.
Imports
Use public package exports:
import {
createCartServerHandlers,
createPredictiveSearchServerHandlers,
createShopifyRequestContext,
createStorefrontClient,
handleShopifyRedirects,
handleShopifyRoutes,
} from "@shopify/hydrogen";
import { createCustomerAccountServerHandlers } from "@shopify/hydrogen/customer-account";Verify
Run the app in dev and production modes, then check:
GET /.well-known/ucpreturns Shopify's UCP business profile with a public cache policy and no shopper cookies.HEADreturns headers without a body. A conditional request with a matchingIf-None-Matchreturns304; an unpublished profile returns an uncached JSON404.POST /api/{api-version}/graphql.jsonreturns Storefront API JSON, not the app 404.GET /api/cartreturns cart handler JSON when cart handlers are registered. With no cart id, the body is{cart: null}and no Storefront API cart lookup is made.GET /api/predictive-search?q=snowreturns predictive search JSON when predictive search handlers are registered.GET /account/login,GET /account/authorize,GET /account/refresh, andPOST /account/logoutare handled before the app router when Customer Account handlers are registered.GET /adminreturns a redirect to the shop admin URL.- An unknown path returns the framework 404 when no Shopify redirect exists.
GET /products/{handle}?variant={numeric id}returns a 302 to the option-params URL whenrouteTemplatesis passed tohandleShopifyRoutes;?variant=garbagefalls through to the product page.- Cart, Customer Account, and consent responses preserve eligible
Set-Cookieheaders. Consent responses remain private and non-cacheable even when personal state is returned only in the body. - Authenticated Customer Account responses do not preserve public or CDN cache-control headers.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

