hydrogen-markets
Skill218 starsChanged 4 days agoMITView on GitHub
Guide for implementing Shopify Markets with Hydrogen. Use when adding market routing, country/language localization, Shopify Markets, subdomains, per-market domains, path-prefixed markets, defineShopifyI18n, locale switchers, hreflang links, Next.js App Router market routing, or Storefront API @inContext wiring.
- Reads credentials
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.2k74% 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 repository23 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-moneySkill
- hydrogen-oxygenSkill
- hydrogen-predictive-searchSkill
- hydrogen-request-handlersSkill
- hydrogen-robots-txtSkill
- hydrogen-routingSkill
- hydrogen-setupSkill
- hydrogen-shop-paySkill
- hydrogen-smoke-testSkill
- hydrogen-storefront-clientSkill
- hydrogen-variant-formSkill
- migrate-to-hydrogen-2026-10Skill
- remix-storeSkill
- testing-practicesSkill
The file
We split this skill into the rules it gives an agent
9 rules. About 0 are common, 2 are distinctive, and 7 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.
7
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 18
If the storefront uses Next.js App Router, read references/nextjs.md before writing code.
- Very specific: line 89
Do not pass country or language in every query call.
- Very specific: line 117
Use type: "pathname" when locales share one domain and the locale is encoded in the first path segment, like /fr-ca/products/shirt.
- Very specific: line 141
Use type: "domain" when each locale has its own hostname: example.com, example.ca, fr.example.com.
- Distinctive: line 166
Use the exported helpers instead of string-building URLs:
- Very specific: line 208
Read the relevant reference before applying the generic Request examples in frameworks that do not expose the full incoming request to …
- Very specific: line 216
Define locales once with
defineShopifyI18n: Keep the definition in a module both server and client code can import. - Distinctive: line 226
Ask before choosing the routing type: If the app does not already make locale selection clear, ask whether path prefixes or per-locale …
- Very specific: line 232
Test locale resolution with plain Request objects against the definition.
≈ “Common” is an estimate: at least 1 in 5 of the 372,429 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
Markets
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.
Core Rule
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.
Definition Shape
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[] };
};- Omit
routingfor a single-locale storefront; every request resolves todefaultLocale. - Codes are the Storefront API enums:
US,CA,EN,FR,PT_BR. - Extra per-locale fields (labels,
currency) are kept on the entries returned bygetSupportedLocales(i18n)and onrequestContext.locale, so the app can carry its own metadata without a parallel map. - Cookie-based, geolocation-based, or buyer-preference routing is not a routing type. Read those signals in the app and redirect to a canonical URL; the URL stays the only input to locale resolution.
Path Prefixes
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" },
],
},
});- The prefix derives as
/{language}-{country}lowercased with_replaced by-:{ language: "FR", country: "CA" }is served at/fr-ca. SetpathSegmentwhen the derived segment is undesirable (PT_BR+BRwould derive topt-br-br). A segment is one path part with no slashes. defaultLocaleis served unprefixed only and must not appear inlocales; the definition throws if it does. Every page has one canonical URL.- Unknown first segments resolve to
defaultLocale. If the router has a$localeparam, treat a matched param with an emptyrequestContext.locale.pathPrefixas a 404 so/en-us/...and/xx/...do not render the default locale under a second URL. - Route templates stay prefix-free. Hydrogen prepends
requestContext.locale.pathPrefixwhen it builds or matches standard route URLs, andhandleShopifyRoutesmatches registered handlers with the prefix stripped, so/fr-ca/api/cartreaches the/api/carthandler. Use the localhydrogen-routingskill for templates.
Per-Market Domains And Subdomains
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" },
],
},
});- Match is exact on
URL.hostname(no port), sofr.example.com,example.fr, andexample.comare three separate entries. Hostname comparison is case-insensitive. defaultLocalemust be listed so it has a canonical hostname for links and sitemaps. Unrecognized hosts (localhost, preview URLs) resolve todefaultLocale.www.and other aliases are a redirect concern. Do not list them as locales.pathPrefixis always""under domain routing.
Locale Switchers And Alternate Links
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}`;
}hreflangvalues arelanguage-REGION(optionallylanguage-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 absolutehttps:URL on the target hostname; with no routing it returns the input unchanged. It throws whenlocaleis not defined ini18n.getSupportedLocales(i18n)returns every locale the definition can resolve to, default first, keepingpathSegment/hostnameand 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 itspathPrefix/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.
Framework Exceptions
Read the relevant reference before applying the generic Request examples in frameworks that do not expose the full incoming request to server code.
- Next.js App Router — read
references/nextjs.mdfirst. Server Components can readheaders()but not the current URL or a standardRequest; the per-request client resolves the locale from the forwardedx-storefront-urlheader, and module-scope static clients pinlocaleexplicitly.
Rules
- Define locales once with
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. - Resolve the locale through
createShopifyRequestContext({ request, i18n }). Pass a realRequestwhen the framework has one sorequest.urldrives matching. Withrequest: { headers }, the forwardedx-storefront-urlheader is used instead. - Pass
localeonly when there is no meaningful URL. Static rendering, background jobs, and module-scope clients setlocale: i18n.defaultLocale(or another supported locale). The override is validated against the definition and throws for unsupported locales. - Read the resolved locale from
requestContext.locale, never fromrequestContext.i18n.i18nis a deprecated alias kept for apps that still pass a fixed{language, country, pathPrefix}; it is removed in the next major release. - Use market-contextualized queries. The Storefront client injects
countryandlanguagevariable values when the document declares$countryand$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. - Do not calculate currency locally. Render
amountandcurrencyCodereturned by Shopify and format them with the localhydrogen-moneyskill'sformatMoney()guidance. - Keep ShopifyScripts in the same locale. Pass
requestContext.locale(plus optionalcurrency) as theShopifyScriptsi18nprop so Shopify globals match Storefront API context. - Keep route templates prefix-free. Hydrogen applies
requestContext.locale.pathPrefix; do not bake prefixes such as/en-cainto template values. - Keep translations separate. Shopify Markets context localizes Shopify data. Application UI strings still need the app's translation system.
- Treat geolocation as a hint, not truth. Buyers travel, use VPNs, and intentionally choose markets. Redirect to a canonical locale URL when the app supports switching.
- Ask before choosing the routing type. If the app does not already make locale selection clear, ask whether path prefixes or per-locale domains should own it before writing code.
Testing
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.
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.

