Request context
The createShopifyRequestContext function creates the context for one incoming request. Use the context to forward the customer's cookies, locale, and IP address to Shopify, and to apply Hydrogen's response headers.
Import createShopifyRequestContext from @shopify/hydrogen.
Create one context per request, and pass the same context to createStorefrontClient, createCustomerAccountClient, and handleShopifyRoutes.
To resolve the customer's market for each request, refer to Pass the market to the request context.
Anchor to Context setupContext setup
Creates the context for one incoming request. Pass the same context to the Storefront API client, the Customer Account API client, and . The context resolves the request's locale from your i18n definition, forwards the customer's cookies, locale, and privacy signal to Shopify, and adds Shopify's cookies and cache headers to your response.
Call on each response that your app builds. Pass with the customer's trusted IP address when you use a private Storefront API client. The function throws when i18n doesn't come from , when locale isn't one of the definition's supported locales, and when is an empty string.
- Anchor to inputinputinput(ShopifyRequestContextInputBase<TI18n> | LegacyShopifyRequestContextInput<I18nConfig>) & { ...; }(ShopifyRequestContextInputBase<TI18n> | LegacyShopifyRequestContextInput<I18nConfig>) & { ...; }requiredrequired
The incoming request, the storefront's i18n definition, and the customer's IP address for private Storefront API clients.
The context to pass to Hydrogen's API clients and route handlers for this request.
ShopifyRequestContextInputBase
The incoming request and the storefront's i18n definition.
- i18n
The storefront's i18n definition from `defineShopifyI18n`. Hydrogen matches the request's locale against it.
TI18n - locale
The locale to use instead of matching the request URL. The locale must be one of the definition's supported locales. Pass it when the request has no meaningful URL, such as during static rendering.
ShopifyLocale - request
The incoming request from your framework. When the framework exposes no request, such as during prerendering, pass `{ headers: new Headers() }`.
StorefrontRequest
ShopifyLocale
A `{language, country}` pair identifying one locale a storefront serves.
- country
ShopifyCountryCode - language
ShopifyLanguageCode
ShopifyCountryCode
ShopifyLanguageCode
StorefrontRequest
The incoming request's headers, plus its method, abort signal, and URL when the framework provides them.
Pick<Request, "headers"> & Partial<Pick<Request, "method" | "signal" | "url">>LegacyShopifyRequestContextInput
Deprecated: the request and a fixed locale, used for every request with no URL matching. Pass a definition from `defineShopifyI18n` as `i18n` instead. Removed in the next major release.
- i18n
Deprecated: the fixed `{language, country, pathPrefix}` for every request.
TConfig - locale
never - request
The incoming request's headers, plus its method, abort signal, and URL when the framework provides them.
StorefrontRequest
I18nConfig
Deprecated: a fixed request locale with an optional path prefix. Removed in the next major release.
- country
The request's country.
ShopifyCountryCode - language
The request's language.
ShopifyLanguageCode - pathPrefix
The URL prefix for localized routes, such as `/es-es`. Hydrogen adds the prefix to standard route redirects and product variant URLs.
string
ShopifyRequestContext
The context for one request. Pass the context to Hydrogen's API clients and route handlers for that request.
ShopifyRequestContextBase & {
/** The locale resolved for this request, with the path prefix it is served under. */
locale: RequestLocale<TI18n>;
/**
* The locale resolved for this request.
* @deprecated Use `locale` instead. Removed in the next major release.
*/
i18n: RequestLocale<TI18n>;
}ShopifyRequestContextBase
The fields and methods on every request context.
- __hydrogenShopifyRequestContextBrand
A type-only marker. Create request contexts only with `createShopifyRequestContext`.
never - applyResponseHeaders
Adds the headers that a Hydrogen storefront needs to the final response. Call the method on each response that your app builds. Responses from `handleShopifyRoutes` and `handleShopifyRedirects` already carry these headers. Append your committed session headers before you call the method. The method makes any response that sets a cookie private and uncacheable. The method also sets the `powered-by` header, makes responses marked with `markResponseAsPersonalized()` private and uncacheable, and adds eligible Shopify cookies only to non-document responses for methods other than `GET` and `HEAD`. Pass the response's `status` as well. When the status is `429` and the Storefront API rate limited a request that used this context, the method sets `Cache-Control: no-store` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. It also sets `Retry-After` to the later of the response's own valid `Retry-After` value and the latest valid retry deadline from all Storefront API `429` responses on this context, including recovered errors. Delay-seconds and IMF-fixdates are accepted. The value is the remaining delay-seconds, rounded up and never negative. React Router doesn't copy the headers of a thrown response, so this keeps the headers of a `429` from `withStorefrontRateLimit`. Responses with other statuses keep their cache headers. When you omit `status` after a Storefront API rate limit, the method logs one warning and adds no rate-limit headers. The `429` response can then lose `Retry-After` and `Cache-Control: no-store`.
(headers: Headers, status?: number) => void - applyStorefrontRequestHeaders
Adds the Hydrogen SDK headers and the customer's cookie, privacy, and origin headers to a Storefront API request. The Storefront API client and the API proxies call the method for you.
(headers: Headers) => void - buyerIp
The customer's trusted IP address. Private Storefront API clients require it.
string - captureStorefrontRateLimit
Tracks Storefront API `429` responses and the latest valid retry deadline, independent of completion order. Delay-seconds start at capture time; HTTP dates specify absolute deadlines. Invalid values do not replace valid advice. The Storefront API client calls the method for you.
(retryAfter: string) => void - captureSubrequestHeaders
Saves the cookies from the first Storefront API response that sets cookies. The Storefront API client calls the method for you, and `applyResponseHeaders()` can add the cookies to your response.
(headers: Headers) => void - consumeStorefrontResponseHeaders
Saves the cookies from a proxied Storefront API response and removes the `set-cookie` header from that response. The API proxies in `handleShopifyRoutes` call the method for you.
(headers: Headers) => void - cookie
The incoming request's `Cookie` header. Hydrogen forwards the header to the Storefront API.
string - getForwardedRequestHeaders
Returns the incoming request's headers with Shopify's request headers added. Pass the headers when you forward the request to a proxy or another origin.
() => Headers - i18nDefinition
The i18n definition the context matched its locale against. Absent for the deprecated fixed-locale input.
ShopifyI18n - markResponseAsPersonalized
Marks the final response as private and uncacheable because the response holds customer data, such as a server-rendered cart. `applyResponseHeaders()` then sets `Cache-Control: private, no-store, max-age=0, must-revalidate` and removes `Surrogate-Control` and every vendor `*-Cache-Control` header. Call the method before `applyResponseHeaders()`, and only on requests whose response holds customer data, so other responses stay cacheable. Pass a short `reason` that names the customer data. The Customer Account API client and the customer session call the method for you.
(reason: string) => void - markResponseAsSessionEstablishing
Lets the final response set Shopify cookies before the customer has a Shopify session, and marks the response as private and uncacheable. The UCP MCP proxy calls the method for you.
(reason: string) => void - requestGroupId
The ID that groups this request's Shopify API calls. Hydrogen reads the ID from the request headers or generates one.
string - signal
The incoming request's abort signal. Hydrogen's API clients stop their requests when the signal aborts.
AbortSignal - storefrontOrigin
The origin of the incoming request's URL. Hydrogen forwards the origin to the Storefront API.
string - url
The incoming request's URL.
string
Headers
ShopifyI18n
Module-scope internationalization definition shared by the server request context, route matching, URL builders, and client scripts. Create it with `defineShopifyI18n`.
- defaultLocale
Locale used when routing determines nothing: unprefixed paths or unrecognized hostnames.
ShopifyLocale - routing
Omit for single-locale storefronts.
ShopifyI18nRouting
ShopifyI18nRouting
{
type: "pathname";
/**
* Locales served under a prefix. `defaultLocale` is served unprefixed only and must not be
* listed here, so every page has one canonical URL.
*/
locales: readonly ShopifyPathnameLocale[];
} | {
type: "domain";
/**
* Locales served per hostname. `defaultLocale` must be listed here so it has a canonical
* hostname for links and sitemaps; it is also what unrecognized hosts (localhost, preview
* URLs) resolve to.
*/
locales: readonly ShopifyDomainLocale[];
}ShopifyPathnameLocale
A locale served under a URL path prefix. The prefix is derived from the locale as `/{language}-{country}` (lowercased, `_` → `-`), so `{language: "FR", country: "CA"}` is served at `/fr-ca`. Set `pathSegment` when the derived segment is undesirable, for example `PT_BR` + `BR` derives to `pt-br-br`. A segment is a single path part: no slashes.
ShopifyLocale & {
pathSegment?: string;
}ShopifyDomainLocale
A locale served from its own hostname. Match is exact on `URL.hostname` (no port), so `fr.example.com`, `example.fr`, and `example.com` are three separate entries. Aliases such as `www.` are a redirect concern and must not be listed here.
ShopifyLocale & {
hostname: string;
}RequestLocale
The locale a request context resolves: matched from a definition, or the legacy fixed locale.
TI18n extends ShopifyI18n
? ShopifyMatchedLocale<TI18n>
: TI18n extends I18nConfig
? NormalizedI18nConfig<TI18n>
: neverShopifyMatchedLocale
A locale resolved for one request. `pathSegment` is replaced by the derived `pathPrefix` (`""` for the default locale and under domain routing), which is what URL builders consume. Domain-routed locales keep their `hostname` so canonical and `hreflang` URLs can be built.
DistributiveOmit<
ShopifySupportedLocale<TI18n>,
"pathSegment"
> & {
pathPrefix: string;
}DistributiveOmit
T extends unknown ? Omit<T, K> : neverShopifySupportedLocale
Every locale entry a definition can resolve to, keeping any extra per-locale fields.
ShopifySupportedLocale<TI18n>NormalizedI18nConfig
Omit<TConfig, "pathPrefix"> & {
pathPrefix: string;
}TypeScript
Examples
Create a request context
Description
Create a context for the incoming request and build a client from it. This example applies the context's response headers to the final response.
TypeScript
import { createShopifyRequestContext, createStorefrontClient, type StorefrontClient, } from "@shopify/hydrogen"; export async function handleRequest( request: Request, next: (storefront: StorefrontClient) => Promise<Response>, ) { const requestContext = createShopifyRequestContext({ request, i18n: { country: "US", language: "EN" }, }); const storefront = createStorefrontClient({ type: "public", requestContext, config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN! }, }); const routedResponse = await next(storefront); const response = new Response(routedResponse.body, routedResponse); requestContext.applyResponseHeaders(response.headers); return response; }Create a static context
Description
Create a context without a request for prerendering. This example builds a `private_no_buyer_context` client with a localized `pathPrefix`.
TypeScript
import { createShopifyRequestContext, createStorefrontClient } from "@shopify/hydrogen"; const requestContext = createShopifyRequestContext({ request: { headers: new Headers() }, i18n: { country: "CA", language: "FR", pathPrefix: "/fr-ca" }, }); export const prerenderStorefront = createStorefrontClient({ type: "private_no_buyer_context", requestContext, config: { storeDomain: process.env.PUBLIC_STORE_DOMAIN!, privateStorefrontToken: process.env.PRIVATE_STOREFRONT_API_TOKEN!, }, });