# General Translation Integrations: Localising Shopify Hydrogen with React Router
URL: https://generaltranslation.com/en-GB/docs/integrations/shopify/guides/localizing-react-router.mdx
Docs index: https://generaltranslation.com/llms.txt
Description: How to add gt-react to a Hydrogen storefront on React Router and keep Shopify's language context in step with it.

In a React Router storefront, `gt-react` translates the copy in your code and Hydrogen talks to Shopify. The Shopify-specific work is giving Hydrogen&#39;s request context the same locale as the page, and keeping links, the Basket, and search in that locale.

This guide adds French and Japanese under `/fr` and `/ja` to Hydrogen&#39;s React Router template, with English unprefixed. Every step names the template file it changes; in your own app, make the same change wherever you create the Shopify request context, the root loader, and your links.

*Note: This guide matches `@shopify/hydrogen` 2026.10.3 on React Router 8, or on React Router 7 with `future.v8_middleware: true` in `react-router.config.ts`, as in Hydrogen&#39;s React Router template.*

## Before you start [#before-start]

* Start from Hydrogen&#39;s React Router template, or set up Hydrogen in your React Router app with `npx @shopify/hydrogen setup`. Your root middleware creates the Shopify request context and Storefront client, and runs `handleShopifyRoutes`.
* Follow steps 1 to 3 of the [React Router Quickstart](/docs/react/react-router-quickstart): install `gt-react` and `gt`, and create `gt.config.json` and `app/loadTranslations.ts`. This guide replaces its step 4, because the locale comes from the URL instead of a cookie.

```json title="gt.config.json"
{
  "defaultLocale": "en",
  "locales": ["fr", "ja"],
  "files": {
    "gt": {
      "output": "app/_gt/[locale].json"
    }
  }
}
```

*Note: [`npx gt init`](/docs/cli/reference/commands/init) creates `gt.config.json`, the loader, and the translation files, but leaves the template&#39;s `app/root.tsx` unchanged. Set up the root in [Wire up the root](#root).*

## Resolve the locale from the URL [#request-locale]

Read the locale from the request path, so every locale has its own URL. Put the helpers in one module that `gt-react`, Hydrogen, and your links share:

```ts title="app/lib/i18n.ts"
import type { ShopifyLanguageCode, ShopifyLocale } from "@shopify/hydrogen";
import gtConfig from "../../gt.config.json";

// One entry for every locale in gt.config.json.
const SHOPIFY_LANGUAGES: Record<string, ShopifyLanguageCode> = { en: "EN", fr: "FR", ja: "JA" };

// The market you sell in. Every language uses it, so switching language never changes prices.
const COUNTRY = "US";

/** The Shopify language and country for a General Translation locale. */
export function toShopifyLocale(locale: string): ShopifyLocale {
  return { language: SHOPIFY_LANGUAGES[locale], country: COUNTRY };
}

export const LOCALE_COOKIE_NAME = "shop_locale";

const allLocales = [gtConfig.defaultLocale, ...gtConfig.locales];

export function readCookie(request: Request, name: string): string | undefined {
  const cookie = request.headers
    .get("Cookie")
    ?.split(/;\s*/)
    .find((part) => part.startsWith(`${name}=`));
  return cookie?.slice(name.length + 1);
}

/**
 * "/fr/products/x" -> "fr"; unprefixed pages use the default locale. Hydrogen's `/api` handlers
 * use the locale of the page that called them, which the root middleware keeps in a cookie.
 */
export function getRequestLocale(request: Request): string {
  const { pathname } = new URL(request.url);
  const [, segment] = pathname.split("/");
  if (gtConfig.locales.includes(segment)) return segment;
  if (!pathname.startsWith("/api/")) return gtConfig.defaultLocale;
  const remembered = readCookie(request, LOCALE_COOKIE_NAME);
  // Only a configured locale is trusted; anything else falls back to the default.
  return remembered && allLocales.includes(remembered) ? remembered : gtConfig.defaultLocale;
}

/** Page loads and client navigations, but not `/api` calls or speculative prefetches. */
export function isPageNavigation(request: Request): boolean {
  const purpose = `${request.headers.get("Purpose") ?? ""} ${request.headers.get("Sec-Purpose") ?? ""}`;
  return (
    request.method === "GET" &&
    !new URL(request.url).pathname.startsWith("/api/") &&
    !purpose.includes("prefetch")
  );
}

/** "/products/x" -> "/fr/products/x"; the default locale keeps the unprefixed path. */
export function localizePath(pathname: string, locale: string): string {
  if (locale === gtConfig.defaultLocale) return pathname;
  return pathname === "/" ? `/${locale}` : `/${locale}${pathname}`;
}

/** "/fr/products/x" -> "/products/x"; unprefixed paths are returned as they are. */
export function stripLocale(pathname: string): string {
  const [, segment, ...rest] = pathname.split("/");
  return gtConfig.locales.includes(segment) ? `/${rest.join("/")}` : pathname;
}
```

Hydrogen&#39;s Basket and predictive search call `/api/cart` and `/api/predictive-search` without a locale prefix. `getRequestLocale` gives those requests the locale of the page that called them, from a cookie the root middleware sets, so a French page&#39;s Basket and search results show French catalogue text. The URL stays the only source of the locale for pages.

## Pass the locale to Shopify [#storefront-language]

Declare the same locales in Hydrogen&#39;s i18n definition, so Hydrogen knows each locale&#39;s path prefix. In the template, the definition is in `app/lib/shop.ts`:

```ts title="app/lib/shop.ts"
import { defineShopifyI18n } from "@shopify/hydrogen";
import gtConfig from "../../gt.config.json"; // [!code ++]
import { toShopifyLocale } from "~/lib/i18n"; // [!code ++]

export const i18n = defineShopifyI18n({
  defaultLocale: { country: "US", language: "EN" }, // [!code --]
  defaultLocale: toShopifyLocale(gtConfig.defaultLocale), // [!code ++]
  // [!code ++:4]
  routing: {
    type: "pathname",
    locales: gtConfig.locales.map((locale) => ({ ...toShopifyLocale(locale), pathSegment: locale })),
  },
});
```

`pathSegment` serves each locale under its General Translation code, such as `/fr`, instead of Hydrogen&#39;s default `/fr-us`. Hydrogen adds the prefix to the product variant and standard route redirects it returns, and `handleShopifyRoutes` still finds its handlers under a prefix.

Then pass the request&#39;s locale to `createShopifyRequestContext`, so the cookie decides the locale of Hydrogen&#39;s `/api` handlers. In the template, the request context is created in `app/lib/storefront.ts`:

```ts title="app/lib/storefront.ts"
import { getRequestLocale, toShopifyLocale } from "~/lib/i18n"; // [!code ++]

export function createRequestStorefrontClient(
  request: Request,
  env: Env,
  cache: CacheInstance,
  waitUntil: ExecutionContext["waitUntil"],
): RequestStorefrontClient {
  // The page's locale; for Hydrogen's /api handlers, the locale of the page that called them. // [!code ++]
  const locale = toShopifyLocale(getRequestLocale(request)); // [!code ++]
  if (shouldUseMockShop(env)) {
    return createStorefrontClient({
      type: "public",
      requestContext: createShopifyRequestContext({ request, i18n }), // [!code --]
      requestContext: createShopifyRequestContext({ request, i18n, locale }), // [!code ++]
      // ...
    });
  }

  return createStorefrontClient({
    type: "private",
    requestContext: createShopifyRequestContext({
      request,
      i18n,
      locale, // [!code ++]
      buyerIp: getBuyerIp(request.headers),
    }),
    // ...
  });
}
```

The Storefront client then fills `$language` and `$country` in every query that declares `@inContext(country: $country, language: $language)`.

This guide keeps the US market for every language, so switching to French changes the copy without changing the Basket&#39;s buyer country or currency. For multiple markets, return each locale&#39;s country from `toShopifyLocale` and move the Basket when the language changes. (See [Selling in multiple markets](/docs/integrations/shopify/guides/selling-in-markets)).

## Wire up the root [#root]

In `app/root.tsx`, initialise `gt-react`, return the locale and a translations snapshot from the root loader, render `<html lang>` and [`GTProvider`](/docs/react/reference/components/gt-provider), and set the locale cookie in the root middleware:

```tsx title="app/root.tsx"
import { handleShopifyRedirects, handleShopifyRoutes } from "@shopify/hydrogen";
import { ShopifyScripts } from "@shopify/hydrogen/react";
import { getTranslationsSnapshot, GTProvider, initializeGT } from "gt-react"; // [!code ++]
import { getRequestLocale, isPageNavigation, LOCALE_COOKIE_NAME, readCookie } from "~/lib/i18n"; // [!code ++]
import gtConfig from "../gt.config.json"; // [!code ++]
import loadTranslations from "./loadTranslations"; // [!code ++]

initializeGT({ ...gtConfig, loadTranslations }); // [!code ++]

export const middleware: Route.MiddlewareFunction[] = [
  async ({ context, request }, next) => {
    // ...
    const response = await next();
    // ...
    // [!code ++:6]
    // Remember the page's locale for Hydrogen's /api handlers. Set the cookie before
    // applyResponseHeaders, which makes any response that sets a cookie private and uncacheable.
    const locale = getRequestLocale(request);
    if (isPageNavigation(request) && readCookie(request, LOCALE_COOKIE_NAME) !== locale) {
      response.headers.append("Set-Cookie", `${LOCALE_COOKIE_NAME}=${locale}; Path=/; SameSite=Lax`);
    }
    requestContext.applyResponseHeaders(response.headers);
    return response;
  },
];

export async function loader({ context, request }: Route.LoaderArgs) {
  const env = context.get(envContext);
  const storefrontClient = context.get(storefrontClientContext);
  const gtLocale = getRequestLocale(request); // [!code ++]
  const [cartResult, layout, translations] = await Promise.all([
    cartHandlers.get({ storefrontClient, request }),
    loadRootLayout(storefrontClient),
    getTranslationsSnapshot(gtLocale), // [!code ++]
  ]);

  return {
    // ...
    locale: storefrontClient.locale,
    gtLocale, // [!code ++]
    translations, // [!code ++]
  };
}

export function Layout({ children }: { children: ReactNode }) {
  // ...
  const rootData = useRouteLoaderData<typeof loader>("root");

  return (
    <html lang="en"> {/* [!code --] */}
    <html lang={rootData?.gtLocale ?? gtConfig.defaultLocale}> {/* [!code ++] */}
      {/* ... */}
    </html>
  );
}

export default function App({ loaderData }: Route.ComponentProps) {
  return (
    <GTProvider locale={loaderData.gtLocale} translations={loaderData.translations}> {/* [!code ++] */}
      <CartProvider initialData={loaderData.cartData}>
        {/* ... */}
      </CartProvider>
    </GTProvider> {/* [!code ++] */}
  );
}
```

* The template&#39;s root loader already returns Shopify&#39;s locale as `locale`, which `ShopifyScripts` reads, so the `gt-react` locale is returned as `gtLocale`.
* [`GTProvider`](/docs/react/reference/components/gt-provider) wraps `App`, which always has loader data. The root `ErrorBoundary` renders outside it, so keep error pages untranslated.
* A page response that sets the cookie isn&#39;t cached, so the cookie is set only on a shopper&#39;s first page view and when they change language.

## Serve pages under a locale prefix [#routes]

Nest your pages under an optional `:locale?` layout route. Keep Hydrogen&#39;s catch-all route last, so unmatched paths still reach its redirects:

```ts title="app/routes.ts"
import { type RouteConfig, index, route } from "@react-router/dev/routes";

export default [
  // Pages render with no prefix or with a target-locale prefix, such as /fr.
  route(":locale?", "routes/locale.tsx", [
    index("routes/home.tsx"),
    route("products/:handle", "routes/product.tsx"),
    route("collections", "routes/collections.tsx"),
    route("collections/:handle", "routes/collection.tsx"),
    route("cart", "routes/cart.tsx"),
    route("search", "routes/search.tsx"),
    route("account", "routes/account.tsx"),
  ]),
  route("robots.txt", "routes/robots.ts"),
  route("*", "routes/catchall.tsx"),
] satisfies RouteConfig;
```

In the layout route, respond with 404 when the segment is not a target locale, so `/en/...` and unknown prefixes don&#39;t render a second copy of a page:

```tsx title="app/routes/locale.tsx"
import { Outlet } from "react-router";

import gtConfig from "../../gt.config.json";

import type { Route } from "./+types/locale";

// Only target locales are valid prefixes; the default locale stays unprefixed.
export function loader({ params }: Route.LoaderArgs) {
  if (params.locale && !gtConfig.locales.includes(params.locale)) {
    throw new Response(null, { status: 404 });
  }
  return null;
}

export default function LocaleLayout() {
  return <Outlet />;
}
```

With file-based routes, name the layout `($locale).tsx` and nest page files under it instead.

Hydrogen&#39;s own handlers, such as `/api/cart`, `/api/predictive-search`, `/checkout`, and the Customer Account routes, answer in the root middleware before any page renders, so they stay unprefixed.

## Link within the locale [#links]

Keep route paths in your code unprefixed, and add the current locale&#39;s prefix when you render a link. Create a `Link` that does this, and import it instead of React Router&#39;s:

```tsx title="app/components/LocalizedLink.tsx"
import { useLocale } from "gt-react";
import { Link as RouterLink, NavLink as RouterNavLink, type LinkProps, type NavLinkProps } from "react-router";

import { localizePath } from "~/lib/i18n";

function localizeTo(to: LinkProps["to"], locale: string): LinkProps["to"] {
  if (typeof to === "string") return to.startsWith("/") ? localizePath(to, locale) : to;
  return to.pathname?.startsWith("/") ? { ...to, pathname: localizePath(to.pathname, locale) } : to;
}

/** React Router's `Link`, with the current locale's prefix added to absolute paths. */
export function Link({ to, ...props }: LinkProps) {
  return <RouterLink to={localizeTo(to, useLocale())} {...props} />;
}

/** React Router's `NavLink`, with the current locale's prefix added to absolute paths. */
export function NavLink({ to, ...props }: NavLinkProps) {
  return <RouterNavLink to={localizeTo(to, useLocale())} {...props} />;
}

/** Adds the current locale's prefix to a path, for `navigate()` calls and form actions. */
export function useLocalizedPath(): (path: string) => string {
  const locale = useLocale();
  return (path) => localizePath(path, locale);
}
```

```tsx
import { Link } from "react-router"; // [!code --]
import { Link } from "~/components/LocalizedLink"; // [!code ++]
```

Absolute paths passed to `navigate()` or a form&#39;s `action` need the prefix too. In the template, wrap them with `useLocalizedPath`:

* The search form&#39;s `action="/search"` in `app/routes/search.tsx`.
* The search drawer&#39;s `navigate()` to the search page in `app/components/SearchDrawer.tsx`.
* The variant selector&#39;s `navigate(url)` in `app/routes/product.tsx`.

Link to Customer Account routes, such as `/account/login`, with a plain `<a>` or `<form>`, as the template does. Their handlers redirect to Shopify, which client-side navigation cannot follow.

## Switch languages [#switch-languages]

Switch languages with a full page load to the current page under the new prefix. Shopify&#39;s scripts read the locale once per page load, so a client-side navigation to another language would leave them, and the requests they send, on the previous language. Don&#39;t use [`<LocaleSelector>`](/docs/react/reference/components/locale-selector) here either: it saves the locale in a cookie and reloads the same URL, which still resolves to the old locale.

```tsx title="app/components/LanguageSwitcher.tsx"
import { useLocale, useLocales } from "gt-react";
import { useLocation } from "react-router";

import { localizePath, stripLocale } from "~/lib/i18n";

/** Switches language with a full page load, so Shopify's scripts and the basket start in the new locale. */
export function LanguageSwitcher() {
  const locale = useLocale();
  const locales = useLocales();
  const { pathname, search } = useLocation();
  return (
    <select
      aria-label="Language"
      value={locale}
      onChange={(event) => {
        window.location.assign(localizePath(stripLocale(pathname), event.target.value) + search);
      }}
    >
      {locales.map((option) => (
        // Name each language in itself, such as "français" or "日本語".
        <option key={option} value={option} lang={option}>
          {new Intl.DisplayNames([option], { type: "language" }).of(option)}
        </option>
      ))}
    </select>
  );
}
```

The Basket keeps its lines and currency across the switch.

## Format prices [#prices]

Format Shopify&#39;s amount with the currency code Shopify returns. [`<Currency>`](/docs/react/reference/components/currency) formats for the active locale; it never converts the amount.

```tsx title="app/components/LocalizedMoney.tsx"
import { Currency } from "gt-react";

/** Format Shopify's price in the active locale without converting currency. */
export function LocalizedMoney({ data }: { data: { amount?: string; currencyCode?: string } }) {
  // Optimistic cart responses can temporarily omit their cost fields.
  if (data.amount == null || !data.currencyCode) return null;
  return <Currency currency={data.currencyCode}>{data.amount}</Currency>;
}
```

## Generate translations [#generate]

Wrap copy in [`<T>`](/docs/react/reference/components/t), use [`useGT`](/docs/react/reference/hooks/use-gt) for strings such as `aria-label` values, and run [`npx gt translate`](/docs/cli/reference/commands/translate) before `react-router build`. Translations bundled by your loader are available on the first server render, so cached responses include them.

To keep copy wrapped and translated as the storefront changes, connect the repository to [Locadex](/docs/platform/locadex/quickstart). It opens pull requests with new translations for review.

## Check the storefront [#check]

Start the storefront and open a page under a target locale, such as `/fr/products/<handle>`. Confirm that:

* `<html lang>` is `fr`, and links on the page start with `/fr`.
* Adding to the Basket and searching return French catalogue text, if your store has French translations.
* `/en/products/<handle>` and unknown prefixes return 404.
* Switching to English loads `/products/<handle>` with the same Basket.

## Next steps

- /docs/integrations/shopify/guides/localizing-nextjs
- /docs/integrations/shopify/guides/translating-products
- /docs/integrations/shopify/guides/selling-in-markets

## Sitemap

See the full [sitemap](https://generaltranslation.com/sitemap.md) for all pages.
