This example shows how to use i18next and react-i18next directly in a Next.js App Router app: you own the Next.js wiring (middleware, server/client split, resource loading) yourself, with no additional dependency.
Tip
Looking for the batteries-included path instead? Since v16, next-i18next supports the App Router out of the box: getT() for Server Components, useT() for Client Components and createProxy() for language detection and routing, with runnable examples. It is a thin layer on top of the same i18next + react-i18next shown here (see the next-i18next v16 announcement for the background). This example remains the right starting point if you prefer full control over your setup.
It shows i18next integration on some server side pages and some client side pages.
There is also an example middleware with language detection and persistence via cookie.
This example has been created out of this discussion.
There's also a blog post describing this with more detail information.
If you like to have all this hosted on a static server, you can add the output: 'export' options and optionally the trailingSlash: true option:
/** @type {import('next').NextConfig} */
const nextConfig = {
output: 'export',
trailingSlash: true,
reactStrictMode: true
}
module.exports = nextConfigAlso make sure you adapt the server side i18next getT helper to not use the headers feature - since this is not compatible with SSG.
Pass the lng to the getT function from withing your server side pages, components and layouts.
import i18next from './i18next'
export async function getT(lng, ns, options) {
if (lng && i18next.resolvedLanguage !== lng) {
await i18next.changeLanguage(lng)
}
if (ns && !i18next.hasLoadedNamespace(ns)) {
await i18next.loadNamespaces(ns)
}
return {
t: i18next.getFixedT(lng ?? i18next.resolvedLanguage, Array.isArray(ns) ? ns[0] : ns, options?.keyPrefix),
i18n: i18next
}
}export default async function Page({ params }) {
const { lng } = await params
const { t } = await getT(lng, 'second-page')
// ...
}And the just run npm run build and you should see the out folder.
Additionally, I recommend adding a root index.html file that detects the browser language and redirects to the corresponding sub-page. i.e.:
<!-- out/index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charSet="utf-8"/>
<meta name="viewport" content="width=device-width"/>
<title>redirect</title>
</head>
<body>
<script src="https://cdnjs.cloudflare.com/ajax/libs/i18next-browser-languagedetector/7.0.2/i18nextBrowserLanguageDetector.min.js"></script>
<!-- <script src="https://unpkg.com/i18next-browser-languagedetector@7.0.2/dist/umd/i18nextBrowserLanguageDetector.min.js"></script> -->
<script>
var lngDetector = new window.i18nextBrowserLanguageDetector()
var lng = lngDetector.detect()
if (lng.indexOf('it') === 0) window.location.href = '/it/'
else if (lng.indexOf('de') === 0) window.location.href = '/de/'
else window.location.href = '/en/'
</script>
</body>
</html>