Next.js i18n – Add Internationalization with Example Tutorial

In this guide, we will discuss how to add the Internationalization or i18n feature in the Next js application, which will have a select box to easily switch between various languages and also update the text on the page right away. Having a language switch option or translation feature is a very important aspect of…

By.

•

min read

In this guide, we will discuss how to add the Internationalization or i18n feature in the Next js application, which will have a select box to easily switch between various languages and also update the text on the page right away.

Having a language switch option or translation feature is a very important aspect of web development, especially for those applications which are served to the global audience. Thankfully in Next js a popular framework for React, we have good support for i18n which makes it a good choice for developers.

Native Next.js i18n

After Next js 10, it has a built-in support for the internationalization routing, which means that after a few locale configurations Next js can automatically handle the localized routing. This adds a powerful feature in Next js including the sub-route path and domain routing.

In the Sub-Route path, the locale becomes part of the URL /blog, /fr/blog, /es/blog.

On the other side, the domain routing has the locale which appears in the top-level domain, like mywebsite.com/blog, mywebsite.fr/blog, mywebsite.nl/blog.

 

Libraries for Next.js i18n

There are a number of libraries available to enable the feature of i18n in Next js which includes the following:

next-i18next simplifies the process of adding i18n support to Next js apps. It helps to use i18next on both the client and the server with a consistent API.

react-i18next is a powerful internationalization framework for React.js and Next.js which provides many features to simplify the i18n process in your app.

i18next is for browsers or any other javascript environment like Node.js.

 

How to Add i18n in Next js Application?

Follow these quick steps to add a language switch dropdown in Next js application to implement localization support:

Step 1 – Create Next js Application

Step 2 – Install Required Libraries

Step 3 – Next js i18n Configuration

Step 4 – Create Locale Files

Step 5 – Create Language Switch Component

Step 6 – Wrap App with Translation

Step 7 – Update Index Page

Step 8 – Run the Application

 

 

Step 1 – Create Next js Application

First, create a new Next js application by executing the below create-next-app command:

npx create-next-app@11 nextjs-app-with-i18n

 

Thereafter, move inside the application directory:

cd nextjs-app-with-i18n

 

Step 2 – Install Required Libraries

After creating the Next js application project, we will install the required libraries to implement the i18n or internationalization support.

Execute the following command at your application root to install these npm packages:

npm install next-i18next react-i18next i18next

 

Step 3 – Next js i18n Configuration

Now, we need to configure our Next js app to use the i18n, for that we will create two new files at the application root:

 

Create next.config.js File

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

This config will intimate Next js that our application will support the English and German languages where English is the default locale.

 

Create next-i18next.config.js

// next-i18next.config.js
const path = require("path");

module.exports = {
  i18n: {
    defaultLocale: "en",
    locales: ["en", "de"],
  },
  localePath: path.resolve("./public/locales"),
};

In the above config, we are telling the next-i18next that our default locale is English – en and we are providing support for English and German – de.

Here the localePath is the path to the directory where we will be placing the translation files in further steps.

 

Step 4 – Create Translation Locale Files

After placing the configuration files, next we need to create the locale files for each language we support i.e. English – en and German – de.

Create these new directories with a file named common.json:

~public/locales/en/comman.json

~public/locales/de/comman.json

The directory structure will look like this:

.
└── public
    └── locales
        ├── en
        |   └── common.json
        └── de
            └── common.json

 

After creating the respective common.json files, update them with the following content:

// en/common.json
{
  "hello": "Hello",
  "welcome": "Welcome to our blog!"
}

// de/common.json
{
  "hello": "Hallo",
  "welcome": "Willkommen in unserem Blog!"
}

 

Step 5 – Create Language Switch Component

Our page will show a select box dropdown using which a user can easily switch the preferred language from English or German. For that, we will create a new LanguageSwitcher component.

Create a new file ~components/LanguageSwitcher.js at the application root and update with the following code:

// components/LanguageSwitcher.js
import { useState } from "react";
import { useRouter } from "next/router";

export const LanguageSwitcher = () => {
  const router = useRouter();
  const [selectedLanguage, setSelectedLanguage] = useState(router.locale);

  const changeLanguage = (event) => {
    const newLanguage = event.target.value;
    setSelectedLanguage(newLanguage);
    router.push(router.pathname, router.asPath, { locale: newLanguage });
  };

  const setDefaultLanguage = () => {
    localStorage.setItem("defaultLanguage", selectedLanguage);
  };

  return (
    <div>
      <select value={selectedLanguage} onChange={changeLanguage}>
        {router.locales.map((locale) => (
          <option key={locale} value={locale}>
            {locale}
          </option>
        ))}
      </select>
      <button onClick={setDefaultLanguage}>Set as default</button>
    </div>
  );
};

 

Step 6 – Wrap App with Translation

The most important part is to wrap our custom _app component using the appWithTranslation. This will set up the i18n context for our Next js pages which will enable us to use the useTranslation hook.

Open the pages/_app.js file, and update as shown below:

// pages/_app.js
import { appWithTranslation } from "next-i18next";

function MyApp({ Component, pageProps }) {
  return <Component {...pageProps} />;
}

export default appWithTranslation(MyApp);

 

Step 7 – Update Index Page

Finally, we will localize our pages and components, and for that open the pages/index.js file and update it with the following:

// pages/index.js
import { serverSideTranslations } from "next-i18next/serverSideTranslations";
import { useTranslation } from "next-i18next";
import { LanguageSwitcher } from "../components/LanguageSwitcher";

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

export default function Home() {
  const { t } = useTranslation("common");

  return (
    <div>
      <LanguageSwitcher />
      <h1>{t("hello")}</h1>
      <p>{t("welcome")}</p>
    </div>
  );
}

 

 

Step 8 – Run the Application

We are done with the implementation, now you can test the i18n implementation in the Next js app by running the application. Execute the npm run dev command in the terminal.

Next.js i18n - Add Internationalization with Example Tutorial

 

Conclusion

We have finally implemented the internationalization or i18n in the Next js application by using the next-i18nnext plugin and configuring it. We created the translation files which can have key-value pairs for various labels we use in our Next js app.

We use the serverSideTranslations function with useTranslation hook in our component which ensures that elements are set up correctly in sync with i18n implementation.

We also added the language switcher select box to easily change the language on runtime.  Hope this will be helpful to scale the i18n implementation in your Next js application.

Leave a Reply

Your email address will not be published. Required fields are marked *