codegino
← all posts

Build a multilingual NextJS app using the new app directory - cookie-based

Learn how to build a multilingual NextJS app using the new app directory and i18next library

10 min read#react#nextjs#i18n

international cookies
international cookies

TL;DR

Check the demo here

Check the source code here

Introduction

Internationalization, or i18n for short, is the process of designing and developing software applications that can be adapted to different languages and cultures. It is an important consideration for any application that is intended for a global audience.


Next.js is a popular framework for building web applications that simplifies the process of implementing i18n. In this article, we will explore how to handle i18n in Next.js using the app directory and the i18next library. We will also cover some of the key translation functions and techniques that you can use to make your application more accessible to users around the world.


I have written in another article about how to do i81n in Next.js using the URL segment to detect the locale. In this article, we will use the cookie-based approach instead.


Initialize a NextJS project

The easiest way to follow this guide is to degit a Nextjs boilerplate.

bash
1npx degit codegino/nextjs-ts-tw-tldr next13-i18n

I will be using TailwindCSS and TypeScript due to personal preference, but you can use plain CSS and JavaScript if you want.

Install dependencies

bash
1npm i

Remove unused files

Delete everything under the app and components folders

bash
1rm -rf app/* components/*

Project Setup

Our Internationalization strategy

In this blog post, we will use a cookie-based strategy to determine the locale of our web application. We can effortlessly obtain the locale from the cookies function exposed by next/headers in a server component. In a client component, we will create a custom hook to get the locale.

Install required dependencies

There are various libraries available for handling translations, but I find libraries from i18next very easy to use.

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

i18next-resources-to-backend is a very small utility, so you can just copy the implementation if you don't want an additional dependency.

Create a reusable settings file

Let's create a utility file for both the server and the client-side translations

i18n/settings.ts
1import type {InitOptions} from 'i18next';2
3export const FALLBACK_LOCALE = 'en';4export const supportedLocales = ['en', 'zh-CN', 'sv'] as const;5export type Locales = (typeof supportedLocales)[number];6
7// You can name the cookie to whatever you want8export const LANGUAGE_COOKIE = 'preferred_language';9
10export function getOptions(lang = FALLBACK_LOCALE, ns = 'common'): InitOptions {11  return {12    // debug: true, // Set to true to see console logs13    supportedLngs: supportedLocales,14    fallbackLng: FALLBACK_LOCALE,15    lng: lang,16    ns,17  };18}

To learn more about the options, check out the i18next documentation.

Server Components translation setup

i18n/server.ts
1import {createInstance} from 'i18next';2import resourcesToBackend from 'i18next-resources-to-backend';3import {initReactI18next} from 'react-i18next/initReactI18next';4import {FALLBACK_LOCALE,getOptions,Locales,LANGUAGE_COOKIE} from './settings';5import {cookies} from 'next/headers';6
7async function initI18next(lang: Locales, namespace: string) {8  const i18nInstance = createInstance();9  await i18nInstance10    .use(initReactI18next)11    .use(12      resourcesToBackend(13        // Get the JSON file that matches the locale and namespace14        (lang: string, ns: string) => import(`./locales/${lang}/${ns}.json`),15      ),16    )17    // Initialize i18next with the options we created earlier18    .init(getOptions(lang, namespace));19
20  return i18nInstance;21}22
23// This function will be used in our server components for the translation24export async function createTranslation(ns: string) {25  const lang = getLocale();26  const i18nextInstance = await initI18next(lang, ns);27
28  return {29    t: i18nextInstance.getFixedT(lang, Array.isArray(ns) ? ns[0] : ns),30  };31}32
33// Utility function to get the locale from server components34export function getLocale() {35  return (cookies().get(LANGUAGE_COOKIE)?.value ?? FALLBACK_LOCALE) as Locales;36}

Create translation files

Unless our users use translation plugins like Google Translate, there is no way for our content to be magically translated. Therefore, we need to determine how our pages will be translated based on the selected locale and namespace.


Here is what our translation files' structure will look like. en is the locale, and home is the namespace.

i18n└── locales    ├── en    │   └── home.json    ├── zh-CN    │   └── home.json                    └── sv        └── home.json

NOTE: It does not matter where you put the translation files as long as you can import them correctly.

English translations

i18n/locales/en/home.json
1{2  "greeting": "Hello world!"3}

Chinese translations

i18n/locales/zh-CN/home.json
1{2  "greeting": "世界您好"3}

Swedish translation

i18n/locales/sv/home.json
1{2  "greeting": "Hej världen!"3}

Create our page to display the locale

app/page.tsx
1import {createTranslation} from '../i18n/server';2
3export default async function IndexPage() {4  const {t} = await createTranslation('home');5
6  return (7    <div>8      <h1>{t('greeting')}</h1>9    </div>10  );11}

NextJS has a feature that automatically creates a layout component if we don't provide one. However, I prefer to create my own layout component because I need to basic customization.

app/layout.tsx
1import React from 'react';2import {getLocale} from '../i18n/server';3import '../styles/tailwind.css';4
5export const metadata = {6  title: 'Next.js i18n',7};8
9export default function RootLayout({children}: {children: React.ReactNode}) {10  const locale = getLocale();11  return (12    // It's good to sync the html lang attribute with the locale13    <html lang={locale}>14      <body className="p-3">{children}</body>15    </html>16  );17}

Testing our page

By default, our page will use the fallback locale. Then, I manually update the cookie and refresh the page to see the changes.

An image of a blog post

Locale switcher

It will be a weird application if we need to update the cookie manually in the dev tools. So, let's create a locale switcher component.

Create a server action to update the cookie

We will take advantage of server actions to update the cookie easily.

actions/switch-locale.ts
1'use server';2
3import {cookies} from 'next/headers';4import {LANGUAGE_COOKIE} from '../i18n/settings';5
6export async function switchLocaleAction(value: string) {7  cookies().set(LANGUAGE_COOKIE, value);8
9  // It does not matter what we return here10  return {11    status: 'success',12  };13}

Create the locale switcher component

components/ChangeLocale.tsx
1'use client';2import React from 'react';3import {switchLocaleAction} from '../actions/switch-locale';4
5export default function ChangeLocale({locale}) {6  const handleLocaleChange = event => {7    switchLocaleAction(event.target.value);8  };9
10  return (11    <div>12      <select onChange={handleLocaleChange} value={locale}>13        <option value="en">🇺🇸 English</option>14        <option value="zh-CN">🇨🇳 Chinese</option>15        <option value="sv">🇸🇪 Swedish</option>16      </select>17    </div>18  );19}

Now it's easier to test around what language we want to see.

An image of a blog post

Client-side translation

Now, we need to find a way to translate the content on the client side. We will use almost the same approach as the server-side translation but with additional configuration and a custom React hook.


In this section, we will update the locale switcher options to display translated text.

Create a global provider of the locale

I could not make the react-i18n provider work so I created a simple provider and hook to share the active locale.

hooks/locale-provider.tsx
1'use client';2
3import {createContext, useContext} from 'react';4import {FALLBACK_LOCALE, Locales} from '../i18n/settings';5
6const Context = createContext<Locales>(FALLBACK_LOCALE);7
8export function LocaleProvider({9  children,10  value,11}: {12  children: React.ReactNode;13  value: Locales;14}) {15  return <Context.Provider value={value}>{children}</Context.Provider>;16}17
18export function useLocale() {19  return useContext(Context);20}

Install language detector in the browser

Install i18next-browser-languagedetector to simplify language detection in the frontend

bash
1npm install i18next-browser-languagedetector

Client Components translation setup

The code below might be lengthy because we need to support both server rendering and client rendering. Don't confuse SSR with Server Component rendering.

i18n/client.ts
1'use client';2
3import {useEffect} from 'react';4import i18next, {i18n} from 'i18next';5import {initReactI18next, useTranslation as useTransAlias} from 'react-i18next';6import resourcesToBackend from 'i18next-resources-to-backend';7import LanguageDetector from 'i18next-browser-languagedetector';8import {9  Locales,10  LANGUAGE_COOKIE,11  getOptions,12  supportedLocales,13} from './settings';14import {useLocale} from '../hooks/locale-provider';15
16const runsOnServerSide = typeof window === 'undefined';17
18// Initialize i18next for the client side19i18next20  .use(initReactI18next)21  .use(LanguageDetector)22  .use(23    resourcesToBackend(24      (lang: string, ns: string) => import(`./locales/${lang}/${ns}.json`),25    ),26  )27  .init({28    ...getOptions(),29    lng: undefined, // detect the language on the client30    detection: {31      // We only care about the cookie32      order: ['cookie'],33      // If `lookupCookie` is not set, it will use `i18next` as the cookie name34      lookupCookie: LANGUAGE_COOKIE,35      // This will automatically update the cookie36      caches: ['cookie'],37    },38    preload: runsOnServerSide ? supportedLocales : [],39  });40
41export function useTranslation(ns: string) {42  const lng = useLocale();43
44  const translator = useTransAlias(ns);45  const {i18n} = translator;46
47  // Run content is being rendered on server side48  if (runsOnServerSide && lng && i18n.resolvedLanguage !== lng) {49    i18n.changeLanguage(lng);50  } else {51    // Use our custom implementation when running on client side52    // eslint-disable-next-line react-hooks/rules-of-hooks53    useCustomTranslationImplem(i18n, lng);54  }55  return translator;56}57
58function useCustomTranslationImplem(i18n: i18n, lng: Locales) {59  // This effect changes the language of the application when the lng prop changes.60  useEffect(() => {61    if (!lng || i18n.resolvedLanguage === lng) return;62    i18n.changeLanguage(lng);63  }, [lng, i18n]);64}

Update the ChangeLocale to use the new hook

components/ChangeLocale.tsx
1'use client';2import React from 'react';3import {switchLocaleAction} from '../actions/switch-locale';4import {useTranslation} from '../i18n/client';5
6// We removed the `locale` prop because we can get it from the hook7export default function ChangeLocale() {8  const {i18n, t} = useTranslation('common');9  // You can also use our custom hook instead of `i18n.resolvedLanguage`10  // const locale = useLocale();11
12  return (13    <div>14      <select15        onChange={e => switchLocaleAction(e.target.value)}16        value={i18n.resolvedLanguage}17      >18        <option value="en">🇺🇸 {t('english')}</option>19        <option value="zh-CN">🇨🇳 {t('chinese')}</option>20        <option value="sv">🇸🇪 {t('swedish')}</option>21      </select>22    </div>23  );24}

Update the layout component

app/layout.tsx
1import React from 'react';2import ChangeLocale from '../components/ChangeLocale';3import {LocaleProvider} from '../hooks/locale-provider';4import {getLocale} from '../i18n/server';5import '../styles/tailwind.css';6
7export const metadata = {8  title: 'Next.js i18n',9};10
11export default function RootLayout({children}: {children: React.ReactNode}) {12  const locale = getLocale();13  return (14    <html lang={locale}>15      <body className="p-3">16        <LocaleProvider value={locale}>17          <ChangeLocale />18          {children}19        </LocaleProvider>20      </body>21    </html>22  );23}

Create translation files

English translations

i18n/locales/en/common.json
1{2  "english": "English",3  "swedish": "Swedish",4  "chinese": "Chinese"5}

Chinese translations

i18n/locales/zh-CN/common.json
1{2  "english": "中国人",3  "swedish": "英语",4  "chinese": "瑞典"5}

Swedish translation

i18n/locales/sv/common.json
1{2  "english": "engelska",3  "swedish": "svenska",4  "chinese": "kinesiska"5}

After all those many changes, we can now see our locale switcher with the translated options. Also, the cookie value is updated automatically to the fallback when we first load our page.

An image of a blog post

Bonus

Nested translation keys and default translation

We are not limited to a flat JSON structure.

i18n/locales/en/newsletter.json
1{2  "title": "Stay up to date",3  "subtitle": "Subscribe to my newsletter",4  "form": {5    "firstName": "First name",6    "email": "E-mail",7    "action": {8      "signUp": "Sign Up",9      "cancel": "Cancel"10    }11  }12}

We can omit some translation keys if we want it to use the default locale value(en in our case. See the demo later).

i18n/locales/zh-CN/newsletter.json
1{2  "title": "保持最新状态",3  "form": {4    "email": "电子邮箱",5    "action": {6      "cancel": "取消"7    }8  }9}
i18n/locales/sv/newsletter.json
1{2  "title": "Håll dig uppdaterad",3  "subtitle": "Prenumerera på mitt nyhetsbrev",4  "form": {5    "firstName": "Förnamn",6    "email": "E-post",7    "action": {8      "signUp": "Registrera sig",9      "cancel": "Annullera"10    }11  }12}

Create the component

Let's create a component that uses the translations above. We'll make this a server component to demonstrate one way of using the createTranslation function.

components/SubscribeForm.tsx
1import React from 'react';2import {createTranslation} from '../i18n/server';3
4export default async function SubscribeForm() {5  const {t} = await createTranslation('newsletter');6
7  return (8    <section className="w-[350px]">9      <h3>{t('title')}</h3>10      <h4>{t('subtitle')}</h4>11
12      <form className="flex flex-col items-start">13        <input placeholder={t('form.firstName')} className="border mb-1 p-1 w-full" />14        <input placeholder={t('form.email')} className="border mb-1 p-1 w-full" />15        <button className="border mb-1 p-1 w-full">{t('form.action.signUp')}</button>16        <button className="border mb-1 p-1 w-full">{t('form.action.cancel')}</button>17      </form>18    </section>19  );20};

Render the form on the home page.

app/page.tsx
1import SubscribeForm from '../../components/SubscribeForm';2import {createTranslation} from '../../i18n/server';3
4export default async function IndexPage() {5  const {t} = await createTranslation('home');6
7  return (8    <div>9      <h1>{t('greeting')}</h1>10      <hr className="my-4" />11      <SubscribeForm />12    </div>13  );14};

And now, we have this!

An image of a blog post

Built-in Formatting

It is very easy to format most of our data since i18next comes with a lot of utilities we can use.


Let's use the translation files below to showcase the formatting features.

i18n/en/built-in-formats.json
1{2  "number": "Number: {{val, number}}",3  "currency": "Currency: {{val, currency}}",4  "dateTime": "Date/Time: {{val, datetime}}",5  "relativeTime": "Relative Time: {{val, relativetime}}",6  "list": "List: {{val, list}}",7  "weekdays": ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday"]8}
app/i18n/sv/built-in-formats.json
1{2  "number": "Nummer: {{val, number}}",3  "currency": "Valuta: {{val, currency}}",4  "dateTime": "Datum/tid: {{val, datetime}}",5  "relativeTime": "Relativ tid: {{val, relativetime}}",6  "list": "Lista: {{val, list}}",7  "weekdays": ["Måndag", "Tisdag", "Onsdag", "Torsdag", "Fredag"]8}
app/i18n/zh-CN/built-in-formats.json
1{2  "number": "数: {{val, number}}",3  "currency": "货币: {{val, currency}}",4  "dateTime": "日期/时间: {{val, datetime}}",5  "relativeTime": "相对时间: {{val, relativetime}}",6  "list": "列表: {{val, list}}",7  "weekdays": ["星期一", "星期二", "星期三", "星期四", "星期五"]8}

Create the component

Let's create a component that will use the previous translations. We'll make it a client component just for fun.

app/components/BuiltInFormatsDemo.tsx
1'use client';2import React from 'react';3import {useTranslation} from '../i18n/client';4
5export default function BuiltInFormatsDemo() {6  const {t} = useTranslation('built-in-demo');7
8  return (9    <div>10      <p>11        {/* "number": "Number: {{val, number}}", */}12        {t('number', {13          val: 123456789.0123,14        })}15      </p>16      <p>17        {/* "currency": "Currency: {{val, currency}}", */}18        {t('currency', {19          val: 123456789.0123,20          style: 'currency',21          currency: 'USD',22        })}23      </p>24
25      <p>26        {/* "dateTime": "Date/Time: {{val, datetime}}", */}27        {t('dateTime', {28          val: new Date(1234567890123),29          formatParams: {30            val: {31              weekday: 'long',32              year: 'numeric',33              month: 'long',34              day: 'numeric',35            },36          },37        })}38      </p>39
40      <p>41        {/* "relativeTime": "Relative Time: {{val, relativetime}}", */}42        {t('relativeTime', {43          val: 12,44          style: 'long',45        })}46      </p>47
48      <p>49        {/* "list": "List: {{val, list}}", */}50        {t('list', {51          // https://www.i18next.com/translation-function/objects-and-arrays#objects52          // Check the link for more details on `returnObjects`53          val: t('weekdays', {returnObjects: true}),54        })}55      </p>56    </div>57  );58};

Don't forget to render the component on the home page.

app/page.tsx
1import BuiltInFormatsDemo from '../../components/BuiltInFormatsDemo';2import {createTranslation} from '../../i18n/server';3
4export default async function IndexPage() {5  const {t} = await createTranslation('home');6
7  return (8    <div>9      <h1>{t('greeting')}</h1>10      <hr className="my-4" />11      <BuiltInFormatsDemo />12    </div>13  );14};

The more you look, the more you'll be amazed

An image of a blog post

Other translation functions to check


Conclusion

Internationalization is a complex requirement simplified in Nextjs due to the way applications are built using the framework.