agentleFS
remix-runremix-run/remix-store/.agents/skills/hydrogen-request-handlers/SKILL.md

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

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
  1. Very specific:

    Use the local hydrogen-routing skill to create the shared routeTemplates manifest.

    line 64
  2. Very specific:

    Default to one request-scoped public Storefront client per request.

    line 76
  3. Very specific:

    When creating a private client, resolve trusted buyerIp first and pass it to createShopifyRequestContext.

    line 78
  4. Very specific:

    Create requestContext with createShopifyRequestContext({ request, i18n, buyerIp }) where buyer context exists and the framework exposes a …

    line 79
  5. Very specific:

    Call handleShopifyRoutes without awaiting it immediately.

    line 81
  6. Distinctive:

    Use public package exports:

    line 94
  7. Distinctive:

    Run the app in dev and production modes, then check:

    line 110

≈ “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.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

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 page

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().

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; 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.
  • Route handlers, cart server handlers, and handleShopifyRedirects accept any provided Storefront client.
  • 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.
  • 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.
  • Pass the same request-scoped requestContext, storefrontClient, and sessionManager into handleShopifyRoutes and registered handler groups.
  • 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.
  • 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.
  • Pass request and storefrontClient into handleShopifyRedirects; it does not receive a session manager.
  • Pass registered handler groups explicitly, for example handlers: [cartHandlers, customerAccountHandlers].
  • Pass routeTemplates into handleShopifyRoutes so Liquid-parity ?variant= product links resolve to canonical option params instead of passing through as ordinary product-page requests.
  • handleShopifyRoutes and handleShopifyRedirects apply request-context response headers before returning matched Shopify responses. Return those responses directly without calling requestContext.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/link in Next.js, NuxtLink in 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-plugin to tsconfig.json compilerOptions.plugins and chain hydrogen gql check into 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:

  1. GET /.well-known/ucp returns Shopify's UCP business profile with a public cache policy and no shopper cookies. HEAD returns headers without a body. A conditional request with a matching If-None-Match returns 304; an unpublished profile returns an uncached JSON 404.
  2. POST /api/{api-version}/graphql.json returns Storefront API JSON, not the app 404.
  3. GET /api/cart returns 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.
  4. GET /api/predictive-search?q=snow returns predictive search JSON when predictive search handlers are registered.
  5. GET /account/login, GET /account/authorize, GET /account/refresh, and POST /account/logout are handled before the app router when Customer Account handlers are registered.
  6. GET /admin returns a redirect to the shop admin URL.
  7. An unknown path returns the framework 404 when no Shopify redirect exists.
  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.
  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.
  10. Authenticated Customer Account responses do not preserve public or CDN cache-control headers.

Download now (ZIP)

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
What did you use it for? e.g. Reviewing pull requests in a Rails app

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.