Przejdź do treści
Biblioteka skilli
Programowanie · Integracja z narzędziem

hydrogen-request-handlers

/hydrogen-request-handlers

Prowadzi podpięcie handlerów żądań Hydrogen w frameworkach serwerowych: trasy Shopify, przekierowania, proxy Storefront API, koszyk, konto klienta i przekierowania do checkoutu.

Repozytorium
hydrogen ↗
Licencja
MIT
Ostatnia zmiana repozytorium
26.10.2026

Ocena i bezpieczeństwo

100/ 100Klasa: dobry
Format25 / 25
Frontmatter z nazwą i opisem, poprawna nazwa, opis do 1024 znaków, nazwa zgodna z folderem.
Odkrywalność25 / 25
Opis mówi, kiedy użyć skilla, ma sensowną długość i jest w 3. osobie.
Treść35 / 35
Co najmniej 150 słów i do 500 linii, nagłówki, listy kroków, przykłady albo kod.
Higiena15 / 15
Bez zaślepek typu TODO, bez ścieżek Windows, z licencją.
Ryzykobrak sygnałów w skanie
Pliki w paczce
4
Skrypty
0
Komentarze HTML
0
Adresy URL w SKILL.md
0
Przestarzałość

Brak sygnałów. Repozytorium zmienione 26.10.2026, bez odwołań do wycofanych modeli i API.

Licencja

MIT, otwarta: można używać i zmieniać, z zachowaniem informacji o autorze.

Co robi i kiedy

Prowadzi podpięcie handlerów żądań Hydrogen w frameworkach serwerowych: trasy Shopify, przekierowania, proxy Storefront API, koszyk, konto klienta i przekierowania do checkoutu.

Oryginalny opis (EN)

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.

Jak działa

  1. Framework References
  2. Core Gate
  3. UCP Business Profile
  4. Variant Id Redirects
  5. Standard Route Redirects
  6. Rules
  7. Imports
  8. Verify
Sekcje z nagłówków SKILL.md, w oryginale · 107 linii, 1 267 słów
Podgląd SKILL.md
---
name: hydrogen-request-handlers
description: >
  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.
---

# 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

```ts
const shopifyRoute = handleShopifyRoutes({
  request,
  requestContext,
  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.

```ts
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` and `storefrontClient` into `handleShopifyRoutes` and registered handler groups, plus the same request-scoped `sessionManager` when a handler needs one.
- `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.
- 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:

```ts
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.
Pliki w paczce (4)
  • SKILL.md 10 KB
  • references/frameworks.md 6 KB
  • references/nextjs.md 8 KB
  • references/nuxt.md 7 KB

Wersje

W bazie nie ma innych skilli o nazwie hydrogen-request-handlers.

Migawka bazy z 13.11.2026 · wersja paczki 512afd86448c (skrót SHA-256 całej paczki)

Pobrania w ostatnich 30 dniach: 0 · ranking

Zgłoś problem z tym skillem: szkodliwa treść, błędny opis albo prośba autora o usunięcie.

Podobne skille

  • 100hydrogen-routing
    Opisuje szablony tras Hydrogen i routing adresów URL sklepu Shopify, w tym createShopifyRouteTemplates, własne ścieżki, przekierowania i adresy wyników wyszukiwania.
  • 100hydrogen-storefront-client
    Opisuje typobezpieczny klient GraphQL Storefront API w @shopify/hydrogen: tworzenie klienta, zapytania gql(), obsługę błędów i pobieranie danych sklepu.
  • 100shopify-storefront-headless
    Buduje sklepy headless z Storefront API i Cart API Shopify: własne frontendy, konfiguracja Hydrogen, zapytania o produkty i programowe operacje na koszyku.
  • 86shopify-hydrogen
    Podaje gotowe przepisy wdrożeniowe dla sklepów Hydrogen: B2B, pakiety, koszyk, subskrypcje, Markets i inne.
  • 100shopify-hydrogen
    Buduje sklepy headless Shopify w Hydrogen: framework oparty na Remix, wdrożenie Oxygen, storefront.query(), strategie cache, koszyk, konta klientów, SEO i analityka.
  • 95headless-ecommerce
    Projektuje bezgłowe sklepy internetowe na Shopify Hydrogen i Storefront API: pobieranie danych, cache dla każdego typu danych, koszyk i wdrożenie.

Uwagi i zgłoszenia

Wiadomość trafi do Bartosza Sokolińskiego. Adres e-mail jest potrzebny tylko do odpowiedzi. Szczegóły w polityce prywatności.