DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Cover image for i18n with Next.js 13 and app directory
Adriano Raiano
Adriano Raiano

Posted on

i18n with Next.js 13 and app directory

At Next.js Conf, the Vercel team announced Next.js 13 which introduced the new app directory.


It includes support for Layouts, Server Components, Streaming and Support for Data Fetching.

Awesome! Next.js 13 has been released!


It seems pretty fast and it lays the foundations to be dynamic without limits.

Afterthoughts...

This sounds good, but looking more into the app directory, it looks like this is a complete new Next.js setup... not really comparable to the old one...

What does this mean regarding i18n?

Looking at the docs it seems our old approaches will no work anymore.

not planned

Nice features provided by next-i18next (and other Next.js related i18n modules), like described here and here are not suited to this new app directory setup.

A new approach

In this section you'll see how we can internationalize the new app directory with the use of i18next, react-i18next and i18next-resources-to-backend.


npm install i18next react-i18next i18next-resources-to-backend

  1. Folder structure
  2. Language detection
  3. i18n instrumentation
  4. Language switcher
  5. Client side
  6. Bonus

1. Folder structure

Let's start by creating a new folder structure that uses the language as url parameter. A so called dynamic segment:

.
└── app
    └── [lng]
        β”œβ”€β”€ second-page
        |   └── page.js
        β”œβ”€β”€ layout.js
        └── page.js
Enter fullscreen mode Exit fullscreen mode

The app/[lng]/page.js file could look like this:

import Link from 'next/link'

export default function Page({ params: { lng } }) {
  return (
    <>
      <h1>Hi there!</h1>
      <Link href={`/${lng}/second-page`}>
        second page
      </Link>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

And the app/[lng]/second-page/page.js file could look like this:

import Link from 'next/link'

export default function Page({ params: { lng } }) {
  return (
    <>
      <h1>Hi from second page!</h1>
      <Link href={`/${lng}`}>
        back
      </Link>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

Last the app/[lng]/layout.js file could look like this:

import { dir } from 'i18next'

const languages = ['en', 'de']

export async function generateStaticParams() {
  return languages.map((lng) => ({ lng }))
}

export default function RootLayout({
  children,
  params: {
    lng
  }
}) {
  return (
    <html lang={lng} dir={dir(lng)}>
      <head />
      <body>
        {children}
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

2. Language detection

Now navigating to http://localhost:3000/en or http://localhost:3000/de should show something, and also the links to the second page and back should work, but navigating to http://localhost:3000 will return a 404 error.


To fix that we'll create a Next.js middleware and refactor a bit of code:

Let's first create a new file app/i18n/settings.js:

export const fallbackLng = 'en'
export const languages = [fallbackLng, 'de']
Enter fullscreen mode Exit fullscreen mode

Then adapt the app/[lng]/layout.js file:

import { dir } from 'i18next'
import { languages } from '../i18n/settings'

export async function generateStaticParams() {
  return languages.map((lng) => ({ lng }))
}

export default function RootLayout({
  children,
  params: {
    lng
  }
}) {
  return (
    <html lang={lng} dir={dir(lng)}>
      <head />
      <body>
        {children}
      </body>
    </html>
  )
}
Enter fullscreen mode Exit fullscreen mode

And finally create a middleware.js file:


npm install accept-language

import { NextResponse } from 'next/server'
import acceptLanguage from 'accept-language'
import { fallbackLng, languages } from './app/i18n/settings'

acceptLanguage.languages(languages)

export const config = {
  matcher: '/:lng*'
}

const cookieName = 'i18next'

export function middleware(req) {
  let lng
  if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName).value)
  if (!lng) lng = acceptLanguage.get(req.headers.get('Accept-Language'))
  if (!lng) lng = fallbackLng

  if (req.nextUrl.pathname === '/') {
    return NextResponse.redirect(new URL(`/${lng}`, req.url))
  }

  if (req.headers.has('referer')) {
    const refererUrl = new URL(req.headers.get('referer'))
    const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`))
    const response = NextResponse.next()
    if (lngInReferer) response.cookies.set(cookieName, lngInReferer)
    return response
  }

  return NextResponse.next()
}
Enter fullscreen mode Exit fullscreen mode

middleware

Navigating to the root path / will now check if there's already a cookie with the last chosen language, as fallback it will check the Accept-Language header and the last fallback is the defined fallback language.


The detected language will be used to redirect to the appropriate page.

3. i18n instrumentation

Let's prepare i18next in the app/i18n/index.js file:


We're not using the i18next singleton here but create a new instance on each useTranslation call, because during compilation everything seems to be executed in parallel. Having a separate instance will keep the translations consistent.

import { createInstance } from 'i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import { initReactI18next } from 'react-i18next/initReactI18next'
import { getOptions } from './settings'

const initI18next = async (lng, ns) => {
  const i18nInstance = createInstance()
  await i18nInstance
    .use(initReactI18next)
    .use(resourcesToBackend((language, namespace) => import(`./locales/${language}/${namespace}.json`)))
    .init(getOptions(lng, ns))
  return i18nInstance
}

export async function useTranslation(lng, ns, options = {}) {
  const i18nextInstance = await initI18next(lng, ns)
  return {
    t: i18nextInstance.getFixedT(lng, Array.isArray(ns) ? ns[0] : ns, options.keyPrefix),
    i18n: i18nextInstance
  }
}
Enter fullscreen mode Exit fullscreen mode

In the app/i18n/settings.js file we'll add the i18next options:


export const fallbackLng = 'en'
export const languages = [fallbackLng, 'de']
export const defaultNS = 'translation'

export function getOptions (lng = fallbackLng, ns = defaultNS) {
  return {
    // debug: true,
    supportedLngs: languages,
    fallbackLng,
    lng,
    fallbackNS: defaultNS,
    defaultNS,
    ns
  }
}
Enter fullscreen mode Exit fullscreen mode

Let's prepare some translation files:

.
└── app
    └── i18n
        └── locales
            β”œβ”€β”€ en
            |   β”œβ”€β”€ translation.json
            |   └── second-page.json
            └── de
                β”œβ”€β”€ translation.json
                └── second-page.json
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/en/translation.json:

{
  "title": "Hi there!",
  "to-second-page": "To second page"
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/de/translation.json:

{
  "title": "Hallo Leute!",
  "to-second-page": "Zur zweiten Seite"
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/en/second-page.json:

{
  "title": "Hi from second page!",
  "back-to-home": "Back to home"
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/de/second-page.json:

{
  "title": "Hallo von der zweiten Seite!",
  "back-to-home": "ZurΓΌck zur Hauptseite"
}
Enter fullscreen mode Exit fullscreen mode

Now we're ready to use that in our pages...


Server pages can by async this way we can await the useTranslation response.

app/[lng]/page.js:

import Link from 'next/link'
import { useTranslation } from '../i18n'

export default async function Page({ params: { lng } }) {
  const { t } = await useTranslation(lng)
  return (
    <>
      <h1>{t('title')}</h1>
      <Link href={`/${lng}/second-page`}>
        {t('to-second-page')}
      </Link>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

app/[lng]/second-page/page.js:

import Link from 'next/link'
import { useTranslation } from '../../i18n'

export default async function Page({ params: { lng } }) {
  const { t } = await useTranslation(lng, 'second-page')
  return (
    <>
      <h1>{t('title')}</h1>
      <Link href={`/${lng}`}>
        {t('back-to-home')}
      </Link>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

app_de_1

4. Language switcher

Now let's define a language switcher in a Footer component:

app/[lng]/components/Footer/index.js:

import Link from 'next/link'
import { Trans } from 'react-i18next/TransWithoutContext'
import { languages } from '../../../i18n/settings'
import { useTranslation } from '../../../i18n'

export const Footer = async ({ lng }) => {
  const { t } = await useTranslation(lng, 'footer')
  return (
    <footer style={{ marginTop: 50 }}>
      <Trans i18nKey="languageSwitcher" t={t}>
        Switch from <strong>{{lng}}</strong> to:{' '}
      </Trans>
      {languages.filter((l) => lng !== l).map((l, index) => {
        return (
          <span key={l}>
            {index > 0 && (' or ')}
            <Link href={`/${l}`}>
              {l}
            </Link>
          </span>
        )
      })}
    </footer>
  )
}
Enter fullscreen mode Exit fullscreen mode

You see we can also use the react-i18next Trans component.

A new namespace:

app/i18n/locales/en/footer.json:

{
  "languageSwitcher": "Switch from <1>{{lng}}</1> to: "
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/de/footer.json:

{
  "languageSwitcher": "Wechseln von <1>{{lng}}</1> nach: "
}
Enter fullscreen mode Exit fullscreen mode

And add that Footer component to the pages:

app/[lng]/page.js:

import Link from 'next/link'
import { useTranslation } from '../i18n'
import { Footer } from './components/Footer'

export default async function Page({ params: { lng } }) {
  const { t } = await useTranslation(lng)
  return (
    <>
      <h1>{t('title')}</h1>
      <Link href={`/${lng}/second-page`}>
        {t('to-second-page')}
      </Link>
      <Footer lng={lng}/>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

app/[lng]/second-page/page.js:

import Link from 'next/link'
import { useTranslation } from '../../i18n'
import { Footer } from '../components/Footer'

export default async function Page({ params: { lng } }) {
  const { t } = await useTranslation(lng, 'second-page')
  return (
    <>
      <h1>{t('title')}</h1>
      <Link href={`/${lng}`}>
        {t('back-to-home')}
      </Link>
      <Footer lng={lng}/>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

language switcher

πŸ₯³ Awesome, you've just created your first language switcher!

5. Client side

So far we've created serverside pages only.


So how does clientside pages look like?

Since clientside react components can't async we need to do some adjustments.

Let's introduce the app/i18n/client.js file:

'use client'

import i18next from 'i18next'
import { initReactI18next, useTranslation as useTranslationOrg } from 'react-i18next'
import resourcesToBackend from 'i18next-resources-to-backend'
import { getOptions } from './settings'

// 
i18next
  .use(initReactI18next)
  .use(resourcesToBackend((language, namespace) => import(`./locales/${language}/${namespace}.json`)))
  .init(getOptions())

export function useTranslation(lng, ns, options) {
  if (i18next.resolvedLanguage !== lng) i18next.changeLanguage(lng)
  return useTranslationOrg(ns, options)
}
Enter fullscreen mode Exit fullscreen mode

On clientside the normal i18next singleton is ok. It will be initialized just once. And we can make use of the "normal" useTranslation hook. We just wrap it to have the possibility to pass in the language.

We also need to create 2 versions of the Footer component.

.
└── app
    └── [lng]
        └── components
            └── Footer
                β”œβ”€β”€ client.js
                β”œβ”€β”€ FooterBase.js
                └── index.js
Enter fullscreen mode Exit fullscreen mode

app/[lng]/components/Footer/FooterBase.js:

import Link from 'next/link'
import { Trans } from 'react-i18next/TransWithoutContext'
import { languages } from '../../../i18n/settings'

export const FooterBase = ({ t, lng }) => {
  return (
    <footer style={{ marginTop: 50 }}>
      <Trans i18nKey="languageSwitcher" t={t}>
        Switch from <strong>{{lng}}</strong> to:{' '}
      </Trans>
      {languages.filter((l) => lng !== l).map((l, index) => {
        return (
          <span key={l}>
            {index > 0 && (' or ')}
            <Link href={`/${l}`}>
              {l}
            </Link>
          </span>
        )
      })}
    </footer>
  )
}
Enter fullscreen mode Exit fullscreen mode

The serverside part continuous to use the async version, app/[lng]/components/Footer/index.js:

import { useTranslation } from '../../../i18n'
import { FooterBase } from './FooterBase'

export const Footer = async ({ lng }) => {
  const { t } = await useTranslation(lng, 'footer')
  return <FooterBase t={t} lng={lng} />
}
Enter fullscreen mode Exit fullscreen mode

The clientside part will use the new i18n/client version, app/[lng]/components/Footer/client.js:

'use client'

import { FooterBase } from './FooterBase'
import { useTranslation } from '../../../i18n/client'

export const Footer = ({ lng }) => {
  const { t } = useTranslation(lng, 'footer')
  return <FooterBase t={t} lng={lng} />
}
Enter fullscreen mode Exit fullscreen mode

A clientside page could look like this - app/[lng]/client-page/page.js:

'use client'

import Link from 'next/link'
import { useTranslation } from '../../i18n/client'
import { Footer } from '../components/Footer/client'
import { useState } from 'react'

export default function Page({ params: { lng } }) {
  const { t } = useTranslation(lng, 'client-page')
  const [counter, setCounter] = useState(0)
  return (
    <>
      <h1>{t('title')}</h1>
      <p>{t('counter', { count: counter })}</p>
      <div>
        <button onClick={() => setCounter(Math.max(0, counter - 1))}>-</button>
        <button onClick={() => setCounter(Math.min(10, counter + 1))}>+</button>
      </div>
      <Link href={`/${lng}`}>
        <button type="button">
          {t('back-to-home')}
        </button>
      </Link>
      <Footer lng={lng} />
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

With some translation resources:

app/i18n/locales/en/client-page.json:

{
  "title": "Client page",
  "counter_one": "one selected",
  "counter_other": "{{count}} selected",
  "counter_zero": "none selected",
  "back-to-home": "Back to home"
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/de/client-page.json:

{
  "title": "Client Seite",
  "counter_one": "eines ausgewΓ€hlt",
  "counter_other": "{{count}} ausgewΓ€hlt",
  "counter_zero": "keines ausgewΓ€hlt",
  "back-to-home": "ZurΓΌck zur Hauptseite"
}
Enter fullscreen mode Exit fullscreen mode

And a link in our initial page - app/[lng]/page.js:

import Link from 'next/link'
import { useTranslation } from '../i18n'
import { Footer } from './components/Footer'

export default async function Page({ params: { lng } }) {
  const { t } = await useTranslation(lng)
  return (
    <>
      <h1>{t('title')}</h1>
      <Link href={`/${lng}/second-page`}>
        {t('to-second-page')}
      </Link>
      <br />
      <Link href={`/${lng}/client-page`}>
        {t('to-client-page')}
      </Link>
      <Footer lng={lng}/>
    </>
  )
}
Enter fullscreen mode Exit fullscreen mode

...with translation resources:

app/i18n/locales/en/translation.json:

{
  "title": "Hi there!",
  "to-second-page": "To second page",
  "to-client-page": "To client page"
}
Enter fullscreen mode Exit fullscreen mode

app/i18n/locales/de/translation.json:

{
  "title": "Hallo Leute!",
  "to-second-page": "Zur zweiten Seite",
  "to-client-page": "Zur clientseitigen Seite"
}
Enter fullscreen mode Exit fullscreen mode

πŸŽ‰πŸ₯³ Congratulations 🎊🎁

The result should look like this:

result

πŸ§‘β€πŸ’» The complete code of an example app can be found here.

6. Bonus

transform the localization process

Connect to an awesome translation management system and manage your translations outside of your code.

Let's synchronize the translation files with locize.
This can be done on-demand or on the CI-Server or before deploying the app.

What to do to reach this step:

  1. in locize: signup at https://locize.app/register and login
  2. in locize: create a new project
  3. install the locize-cli (npm i locize-cli)
  4. in locize: add all your additional languages (this can also be done via API or with using the migrate command of the locize-cli)

Use the locize-cli

Use the locize download command to always download the published locize translations to your local repository (app/i18n/locales) before bundling your app. example

Alternatively, you can also use the locize sync command to synchronize your local repository (app/i18n/locales) with what is published on locize. example

πŸŽ‰πŸ₯³ Congratulations 🎊🎁

I hope you’ve learned a few new things about i18n in the new app directory setup, Next.js, i18next, react-i18next, react-i18next, i18next-resources-to-backend and modern localization workflows.

So if you want to take your i18n topic to the next level, it's worth to try the localization management platform - locize.

The founders of locize are also the creators of i18next. So with using locize you directly support the future of i18next.

πŸ‘

Top comments (14)

Collapse
 
spock123 profile image
Lars Rye Jeppesen

I have to admit, coming from Angular, this is such a bad experience in comparison.

In Angular you just use a system-provided prop called i18n and you use it in component templates like<h1 i18n="id_for_my_translation">Translate-me</h1>

No special imports needed, no function calls, no contexts, no having to make components async etc etc.

Collapse
 
cbfn profile image
Christian Nascimento

Nice post! Awesome! I follow the code but I had problems to implement a typescript version. Any ideia?

Collapse
 
adrai profile image
Adriano Raiano
Collapse
 
spock123 profile image
Lars Rye Jeppesen

Fantastic, thank you

Collapse
 
cbfn profile image
Christian Nascimento

Really awesome, now I can remove my tslint-ignore. Thanks!

Collapse
 
rc77526076 profile image
rc

hi there a error, when i try a not exit path. didnt go to "not-found"page.
"Server Error
Error: A required parameter (slug) was not provided as a string in generateStaticParams for /[lng]/[slug]

This error happened while generating the page. Any console logs will be displayed in the terminal window."

Collapse
 
adrai profile image
Adriano Raiano

There's no slug in my example…
If you see any issue feel free to open an issue or PR on GitHub: github.com/i18next/next-13-app-dir...

Collapse
 
anilbms75 profile image
ANIL KUMAR • Edited on

@adrai tried and works fine -

Collapse
 
hamzakhuswan profile image
HamzaKhuswan

How did you solve the issue?

Collapse
 
bejaranotech profile image
bejarano-tech

Great job, awesome post.!!

I have a issue that is because i want that the / path to be responded by the fallback language, example /enterprises to be responded by /en-US/enterprises. Do you know how i can accomplish that?

Collapse
 
amm834 profile image
Aung Myat Moe

You should use lang or locale in product ready products instead of lng. lng means what?

Collapse
 
adrai profile image
Adriano Raiano

used lng because also i18next uses it as option name: i18next.com/overview/configuration...

Collapse
 
spock123 profile image
Lars Rye Jeppesen

Lots of typing issues when going to Typescript

Collapse
 
adrai profile image
Adriano Raiano

Create an Account!

πŸ‘€ Just want to lurk?

That's fine, you can still create an account and turn on features like 🌚 dark mode.