Implementing Internationalization (i18n) in Next.js: Multilingual

In this section, we will guide you through the process of implementing Internationalization (i18n) in your Next.js application. With i18n, you can create a multilingual experience for users and provide language-specific content.

Using the next-i18next Library

next-i18next is a popular library for implementing i18n in Next.js applications. Here's how you can add i18n to your application:

Install next-i18next:

npm install next-i18next

Configure the library in your next.config.js file:

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

module.exports = {
  i18n,
};

Create a configuration file named next-i18next.config.js:

module.exports = {
  i18n: {
    locales: ['en', 'fr', 'es'],
    defaultLocale: 'en',
  },
};

Use the library in your application:

import { useTranslation } from 'next-i18next';

function MyComponent() {
  const { t } = useTranslation();

  return (
    <div>
      <p>{t('welcome')}</p>
    </div>
  );
}

Creating Multilingual Content

After installing next-i18next, you can create language files like en.json, fr.json, es.json to provide content in each language:

// en.json
{
  "welcome": "Welcome!"
}

// fr.json
{
  "welcome": "Bienvenue!"
}

// es.json
{
  "welcome": "¡Bienvenido!"
}

Language Switching

To allow language switching, you can create a language switcher tool and use the i18n.changeLanguage function:

 

import { useTranslation } from 'next-i18next';

function LanguageSwitcher() {
  const { i18n } = useTranslation();

  const handleChangeLanguage = (newLanguage) => {
    i18n.changeLanguage(newLanguage);
  };

  return (
    <div>
      <button onClick={() => handleChangeLanguage('en')}>English</button>
      <button onClick={() => handleChangeLanguage('fr')}>Français</button>
      <button onClick={() => handleChangeLanguage('es')}>Español</button>
    </div>
  );
}

Conclusion

This section introduced you to the process of implementing Internationalization (i18n) in your Next.js application using the next-i18next library. By providing language-specific content and enabling users to switch languages, you can create an engaging multilingual experience for your users.