Hydrogen Markets
- by Shopify
- MIT license
Guide for implementing Shopify Markets with Hydrogen.
npx skills add 'Shopify/hydrogen' --skill 'hydrogen-markets' -a claude-code -yInstalls in this project. Add -g to install globally.
Guide for implementing Shopify Markets with Hydrogen.
npx skills add 'Shopify/hydrogen' --skill 'hydrogen-markets' -a claude-code -yInstalls in this project. Add -g to install globally.
Markets are a routing concern plus Storefront API context. Hydrogen owns both halves once the storefront declares its locales: defineShopifyI18n describes which locales exist and how the URL encodes them, and createShopifyRequestContext({ request, i18n }) resolves the request's locale from that definition. Queries that declare $country and $language with @inContext(country: $country, language: $language) receive those values from the resolved locale.
If the storefront uses Next.js App Router, read references/nextjs.md before writing code. Server Components do not receive a full Request, so the locale comes from the forwarded URL header or an explicit locale override.
Define the storefront's locales once at module scope, then pass that definition where the app creates its Shopify request context:
// lib/i18n.ts
import { defineShopifyI18n } from "@shopify/hydrogen";
export const i18n = defineShopifyI18n({
defaultLocale: { language: "EN", country: "US" },
routing: {
type: "pathname",
locales: [
{ language: "EN", country: "CA" },
{ language: "FR", country: "CA" },
],
},
});
import {
createStorefrontClient,
createShopifyRequestContext,
gql,
} from "@shopify/hydrogen";
+import { i18n } from "./lib/i18n";
const PRODUCTS_PAGE_SIZE = 12;
const PRODUCTS_QUERY = gql(`
- query Products($first: Int!) {
+ query Products($first: Int!, $country: CountryCode, $language: LanguageCode)
+ @inContext(country: $country, language: $language) {
products(first: $first) {
nodes {
title
}
}
}
`);
export async function loadProducts(request: Request) {
- const requestContext = createShopifyRequestContext({
- request,
- i18n: DEFAULT_MARKET,
- });
+ const requestContext = createShopifyRequestContext({
+ request,
+ i18n,
+ });
const client = createStorefrontClient({
type: "public",
requestContext,
config: {
storeDomain: process.env.PUBLIC_STORE_DOMAIN!,
publicStorefrontToken: process.env.PUBLIC_STOREFRONT_API_TOKEN!,
},
});
return client.graphql(PRODUCTS_QUERY, {
variables: { first: PRODUCTS_PAGE_SIZE },
});
}
Do not pass country or language in every query call. The request context resolves the locale once at the request boundary and the client injects the context variables into queries that declare them.
requestContext.locale is the resolved locale for this request: { language, country, pathPrefix } (ShopifyMatchedLocale). pathPrefix is "" for the default locale and for domain routing, or a leading-slash prefix such as /fr-ca with no trailing slash. The Storefront client mirrors it as client.locale. The definition is not on the context: import it from your i18n module wherever you need it.
defineShopifyI18n returns its input unchanged with literal types preserved, so the definition is serializable and safe to import from server and client code. It validates once at module load, so a bad entry fails at startup rather than on the first request that hits it.
type ShopifyI18n = {
defaultLocale: { language: ShopifyLanguageCode; country: ShopifyCountryCode };
routing?:
| { type: "pathname"; locales: readonly ShopifyPathnameLocale[] }
| { type: "domain"; locales: readonly ShopifyDomainLocale[] };
};
routing for a single-locale storefront; every request resolves to defaultLocale.US, CA, EN, FR, PT_BR.currency) are kept on the entries returned by getSupportedLocales(i18n) and on requestContext.locale, so the app can carry its own metadata without a parallel map.Use type: "pathname" when locales share one domain and the locale is encoded in the first path segment, like /fr-ca/products/shirt.
export const i18n = defineShopifyI18n({
defaultLocale: { language: "EN", country: "US" },
routing: {
type: "pathname",
locales: [
{ language: "FR", country: "CA" },
{ language: "PT_BR", country: "BR", pathSegment: "br" },
],
},
});
/{language}-{country} lowercased with _ replaced by -: { language: "FR", country: "CA" } is served at /fr-ca. Set pathSegment when the derived segment is undesirable (PT_BR + BR would derive to pt-br-br). A segment is one path part with no slashes.defaultLocale is served unprefixed only and must not appear in locales; the definition throws if it does. Every page has one canonical URL.defaultLocale. If the router has a $locale param, treat a matched param with an empty requestContext.locale.pathPrefix as a 404 so /en-us/... and /xx/... do not render the default locale under a second URL.requestContext.locale.pathPrefix when it builds or matches standard route URLs, and handleShopifyRoutes matches registered handlers with the prefix stripped, so /fr-ca/api/cart reaches the /api/cart handler. Use the local hydrogen-routing skill for templates.The server resolves the locale from each request's URL, so under pathname routing every request and link from the browser has to carry the page's pathPrefix. A cart request to plain /api/cart from a /fr-ca page reads and writes the cart in the default market.
With the React or Vue bindings, pass the request's locale through loader data and wrap the app in LocaleProvider, above the cart and predictive search providers:
// root loader
return { locale: requestContext.locale };
// root component
import { LocaleProvider } from "@shopify/hydrogen/react"; // or "@shopify/hydrogen/vue"
// The cart route's loader reads the cart; see the `hydrogen-cart-ui` skill.
// import type { loader as cartLoader } from "./routes/($locale).cart";
const cartRoute = useRouteLoaderData<typeof cartLoader>("routes/($locale).cart");
<LocaleProvider locale={loaderData.locale}>
<CartProvider initialData={cartRoute?.cartData}>
<Outlet />
</CartProvider>
</LocaleProvider>;
{pathPrefix}/api/cart and cart and product forms post there. PredictiveSearchProvider requests {pathPrefix}/api/predictive-search and its form submits to {pathPrefix}/search. ShopifyAccount reads {pathPrefix}/account/widget-data and signs in through {pathPrefix}/account/login. A custom cart endpoint, predictiveSearchEndpoint, or searchAction that starts with / gets the prefix too, so pass those without one. Absolute URLs are used as they are.useLocale() returns the same { language, country, pathPrefix } (a ref in Vue). Build the app's own links and requests with it: `${pathPrefix}/collections` for a link, `${pathPrefix}/api/cart/metafields` for a request to an app-owned route, and getPredictiveSearchItemUrl(item, { routes, term, pathPrefix }) for a search result. For the home link use pathPrefix || "/"./fr/collections. Remove that prefix before adding the app's pathPrefix.handleShopifyRoutes matches registered handlers with the prefix stripped; a cart or search route the app serves itself has to exist under each prefix.pathPrefix and needs none of this.Without those bindings, add the prefix yourself. Configure the cart in the browser only, because the endpoint is shared by every request on the server:
configureCartEndpoint(`${locale.pathPrefix}/api/cart`);
const search = createPredictiveSearchStore({
predictiveSearchEndpoint: `${locale.pathPrefix}/api/predictive-search`,
});
Render cart and search forms with the same prefixed action.
One locale per page load. ShopifyScripts reads the locale once, when the document loads, and the cart is priced for that market. Change locale with a full page load (a plain <a href>, or reloadDocument on a React Router Link), and keep every other link under the current prefix. In development, Hydrogen logs a warning when a page under a prefix has no LocaleProvider, when LocaleProvider and ShopifyScripts hold different locales, and when a client-side navigation leaves the page's prefix.
Use type: "domain" when each locale has its own hostname: example.com, example.ca, fr.example.com.
export const i18n = defineShopifyI18n({
defaultLocale: { language: "EN", country: "US" },
routing: {
type: "domain",
locales: [
{ language: "EN", country: "US", hostname: "example.com" },
{ language: "EN", country: "CA", hostname: "example.ca" },
{ language: "FR", country: "FR", hostname: "fr.example.com" },
],
},
});
URL.hostname (no port), so fr.example.com, example.fr, and example.com are three separate entries. Hostname comparison is case-insensitive.defaultLocale must be listed so it has a canonical hostname for links and sitemaps. Unrecognized hosts (localhost, preview URLs) resolve to defaultLocale.www. and other aliases are a redirect concern. Do not list them as locales.pathPrefix is always "" under domain routing.Use the exported helpers instead of string-building URLs:
import {
getLocalizedHref,
getSupportedLocales,
isSameLocale,
type ShopifyLocale,
} from "@shopify/hydrogen";
import { i18n } from "./lib/i18n";
export function getAlternateLinks(currentUrl: string, currentLocale: ShopifyLocale) {
return getSupportedLocales(i18n)
.filter((locale) => !isSameLocale(locale, currentLocale))
.map((locale) => ({
hreflang: toHreflang(locale),
href: getLocalizedHref(currentUrl, { i18n, locale }),
}));
}
// BCP 47 allows one region subtag. Regional language codes (`PT_BR`, `ZH_TW`) already carry one,
// so keep the primary language and let `country` name the region: PT_BR + BR -> `pt-BR`. The
// Chinese codes differ by script, so they keep a script subtag: ZH_TW + HK -> `zh-Hant-HK`.
function toHreflang({ language, country }: ShopifyLocale): string {
const primary = { ZH_CN: "zh-Hans", ZH_TW: "zh-Hant" }[language] ?? language.replace(/_.*$/, "").toLowerCase();
return `${primary}-${country}`;
}
hreflang values are language-REGION (optionally language-Script-REGION). Do not build them as ${language}-${country}: Shopify's regional language codes would yield two region subtags (pt-br-BR), which is invalid. Two locales must never collapse to the same tag; fail loudly if they do.
getLocalizedHref(href, { i18n, locale }) rewrites an href to the same page in another locale. Under pathname routing it returns a path with any existing locale prefix replaced; under domain routing it returns an absolute https: URL on the target hostname; with no routing it returns the input unchanged. It throws when locale is not defined in i18n.
getSupportedLocales(i18n) returns every locale the definition can resolve to, default first, keeping pathSegment / hostname and any extra fields.
matchLocale(request | url, i18n) exposes the same resolution the request context uses, for sitemaps or tests that hold a URL but no request context.
resolveSupportedLocale(locale, i18n) resolves a locale the app already chose (a selector value, a stored preference) to its pathPrefix/hostname, throwing when it is not in the definition. Use it to validate user input before redirecting.
Persist an explicit buyer choice by redirecting to getLocalizedHref(...); do not resolve the locale from a cookie on the server. Render switcher links as full page loads, not client-side navigations (see "Browser Requests And Links").
Read the relevant reference before applying the generic Request examples in frameworks that do not expose the full incoming request to server code.
references/nextjs.md first. Server Components can read headers() but not the current URL or a standard Request; the per-request client resolves the locale from the forwarded x-storefront-url header, and module-scope static clients pin locale explicitly.defineShopifyI18n. Keep the definition in a module both server and client code can import. Do not hand-roll host allowlists or path parsers; the definition is the allowlist.createShopifyRequestContext({ request, i18n }). Pass a real Request when the framework has one so request.url drives matching. With request: { headers }, the forwarded x-storefront-url header is used instead.locale only when there is no meaningful URL. Static rendering, background jobs, and module-scope clients set locale: i18n.defaultLocale (or another supported locale). The override is validated against the definition and throws for unsupported locales.requestContext.locale, never from requestContext.i18n. i18n is a deprecated alias kept for apps that still pass a fixed {language, country, pathPrefix}; it is removed in the next major release.country and language variable values when the document declares $country and $language; it does not rewrite query text. Market-sensitive queries still need @inContext(country: $country, language: $language) or equivalent Storefront API context in the document.amount and currencyCode returned by Shopify and format them with the local hydrogen-money skill's formatMoney() guidance.requestContext.locale (plus optional currency) as the ShopifyScripts i18n prop so Shopify globals match Storefront API context, and pass the same locale to LocaleProvider so cart and predictive search requests carry its pathPrefix.<html lang> with getHtmlLang(locale.language). It converts Shopify language codes to BCP 47 (PT_BR → pt-BR, ZH_TW → zh-Hant). Do not lowercase the enum or append the market country: <html lang> names the content language, while hreflang names the targeted region.Test locale resolution with plain Request objects against the definition. You do not need a framework test harness.
import { matchLocale } from "@shopify/hydrogen";
import { describe, expect, it } from "vitest";
import { i18n } from "./i18n";
describe("i18n", () => {
it("resolves a prefixed locale", () => {
const request = new Request("https://example.com/fr-ca/products/shirt");
expect(matchLocale(request, i18n)).toEqual({
language: "FR",
country: "CA",
pathPrefix: "/fr-ca",
});
});
it("falls back to the default locale for unknown prefixes", () => {
const request = new Request("https://example.com/xx/products/shirt");
expect(matchLocale(request, i18n).pathPrefix).toBe("");
});
});
Also test at least one Storefront API call through a mocked fetch and assert the GraphQL variables include the expected country and language when the query declares them.
Under pathname routing, also check the browser: on a page under a locale prefix, add to cart and confirm the request goes to {pathPrefix}/api/cart and the cart shows that market's currency.
requestContext.locale.pathPrefix; do not bake prefixes such as /en-ca into template values.