> ## Documentation Index
> Fetch the complete documentation index at: https://weaverse.io/docs/llms.txt
> Use this file to discover all available pages before exploring further.

> ## Agent Instructions
> Weaverse component configuration uses `settings`. `inspector` is deprecated; never generate it.
> Weaverse Hydrogen themes use React Router v7: import from `react-router`, never `react-router-dom` or `@remix-run/*`.
> Before using any code sample, read `@weaverse/hydrogen` in the project's `package.json`: 6.x and 5.x import from different entries and use different type names, so code for one does not build on the other.
> `@weaverse/hydrogen` 6 (Shopify Hydrogen 2026.10 and later, the version these docs show) imports from `@weaverse/hydrogen/react-router` and uses `Weaverse*` types such as `WeaverseComponentProps`, `WeaverseComponentLoaderArgs` and `WeaverseComponentSchema`; the root `@weaverse/hydrogen` entry only exports `createSchema()`, data helpers and types.
> `@weaverse/hydrogen` 5.x (Hydrogen 2026.4 and earlier) imports everything from `@weaverse/hydrogen` and uses `HydrogenComponentProps`, `ComponentLoaderArgs` and `HydrogenComponentSchema`. On a 5.x project, convert samples to these names. Upgrade to 6 only when asked (`npx @weaverse/cli@latest migrate v6`, plus the Hydrogen 2026.10 upgrade). Do not mix major versions.
> Next.js themes use `@weaverse/next` 1.x.
> For live project data (pages, theme settings, translations), use the Weaverse MCP server: https://weaverse.io/docs/developer-tools/weaverse-mcp

# i18next Integration

> Learn how to set up i18next for advanced localization and pluralization support in Weaverse.

# How to Integrate i18next with Weaverse Hydrogen

> [!NOTE]
>
> This guide is for Shopify Hydrogen storefronts. Building on Next.js? See the [Next.js overview](https://weaverse.io/docs/nextjs/overview.md).

This guide explains how to integrate **i18next** as the primary translation engine in your Weaverse Hydrogen project.

While Weaverse provides a built-in `useTranslation()` hook for simple `{ {variable} }` substitution, integrating `i18next` enables advanced localization features like **plurals**, **context-based formatting**, and **ordinals**—without breaking Weaverse's visual translation workflow!

## How It Works

Weaverse's resolution chain allows you to inject an external translator function into the `withWeaverse` configuration. When provided, Weaverse evaluates translations in the following priority:

1. **External t (i18next)** ← Highest priority
2. **Live design-mode overrides** (unsaved edits in the Weaverse Studio editor)
3. **Published merchant overrides** (translations saved in Weaverse Studio)
4. **Static theme content** (`schema.i18n.staticContent`)
5. **Raw translation key** ← Fallback

By routing translations through `i18next` first and gracefully falling back to Weaverse if strings aren't matched, your components enjoy full i18next capabilities while giving non-technical merchants complete control inside the Weaverse builder.

***

## Step 1: Install Dependencies

You only need the core `i18next` package. React bindings (`react-i18next`) are optional unless you prefer using its hook directly instead of `useTranslation` from `@weaverse/hydrogen`.

```bash theme={null}
npm install i18next
```

***

## Step 2: Create the i18n Bridge

Create a bridge file (e.g., `app/utils/i18n.ts`) that builds a **request-scoped** `i18next` instance and the adapter function expected by Weaverse.

> [!WARNING]
>
> Do **not** use a module-global `i18next` singleton and call `changeLanguage()` from your root loader. Pilot server-renders every request in the same worker isolate (see `app/entry.server.tsx`), so concurrent requests for different locales would race on shared language state and leak one visitor's language into another's HTML. Create or clone an instance per request instead.

```typescript theme={null}
import { createInstance, type i18n as I18nInstance } from 'i18next';
import type { TranslateFunction } from '@weaverse/hydrogen/react-router';

// 1. Build a fresh, fully isolated instance for one request.
export function createI18nForRequest(
  locale: string,
  translations: Record<string, any>,
): I18nInstance {
  const lng = locale.toLowerCase().split(/[-_]/)[0]; // Map 'EN_US' -> 'en'
  const instance = createInstance();

  // Bundled resources need no async backend. `initImmediate: false` completes
  // initialization synchronously, before this instance is used during SSR.
  void instance.init({
    initImmediate: false,
    lng,
    fallbackLng: 'en',
    resources: { [lng]: { translation: translations } },
    interpolation: { escapeValue: false }, // React already safeguards against XSS
    compatibilityJSON: 'v4', // Required for advanced pluralizations (_one, _other)
    saveMissing: false,
  });

  return instance;
}

// 2. Wrap an instance in the translator Weaverse expects.
export function createWeaverseT(instance: I18nInstance): TranslateFunction {
  return (key, variables) => {
    if (!instance.isInitialized) return key;

    const result = instance.t(key, variables as object | undefined);

    // If no translation is found, return the raw key so Weaverse can handle
    // its own fallbacks (merchant overrides, static content) gracefully.
    return typeof result === 'string' ? result : key;
  };
}
```

> [!NOTE]
>
> On the browser there is only one visitor, so a single client-side instance is fine — the isolation requirement is a **server** concern. The code above works for both: create the instance once per request on the server, and once per page load on the client.

***

## Step 3: Configure Weaverse at the Root Level

`withWeaverse` receives a plain translator callback. That callback must not call React hooks. Instead, create one i18next instance for the current render tree, close the translator over that instance, and memoize the wrapped layout:

```tsx theme={null}
// app/root.tsx
import { useMemo, type ReactNode } from 'react';
import { useRouteLoaderData, type LoaderFunctionArgs } from 'react-router';
import { withWeaverse } from '@weaverse/hydrogen/react-router';
import { createI18nForRequest, createWeaverseT } from '~/utils/i18n';
import baseTranslations from '~/i18n/en.json';

export async function loader(args: LoaderFunctionArgs) {
  const data = await loadData(args); // Your existing root-loader work.
  const locale = data.selectedLocale.language;

  // Return the request's active Hydrogen locale. Do not store an i18next
  // instance in module scope or try to serialize it through loader data.
  return { ...data, locale };
}

function RootDocument({ children }: { children: ReactNode }) {
  const data = useRouteLoaderData<typeof loader>('root');
  const locale = data?.locale ?? 'EN';

  return (
    <html lang={locale.toLowerCase().split(/[-_]/)[0]}>
      <body>{children}</body>
    </html>
  );
}

export function Layout(props: { children: ReactNode }) {
  const data = useRouteLoaderData<typeof loader>('root');
  const locale = data?.locale ?? 'EN';

  const LayoutWithWeaverse = useMemo(() => {
    const instance = createI18nForRequest(locale, baseTranslations);
    const t = createWeaverseT(instance);
    return withWeaverse(RootDocument, { t });
  }, [locale]);

  return <LayoutWithWeaverse {...props} />;
}
```

Each server render gets a separate `Layout` hook state, so concurrent locales never share an i18next instance. In the browser, the memoized wrapped layout remains stable until the active locale changes. A locale change intentionally creates a new wrapped layout so the translation callback cannot retain the previous locale.

> [!WARNING]
>
> Do not call `useContext()`, `useTranslation()`, or any other hook from the translator passed to `withWeaverse`. The SDK invokes that callback as a plain function, so hooks there violate React's Rules of Hooks. Also never mutate a module-global i18next instance during SSR.

***

## Step 4: Write Components

Your components don't need any updates. Standard keys simply fall back to Weaverse, but keys mapped in your `i18next` bundles using advanced interpolations now resolve correctly!

**Theme JSON Example:**

```json theme={null}
{
  "cart": {
    "itemCount_one": "{{count}} item",
    "itemCount_other": "{{count}} items"
  }
}
```

**React Component Example:**

```tsx theme={null}
import { useTranslation } from "@weaverse/hydrogen/react-router";

export function CartItemCount({ count }: { count: number }) {
  const { t } = useTranslation();
  
  // Will output "1 item" or "3 items" depending on the count!
  return <span>{t('cart.itemCount', { count })}</span>;
}
```

## Summary Checklist

* Install `i18next`.
* Create an i18n bridge that builds a **new instance per request** (`createInstance()`), never a mutated module-global singleton.
* Return the active storefront locale from the root loader.
* Memoize a `withWeaverse` wrapper whose translator closes over that render tree's instance; never call hooks from the translator callback.
* Enjoy full i18next pluralization combined with Weaverse's visual translation integration!


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.