### Install Example App Dependencies Source: https://github.com/i18next/next-i18next/blob/master/CONTRIBUTING.md Installs the dependencies for the simple example application located in the examples directory. ```bash npm run install:example:simple ``` -------------------------------- ### Prepare Examples for Development Source: https://github.com/i18next/next-i18next/blob/master/CONTRIBUTING.md Installs dependencies for all example applications and builds them. This is useful when working on the examples themselves. ```bash npm run install:examples npm run build:examples ``` -------------------------------- ### Install Dependencies Source: https://github.com/i18next/next-i18next/blob/master/examples/app-router-simple/README.md Run these commands to install the necessary dependencies and start the development server. ```bash npm install npm run dev ``` -------------------------------- ### Verify and Serve Static Site Source: https://github.com/i18next/next-i18next/blob/master/examples/pages-router-ssg/README.md Commands to install dependencies, build the static Next.js application, and serve it locally for verification. This setup is suitable for deployment to static web servers. ```sh npm i npm run build npm run serve ``` -------------------------------- ### Build and Run E2E Tests Source: https://github.com/i18next/next-i18next/blob/master/CONTRIBUTING.md Commands to build the project, move the build to the examples directory, build the examples, and then run the end-to-end test suite. ```bash npm run build && npm run move-build-to-examples npm run build:examples npm run test:e2e ``` -------------------------------- ### Install next-i18next Source: https://github.com/i18next/next-i18next/blob/master/README.md Install the necessary packages for next-i18next. This includes next-i18next, i18next, and react-i18next. ```bash npm install next-i18next i18next react-i18next ``` -------------------------------- ### Install Project Dependencies Source: https://github.com/i18next/next-i18next/blob/master/CONTRIBUTING.md Run this command after cloning the repository to install all necessary Node.js dependencies. ```bash npm install ``` -------------------------------- ### Pages Router Setup: Index Page with serverSideTranslations Source: https://github.com/i18next/next-i18next/blob/master/README.md Fetch translations for static generation on the index page using serverSideTranslations and useTranslation hook. ```tsx // pages/index.tsx import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations' import { useTranslation } from 'next-i18next/pages' export const getStaticProps = async ({ locale }) => ({ props: { ...(await serverSideTranslations(locale, ['common'])), }, }) export default function Home() { const { t } = useTranslation('common') return

{t('title')}

} ``` -------------------------------- ### Custom i18next Backends Source: https://github.com/i18next/next-i18next/blob/master/README.md Configuration examples for integrating custom i18next backend plugins like `i18next-http-backend`, `i18next-locize-backend`, and `i18next-chained-backend` for loading translations from various sources. ```APIDOC ## Custom i18next Backends next-i18next supports any i18next backend plugin for loading translations from an API, CDN, or services like [Locize](https://www.locize.com?utm_source=next_i18next_readme&utm_medium=github&utm_campaign=readme). When a custom backend is provided via `use`, next-i18next will **not** add its default resource loader, giving you full control. ### i18next-http-backend ```ts import { defineConfig } from 'next-i18next' import HttpBackend from 'i18next-http-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [HttpBackend], i18nextOptions: { backend: { loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json', }, }, }) ``` ### i18next-locize-backend ```ts import { defineConfig } from 'next-i18next' import LocizeBackend from 'i18next-locize-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [LocizeBackend], i18nextOptions: { backend: { projectId: 'your-project-id', apiKey: 'your-api-key', // only needed for saving missing keys }, }, }) ``` ### i18next-chained-backend For client-side caching with a remote fallback: ```ts import { defineConfig } from 'next-i18next' import ChainedBackend from 'i18next-chained-backend' import HttpBackend from 'i18next-http-backend' import LocalStorageBackend from 'i18next-localstorage-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [ChainedBackend], i18nextOptions: { backend: { backends: [LocalStorageBackend, HttpBackend], backendOptions: [ { expirationTime: 7 * 24 * 60 * 60 * 1000 }, { loadPath: '/locales/{{lng}}/{{ns}}.json' }, ], }, }, }) ``` For the client-side `I18nProvider`, pass custom backend plugins via the `use` prop: ```tsx {children} ``` ### Server-side caching On the server, next-i18next uses a **module-level singleton** i18next instance: - Translations are loaded **once** and reused across all subsequent requests - Custom backends benefit from this — no re-fetching per request - Additional namespaces are loaded on demand and cached In **serverless environments** (Lambda, Vercel Serverless, etc.), the cache only lives as long as the warm function instance. For serverless, prefer: 1. Bundling translations at build time via `resources` or `resourceLoader` with dynamic imports 2. Downloading translations in CI/CD via [Locize CLI](https://github.com/locize/locize-cli) ``` -------------------------------- ### Mixed App Router + Pages Router Setup Source: https://context7.com/i18next/next-i18next/llms.txt Set up next-i18next for a mixed App Router and Pages Router environment. Scope the App Router to a `basePath` and import from correct sub-paths. ```javascript // i18n.shared.js — shared language config module.exports = { supportedLngs: ['en', 'de'], fallbackLng: 'en', defaultNS: 'common', ns: ['common', 'footer'], } ``` ```typescript // i18n.config.ts — App Router (basePath scopes the proxy) import type { I18nConfig } from 'next-i18next/proxy' const shared = require('./i18n.shared.js') const i18nConfig: I18nConfig = { ...shared, basePath: '/app-router', resourceLoader: (language, namespace) => import(`./public/locales/${language}/${namespace}.json`), } export default i18nConfig ``` ```javascript // proxy.ts — only handles /app-router/** requests import { createProxy } from 'next-i18next/proxy' import i18nConfig from './i18n.config' export const proxy = createProxy(i18nConfig) export const config = { matcher: ['/app-router/:path*'] } ``` ```javascript // next-i18next.config.js — Pages Router uses Next.js built-in routing const shared = require('./i18n.shared.js') module.exports = { i18n: { defaultLocale: shared.fallbackLng, locales: shared.supportedLngs }, } ``` ```javascript // pages/_app.tsx import { appWithTranslation } from 'next-i18next/pages' export default appWithTranslation(MyApp) ``` ```javascript // pages/index.tsx import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations' import { useTranslation } from 'next-i18next/pages' export const getStaticProps = async ({ locale }) => ({ props: { ...(await serverSideTranslations(locale, ['common'])) }, }) export default function Page() { const { t } = useTranslation('common') return

{t('title')}

} ``` -------------------------------- ### Pages Router Setup: _app.tsx Source: https://github.com/i18next/next-i18next/blob/master/README.md Wrap your MyApp component with appWithTranslation for Pages Router internationalization. ```tsx // pages/_app.tsx import { appWithTranslation } from 'next-i18next/pages' const MyApp = ({ Component, pageProps }) => export default appWithTranslation(MyApp) ``` -------------------------------- ### Pages Router Setup: next.config.js Source: https://github.com/i18next/next-i18next/blob/master/README.md Integrate i18n configuration into your Next.js application's next.config.js file. ```javascript // next.config.js const { i18n } = require('./next-i18next.config.js') module.exports = { i18n } ``` -------------------------------- ### Pages Router Setup Source: https://github.com/i18next/next-i18next/blob/master/README.md Configuration for projects using only the Next.js Pages Router. This includes setting up the i18n configuration in `next-i18next.config.js` and `next.config.js`, and wrapping your App component with `appWithTranslation`. ```APIDOC ## Pages Router Setup For projects using only the Pages Router, the familiar v15 API is available under `next-i18next/pages`: ```js // next-i18next.config.js module.exports = { i18n: { defaultLocale: 'en', locales: ['en', 'de'], }, } ``` ```js // next.config.js const { i18n } = require('./next-i18next.config.js') module.exports = { i18n } ``` ```tsx // pages/_app.tsx import { appWithTranslation } from 'next-i18next/pages' const MyApp = ({ Component, pageProps }) => export default appWithTranslation(MyApp) ``` ```tsx // pages/index.tsx import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations' import { useTranslation } from 'next-i18next/pages' export const getStaticProps = async ({ locale }) => ({ props: { ...(await serverSideTranslations(locale, ['common'])), }, }) export default function Home() { const { t } = useTranslation('common') return

{t('title')}

} ``` See [`examples/pages-router-simple`](examples/pages-router-simple), [`examples/pages-router-ssg`](examples/pages-router-ssg), and [`examples/pages-router-auto-static-optimize`](examples/pages-router-auto-static-optimize) for more. ``` -------------------------------- ### API Reference: next-i18next/server Source: https://github.com/i18next/next-i18next/blob/master/README.md Provides server-side utilities for initializing i18next, getting translation functions, extracting resources, and generating static parameters. ```APIDOC ### `next-i18next/server` | Export | |---|---| | `initServerI18next(config)` | | `getT(ns?, options?)` | | `getResources(i18n, namespaces?)` | | `generateI18nStaticParams()` | ``` -------------------------------- ### App Router Configuration with basePath Source: https://github.com/i18next/next-i18next/blob/master/README.md Configure the App Router with a basePath to scope its middleware. This example imports shared settings and defines the resource loader. ```typescript // i18n.config.ts import type { I18nConfig } from 'next-i18next/proxy' const shared = require('./i18n.shared.js') const i18nConfig: I18nConfig = { ...shared, basePath: '/app-router', resourceLoader: (language, namespace) => import(`./public/locales/${language}/${namespace}.json`), } export default i18nConfig ``` -------------------------------- ### Pages Router Setup: next-i18next.config.js Source: https://github.com/i18next/next-i18next/blob/master/README.md Configure default locale and available locales for your Next.js application using the Pages Router. ```javascript // next-i18next.config.js module.exports = { i18n: { defaultLocale: 'en', locales: ['en', 'de'], }, } ``` -------------------------------- ### `getT(ns?, options?)` — Get translation function for Server Components Source: https://context7.com/i18next/next-i18next/llms.txt Async function that returns `{ t, i18n, lng }` for use in Server Components, layouts, and `generateMetadata`. It detects the current language from headers, cookies, or fallbackLng. The underlying i18n instance is a module-level singleton, ensuring translations are loaded once and reused. ```APIDOC ## `getT(ns?, options?)` — Get translation function for Server Components Async function that returns `{ t, i18n, lng }` for use in Server Components, layouts, and `generateMetadata`. Detects the current language from the `x-i18next-current-language` header (set by the proxy), then falls back to the `i18n` cookie, then to `fallbackLng`. The underlying i18n instance is a module-level singleton — translations are loaded once and reused across all subsequent requests. Additional namespaces requested are loaded on demand and cached. ### Usage Examples: **Basic usage — uses default namespace** ```tsx // app/[lng]/page.tsx — Server Component import { getT } from 'next-i18next/server' export default async function Home() { const { t, lng } = await getT() return

{t('welcome')}

} ``` **With explicit namespace** ```tsx // app/[lng]/page.tsx — Server Component import { getT } from 'next-i18next/server' export default async function About() { const { t } = await getT('about') return

{t('description')}

} ``` **With keyPrefix (scope translations to a sub-key)** ```tsx // app/[lng]/page.tsx — Server Component import { getT } from 'next-i18next/server' export default async function Profile() { const { t } = await getT('common', { keyPrefix: 'profile' }) return {t('name')} // resolves common:profile.name } ``` **With explicit language override** ```tsx // app/[lng]/page.tsx — Server Component import { getT } from 'next-i18next/server' export default async function Preview() { const { t } = await getT('home', { lng: 'de' }) return
{t('title')}
// always German, ignores detected language } ``` **In generateMetadata** ```tsx // app/[lng]/page.tsx — Server Component import { getT } from 'next-i18next/server' export async function generateMetadata() { const { t } = await getT('home') return { title: t('meta_title'), description: t('meta_description'), } } ``` **With Trans component in Server Components** ```tsx // app/[lng]/page.tsx — Server Component import { Trans } from 'react-i18next/TransWithoutContext' import { getT } from 'next-i18next/server' export default async function Page() { const { t, i18n } = await getT() return ( Welcome to next-i18next ) } ``` ``` -------------------------------- ### initServerI18next(config) Source: https://context7.com/i18next/next-i18next/llms.txt Initializes the module-level singleton i18next configuration for server-side use. This function must be called once at module scope in the root layout before any call to `getT()`. Subsequent calls are no-ops. ```APIDOC ## `initServerI18next(config)` — Initialize server-side i18next Initializes the module-level singleton i18next configuration for server-side use. Must be called once — at module scope in the root layout before any call to `getT()`. Subsequent calls (on re-renders/re-imports) are effectively no-ops as the config is stored in a module-level variable. ```ts // app/[lng]/layout.tsx (Server Component — root layout) import { initServerI18next, getT, getResources, generateI18nStaticParams } from 'next-i18next/server' import { I18nProvider } from 'next-i18next/client' import i18nConfig from '../../i18n.config' // Called once at module scope initServerI18next(i18nConfig) export async function generateStaticParams() { return generateI18nStaticParams() } export default async function RootLayout({ children, params, }: { children: React.ReactNode params: Promise<{ lng: string }> }) { const { lng } = await params const { i18n } = await getT() const resources = getResources(i18n) return ( {children} ) } ``` ``` -------------------------------- ### Using custom getServerTranslations in getStaticProps Source: https://github.com/i18next/next-i18next/blob/master/TROUBLESHOOT.md Example of how to use the custom getServerTranslations wrapper within getStaticProps to fetch translations. ```typescript import { getServerTranslations } from '@/lib/i18n'; const i18nNamespaces = ['demo']; export default function DemoRoute( props: InferGetStaticPropsType ) { // ... } export const getStaticProps: GetStaticProps = async (context) => { const { locale } = context; return { props: { ...(await getServerTranslations(locale, i18nNamespaces)), }, }; }; ``` -------------------------------- ### createMiddleware(config) Source: https://context7.com/i18next/next-i18next/llms.txt A backwards-compatible alias for `createProxy`, intended for projects using Next.js < 16's `middleware.ts` convention. It provides identical behavior to `createProxy`. ```APIDOC ## `createMiddleware(config)` — Backwards-compatible alias for `createProxy` An alias for `createProxy` for projects using Next.js < 16's `middleware.ts` convention. Identical behavior. ```ts // middleware.ts (Next.js < 16) import { createMiddleware } from 'next-i18next/middleware' import i18nConfig from './i18n.config' export const middleware = createMiddleware(i18nConfig) export const config = { matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico).*)'], } ``` ``` -------------------------------- ### Custom i18next Backends Source: https://context7.com/i18next/next-i18next/llms.txt Both the server-side `I18nConfig` and the client-side `I18nProvider` accept a `use` array of i18next plugins. When a backend plugin is provided, next-i18next skips its default resource loader, giving full control over translation fetching. The server-side singleton means custom backends only fetch once per warm instance. ```APIDOC ## Custom i18next Backends — `use` option ### Description Both the server-side `I18nConfig` and the client-side `I18nProvider` accept a `use` array of i18next plugins. When a backend plugin is provided, next-i18next skips its default resource loader, giving full control over translation fetching. The server-side singleton means custom backends only fetch once per warm instance. ### Usage ```ts // i18n.config.ts — server-side custom backends import { defineConfig } from 'next-i18next' import HttpBackend from 'i18next-http-backend' import LocizeBackend from 'i18next-locize-backend' import ChainedBackend from 'i18next-chained-backend' import LocalStorageBackend from 'i18next-localstorage-backend' // i18next-http-backend export const httpConfig = defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [HttpBackend], i18nextOptions: { backend: { loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json' }, }, }) // i18next-locize-backend export const locizeConfig = defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [LocizeBackend], i18nextOptions: { backend: { projectId: 'your-project-id', apiKey: 'your-api-key', // only needed for saving missing keys }, }, }) // i18next-chained-backend (localStorage cache + HTTP fallback, client-side) // Pass to I18nProvider via `use` prop: // ``` ``` -------------------------------- ### Custom Backend: i18next-locize-backend Configuration Source: https://github.com/i18next/next-i18next/blob/master/README.md Configure next-i18next to use i18next-locize-backend, requiring project ID and API key for translation management. ```typescript import { defineConfig } from 'next-i18next' import LocizeBackend from 'i18next-locize-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [LocizeBackend], i18nextOptions: { backend: { projectId: 'your-project-id', apiKey: 'your-api-key', // only needed for saving missing keys }, }, }) ``` -------------------------------- ### Custom Backend: i18next-chained-backend Configuration Source: https://github.com/i18next/next-i18next/blob/master/README.md Set up i18next-chained-backend for client-side caching with HttpBackend as a fallback, using LocalStorageBackend. ```typescript import { defineConfig } from 'next-i18next' import ChainedBackend from 'i18next-chained-backend' import HttpBackend from 'i18next-http-backend' import LocalStorageBackend from 'i18next-localstorage-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [ChainedBackend], i18nextOptions: { backend: { backends: [LocalStorageBackend, HttpBackend], backendOptions: [ { expirationTime: 7 * 24 * 60 * 60 * 1000 }, { loadPath: '/locales/{{lng}}/{{ns}}.json' }, ], }, }, }) ``` -------------------------------- ### Initialize Server-Side i18next Source: https://context7.com/i18next/next-i18next/llms.txt Call `initServerI18next` once at module scope in your root layout to initialize the module-level singleton i18next configuration for server-side use. This must be done before any calls to `getT()`. ```typescript // app/[lng]/layout.tsx (Server Component — root layout) import { initServerI18next, getT, getResources, generateI18nStaticParams } from 'next-i18next/server' import { I18nProvider } from 'next-i18next/client' import i18nConfig from '../../i18n.config' // Called once at module scope initServerI18next(i18nConfig) export async function generateStaticParams() { return generateI18nStaticParams() } export default async function RootLayout({ children, params, }: { children: React.ReactNode params: Promise<{ lng: string }> }) { const { lng } = await params const { i18n } = await getT() const resources = getResources(i18n) return ( {children} ) } ``` -------------------------------- ### Get Translation Function for Server Components Source: https://context7.com/i18next/next-i18next/llms.txt Use `getT` in Server Components, layouts, and `generateMetadata` to access translations. It detects the current language from headers or cookies and reuses a module-level i18next instance. ```tsx import { getT } from 'next-i18next/server' // Basic usage — uses default namespace export default async function Home() { const { t, lng } = await getT() return

{t('welcome')}

} ``` ```tsx import { getT } from 'next-i18next/server' // With explicit namespace export default async function About() { const { t } = await getT('about') return

{t('description')}

} ``` ```tsx import { getT } from 'next-i18next/server' // With keyPrefix (scope translations to a sub-key) export default async function Profile() { const { t } = await getT('common', { keyPrefix: 'profile' }) return {t('name')} // resolves common:profile.name } ``` ```tsx import { getT } from 'next-i18next/server' // With explicit language override export default async function Preview() { const { t } = await getT('home', { lng: 'de' }) return
{t('title')}
// always German, ignores detected language } ``` ```tsx import { getT } from 'next-i18next/server' // In generateMetadata export async function generateMetadata() { const { t } = await getT('home') return { title: t('meta_title'), description: t('meta_description'), } } ``` ```tsx import { getT } from 'next-i18next/server' import { Trans } from 'react-i18next/TransWithoutContext' // With Trans component in Server Components export default async function Page() { const { t, i18n } = await getT() return ( Welcome to next-i18next ) } ``` -------------------------------- ### Initialize Server-Side i18next in Root Layout Source: https://github.com/i18next/next-i18next/blob/master/README.md Call `initServerI18next` once at module scope in your root layout. This function initializes the i18next server instance with the provided configuration. `getResources` serializes translations for client hydration, and `I18nProvider` wraps children to enable client component translation hooks. ```tsx // app/[lng]/layout.tsx import { initServerI18next, getT, getResources, generateI18nStaticParams } from 'next-i18next/server' import { I18nProvider } from 'next-i18next/client' import i18nConfig from '../../i18n.config' initServerI18next(i18nConfig) export async function generateStaticParams() { return generateI18nStaticParams() } export default async function RootLayout({ children, params, }: { children: React.ReactNode params: Promise<{ lng: string }> }) { const { lng } = await params const { i18n } = await getT() const resources = getResources(i18n) return ( {children} ) } ``` -------------------------------- ### Create Proxy for App Router Source: https://github.com/i18next/next-i18next/blob/master/README.md Sets up the proxy for language detection and routing in the App Router. This file replaces middleware.ts in Next.js 16+. ```typescript import { createProxy } from 'next-i18next/proxy' import i18nConfig from './i18n.config' export const proxy = createProxy(i18nConfig) export const config = { matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'], } ``` -------------------------------- ### Custom i18next Backends with `use` option Source: https://context7.com/i18next/next-i18next/llms.txt Configure custom i18next backends by providing them in the `use` array within `defineConfig` for server-side configurations or directly to the `I18nProvider` on the client-side. This bypasses the default resource loader, allowing full control over translation fetching. Custom backends fetch only once per warm server instance. ```ts // i18n.config.ts — server-side custom backends import { defineConfig } from 'next-i18next' import HttpBackend from 'i18next-http-backend' import LocizeBackend from 'i18next-locize-backend' import ChainedBackend from 'i18next-chained-backend' import LocalStorageBackend from 'i18next-localstorage-backend' // i18next-http-backend export const httpConfig = defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [HttpBackend], i18nextOptions: { backend: { loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json' }, }, }) // i18next-locize-backend export const locizeConfig = defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [LocizeBackend], i18nextOptions: { backend: { projectId: 'your-project-id', apiKey: 'your-api-key', // only needed for saving missing keys }, }, }) // i18next-chained-backend (localStorage cache + HTTP fallback, client-side) // Pass to I18nProvider via `use` prop: // ``` -------------------------------- ### API Reference: next-i18next (root export) Source: https://github.com/i18next/next-i18next/blob/master/README.md Provides core configuration helpers and types for next-i18next. ```APIDOC ## API Reference ### `next-i18next` (root export) | Export | |---|---| | `defineConfig(config)` | | `normalizeConfig(config)` | | `I18nConfig` | ``` -------------------------------- ### Custom Backend: i18next-http-backend Configuration Source: https://github.com/i18next/next-i18next/blob/master/README.md Configure next-i18next to use i18next-http-backend for loading translations from a specified path. ```typescript import { defineConfig } from 'next-i18next' import HttpBackend from 'i18next-http-backend' export default defineConfig({ supportedLngs: ['en', 'de'], fallbackLng: 'en', use: [HttpBackend], i18nextOptions: { backend: { loadPath: 'https://cdn.example.com/locales/{{lng}}/{{ns}}.json', }, }, }) ``` -------------------------------- ### Create Middleware for Next.js < 16 Source: https://context7.com/i18next/next-i18next/llms.txt Use `createMiddleware` as a backwards-compatible alias for `createProxy` in projects using Next.js < 16's `middleware.ts` convention. It provides identical behavior for locale detection and routing. ```typescript // middleware.ts (Next.js < 16) import { createMiddleware } from 'next-i18next/middleware' import i18nConfig from './i18n.config' export const middleware = createMiddleware(i18nConfig) export const config = { matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico).*)'], } ``` -------------------------------- ### Client-Side Exports Source: https://github.com/i18next/next-i18next/blob/master/README.md These are the components and hooks available for client-side use from `next-i18next/client`. ```APIDOC ## `I18nProvider` ### Description Client-side provider that wraps `I18nextProvider` to manage translations. ### Usage ```jsx ``` ``` ```APIDOC ## `useT(ns?, options?)` ### Description Translation hook for Client Components. It can be used in all rendering modes. ### Usage ```jsx const { t } = useT(); {t('key')} ``` ``` ```APIDOC ## `useChangeLanguage(cookieName?)` ### Description Hook for switching languages, specifically for the no-locale-path mode. ### Usage ```jsx const { changeLanguage } = useChangeLanguage(); ``` ``` ```APIDOC ## `Trans` ### Description A component for rendering translated elements, re-exported from `react-i18next`. ### Usage ```jsx Some content ``` ``` -------------------------------- ### createProxy(config) Source: https://context7.com/i18next/next-i18next/llms.txt Creates a Next.js middleware function for handling language detection and locale-in-path routing. It redirects unlocalized URLs to locale-prefixed equivalents and sets a custom header for Server Components. It can also operate in a no-locale-path mode. ```APIDOC ## `createProxy(config)` — Locale detection and routing middleware Creates a Next.js proxy/middleware function that handles language detection (cookie → Accept-Language header → fallback) and locale-in-path routing. In locale-in-path mode it redirects unlocalized URLs to the locale-prefixed equivalent and sets a custom header (`x-i18next-current-language`) for Server Components. In no-locale-path mode it only sets the header without redirecting. Export as `proxy` from `proxy.ts` for Next.js 16+, or as `middleware` from `middleware.ts` for earlier versions. ```ts // proxy.ts (Next.js 16+) import { createProxy } from 'next-i18next/proxy' import i18nConfig from './i18n.config' export const proxy = createProxy(i18nConfig) export const config = { matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'], } // --- What happens at runtime --- // GET /about (no locale, cookie unset, Accept-Language: de,en;q=0.9) // → 302 redirect to /de/about // → Sets cookie: i18next=de // GET /en/about (explicit default locale, hideDefaultLocale: true) // → 302 redirect to /about (canonical clean URL) // GET /de/about (locale already in path) // → NextResponse.next() with header x-i18next-current-language: de // --- Mixed Router setup with basePath --- // import { createProxy } from 'next-i18next/proxy' // export const proxy = createProxy({ ...i18nConfig, basePath: '/app-router' }) // Requests outside /app-router/** are passed through untouched (Pages Router handles them) ``` ``` -------------------------------- ### Implement Language Switching (Locale-in-Path) Source: https://github.com/i18next/next-i18next/blob/master/README.md This client component enables language switching when the locale is part of the URL path. It uses `usePathname` and `useRouter` from `next/navigation` to construct and navigate to the new URL with the selected locale prefix. ```tsx 'use client' import { usePathname, useRouter } from 'next/navigation' export function LanguageSwitcher({ supportedLngs }: { supportedLngs: string[] }) { const pathname = usePathname() const router = useRouter() const switchLocale = (locale: string) => { const segments = pathname.split('/') segments[1] = locale router.push(segments.join('/')) } return (
{supportedLngs.map((lng) => ( ))}
) } ``` -------------------------------- ### Create Proxy Middleware for Next.js 16+ Source: https://context7.com/i18next/next-i18next/llms.txt Use `createProxy` to handle language detection and locale-in-path routing. It redirects unlocalized URLs and sets a custom header for Server Components. Ensure the `matcher` configuration is set correctly. ```typescript // proxy.ts (Next.js 16+) import { createProxy } from 'next-i18next/proxy' import i18nConfig from './i18n.config' export const proxy = createProxy(i18nConfig) export const config = { matcher: ['/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)'], } // --- What happens at runtime --- // GET /about (no locale, cookie unset, Accept-Language: de,en;q=0.9) // → 302 redirect to /de/about // → Sets cookie: i18next=de // GET /en/about (explicit default locale, hideDefaultLocale: true) // → 302 redirect to /about (canonical clean URL) // GET /de/about (locale already in path) // → NextResponse.next() with header x-i18next-current-language: de // --- Mixed Router setup with basePath --- // import { createProxy } from 'next-i18next/proxy' // export const proxy = createProxy({ ...i18nConfig, basePath: '/app-router' }) // Requests outside /app-router/** are passed through untouched (Pages Router handles them) ``` -------------------------------- ### Configure next-i18next for App Router Source: https://github.com/i18next/next-i18next/blob/master/README.md Configuration file for next-i18next. It defines supported languages, fallback language, default namespace, and namespaces. The resourceLoader uses dynamic imports for serverless compatibility. ```typescript import type { I18nConfig } from 'next-i18next/proxy' const i18nConfig: I18nConfig = { supportedLngs: ['en', 'de'], fallbackLng: 'en', defaultNS: 'common', ns: ['common', 'home'], // Recommended: works on all platforms including Vercel/serverless resourceLoader: (language, namespace) => import(`./app/i18n/locales/${language}/${namespace}.json`), } export default i18nConfig ``` -------------------------------- ### serverSideTranslations Source: https://context7.com/i18next/next-i18next/llms.txt Loads translations server-side for Pages Router pages and returns a `_nextI18Next` prop object to be spread into `getStaticProps` / `getServerSideProps`. Reads config from `./next-i18next.config.js` by default (overridable via `I18NEXT_DEFAULT_CONFIG_PATH` env var or `configOverride`). If `namespacesRequired` is omitted, it auto-discovers namespaces from the locale directory. ```APIDOC ## `serverSideTranslations(locale, namespacesRequired?, configOverride?, extraLocales?)` — Pages Router SSR helper ### Description Loads translations server-side for Pages Router pages and returns a `_nextI18Next` prop object to be spread into `getStaticProps` / `getServerSideProps`. Reads config from `./next-i18next.config.js` by default (overridable via `I18NEXT_DEFAULT_CONFIG_PATH` env var or `configOverride`). If `namespacesRequired` is omitted, it auto-discovers namespaces from the locale directory. ### Usage ```tsx // pages/index.tsx import type { GetStaticProps } from 'next' import { serverSideTranslations } from 'next-i18next/pages/serverSideTranslations' import { useTranslation } from 'next-i18next/pages' export const getStaticProps: GetStaticProps = async ({ locale }) => { return { props: { // Loads en/common.json + en/home.json (and fallback locales) ...(await serverSideTranslations(locale ?? 'en', ['common', 'home']))[0], }, } } // getServerSideProps works identically: // export const getServerSideProps: GetServerSideProps = async ({ locale }) => ({ // props: { ...(await serverSideTranslations(locale, ['common'])) }, // }) // With inline config override (no config file required): // await serverSideTranslations('en', ['common'], { // i18n: { defaultLocale: 'en', locales: ['en', 'de'] }, // }) // With extra locales (pre-load additional languages for client-side switching): // await serverSideTranslations('en', ['common'], null, ['de']) export default function Home() { const { t } = useTranslation('home') return

{t('title')}

} ``` ``` -------------------------------- ### API Reference: next-i18next/proxy Source: https://github.com/i18next/next-i18next/blob/master/README.md Provides functions for creating proxy and middleware for Next.js, including an alias for older Next.js versions. ```APIDOC ### `next-i18next/proxy` (also available as `next-i18next/middleware`) | Export | |---|---| | `createProxy(config)` | | `createMiddleware(config)` | | `defineConfig`, `normalizeConfig`, `I18nConfig` | ``` -------------------------------- ### I18nProvider Source: https://context7.com/i18next/next-i18next/llms.txt Client Component that creates and provides a hydrated i18next instance to all descendant Client Components. It takes server-loaded resources for instant hydration and supports dynamic fetching for namespaces not bundled in resources. It also syncs language on navigation and supports custom i18next backends. ```APIDOC ## `I18nProvider` — Client-side i18next provider Client Component that creates and provides a hydrated i18next instance to all descendant Client Components. Takes server-loaded `resources` for instant hydration (zero flash), and falls back to dynamic fetching for namespaces not bundled in resources. Syncs language on navigation via a `useEffect` watching the `language` prop. Supports custom i18next backends via the `use` prop. ```tsx // app/[lng]/layout.tsx import { I18nProvider } from 'next-i18next/client' import { getT, getResources } from 'next-i18next/server' import HttpBackend from 'i18next-http-backend' export default async function Layout({ children, params }) { const { lng } = await params const { i18n } = await getT() const resources = getResources(i18n, ['common']) return ( // Minimal required props: language + resources {children} ) } // With custom backend for client-side lazy loading: // // {children} // // No-locale-path mode (app/layout.tsx, no [lng] segment): // export default async function RootLayout({ children }) { // const { i18n, lng } = await getT() // const resources = getResources(i18n) // return ( // // {children} // // ) // } ``` ``` -------------------------------- ### Custom getServerTranslations wrapper Source: https://github.com/i18next/next-i18next/blob/master/TROUBLESHOOT.md Create a custom wrapper for serverSideTranslations to inject configuration. This is recommended for use with getServerSideProps() and getStaticProps() to manage configuration explicitly. ```typescript // ie: ./lib/i18n/getServerTranslations.ts import type { Namespace } from 'i18next'; import type { SSRConfig, UserConfig } from 'next-i18next' import { serverSideTranslations } from 'next-i18next/serverSideTranslations' import nextI18NConfig from '../../next-i18next.config' type ArrayElementOrSelf = T extends Array ? U[] : T[]; export const getServerTranslations = async ( locale: string, namespacesRequired?: ArrayElementOrSelf | undefined, configOverride?: UserConfig, extraLocales?: string[] | false ): Promise => { const config = configOverride ?? nextI18NConfig return serverSideTranslations(locale, namespacesRequired, config, extraLocales) } ``` -------------------------------- ### Configure pnpm for Peer Deduplication Source: https://github.com/i18next/next-i18next/blob/master/TROUBLESHOOT.md Set these configurations in .npmrc for pnpm versions less than 7.29.0 to address peer deduplication issues in monorepos. ```ini # https://pnpm.io/next/npmrc use-lockfile-v6=true # https://github.com/pnpm/pnpm/releases/tag/v7.29.0 dedupe-peer-dependents=true resolve-peers-from-workspace-root=true ``` -------------------------------- ### appWithTranslation Source: https://context7.com/i18next/next-i18next/llms.txt Higher-order component for the Pages Router _app that wraps the application with I18nextProvider. It creates and manages the i18next instance from SSR-serialized resources, handles language changes on navigation, and re-uses an existing instance across page transitions for performance. ```APIDOC ## `appWithTranslation(WrappedComponent, configOverride?)` — Pages Router HOC ### Description Higher-order component for the Pages Router `_app` that wraps the application with `I18nextProvider`. Creates and manages the i18next instance from SSR-serialized resources, handles language changes on navigation, and re-uses an existing instance across page transitions for performance. ### Usage ```tsx // pages/_app.tsx import type { AppProps } from 'next/app' import { appWithTranslation } from 'next-i18next/pages' // Optional: import type { UserConfig } from 'next-i18next/pages' const MyApp = ({ Component, pageProps }: AppProps) => ( ) // Config is read from next-i18next.config.js automatically. // Pass configOverride as second arg to override or supply config inline: // export default appWithTranslation(MyApp, { // i18n: { defaultLocale: 'en', locales: ['en', 'de'] }, // }) export default appWithTranslation(MyApp) ``` ``` -------------------------------- ### Proxy Middleware for Mixed Routers Source: https://github.com/i18next/next-i18next/blob/master/README.md Create a proxy middleware using createProxy with the App Router configuration. It skips requests not under the basePath and handles redirects. ```typescript // proxy.ts import { createProxy } from 'next-i18next/proxy' import i18nConfig from './i18n.config' export const proxy = createProxy(i18nConfig) export const config = { matcher: ['/app-router/:path*'], } ```