i18n with Next.js

the smooth way

React Berlin Meetup
Sept. 2021

Atila Fassina

Lead Web Developer @ SAP

i18n

L10n

g11n

products

internationalization

use

localization

to do

globalization

to achieve

/** @type {import('next').NextConfig} */

module.exports = {
  reactStrictMode: true,
  i18n: {
    locales: ['en', 'gc'],
    defaultLocale: 'en',
  }
}

/next.config.js

import type { NextPage } from 'next'
import { useRouter } from 'next/router'

const Home: NextPage = () => {
  const { locale } = useRouter()
 	
  return (<p>Your locale is {locale}</p>)
}

router/next

export const useI18n = (locale: string) => ({
  translate: (term: string) => {
    return Boolean(dictionary[locale][term])
      ? dictionary[locale][term]
      : term
  },
})

custom hook

import { dictionary } from './dictionary'

type Locale = keyof typeof dictionary
type Term = keyof typeof dictionary[Locale]

export const useI18n = (locale: Locale) => ({
  translate: (term: Term) => dictionary[locale][term]
})

type-safe

export const dictionary = {
  en: { hw: "Hello World" },
  de: { hw: "Hallo Welt" }
}

type-safe

export default function Home() {
  const locale = useRouter().locale as Locale
  const { translate: t } = useI18n(locale)
  
  return (
    <>
      <nav>
        {locale === 'en' ? (
          <Link href="/" locale="de">
            <a>Deutsch</a>
          </Link>
        ) : (
          <Link href="/" locale="en">
            <a>English</a>
          </Link>
        )}
      </nav>
      <h1>{t('hw')}</h1>
    </>
  )
 }

/page/*.tsx

but

let's make it

easier

❯ yarn add next-g11n

globalization

❯ npm i next-g11n

g11n

next-g11n

🪡 tailor-made for Next.js i18n Routing

📦 ~300b (minified and gzipped)

👮 Type-safe dictionaries

atila.io/twitter

g11n-next

atila.io/nextjs-black-belt

thank you

i18n with Next.js: The easy, and the smooth way

By Atila

i18n with Next.js: The easy, and the smooth way

With i18n routing out-of-the-box on Next.js, there's a lot of heavy lifting going on for us already. Let's have a look at 2 different approaches. Both with fairly little code, simple, and lightweight patterns to get our apps fully globalized!!

  • 274