reactjssetup-projecti18nextnext.js13

How to setup i18next with Next.js 13^ for server and client components


Next community, I am having trouble configuring my internationalization with the brand new Next.js13 I am also using i18next.

I kindly ask for your assistance and may be few examples of a working setup.

This is what I have tried so far (I am using the new "app" directory)

//next-i18next-config.js

module.exports = {
  i18n: {
    locales: ['en', 'de'],
    defaultLocale: 'en',
  },
}
// next.config.js

const { i18n } = require('./next-i18next-config')

const nextConfig = {
  reactStrictMode: true,
  swcMinify: true,
  experimental: { appDir: true },
  i18n
}

module.exports = nextConfig
public
├── favicon.ico
└── locales
    ├── de
    │   └── translation.json
    └── en
       └── translation.json

// package.json

"dependencies": {
    "i18next": "^22.0.4",
    "next": "13.0.0",
    "next-i18next": "^12.1.0",
    "react-i18next": "^12.0.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "sass": "^1.56.0",
    "typescript": "4.8.4",
  },

Server side problem - Error on useTranslation

app/
├── approach
│   └── page.tsx
├── layout.tsx
├── loading.tsx
└── page.tsx
import { use } from 'react'
import { useTranslation } from 'next-i18next' // I also tried 'react-i18next'

async function getApproachPage() {
  const res = await fetch(`${process.env.BASE_URL}/page/approach`, {
    cache: 'no-store', // SSR getServerSideProps
  })

  return res.json()
}

const ApproachPage = () => {
  const { t } = useTranslation() // Getting an Error here : (

  const data = use(getApproachPage()) // TODO: implement res data in page after setting up translations

  return (
    <h1>{t('approach.title')}</h1>
  )
}

export default ApproachPage

Client side problem - can't locate translation.json files

This is how I am doing the config in v12 and lower versions (link)

One of the things I can't understand is how to do this in v13

export async function getStaticProps({ locale }) {
  return {
    props: {
      ...(await serverSideTranslations(locale, ['common', 'home'])),
    }, 
  }
}

Solution

  • Okay, I've finally figured out how to make a setup that actually works.

    I was able to comprehend how to accomplish it thanks to this incredibly thorough guide. I'll pass it along here to anyone else who needs it

    https://locize.com/blog/next-13-app-dir-i18n/