Blog>
Snippets

Implementing Internationalization with i18next

Setup i18next in Next.js for internationalization, demonstrating how to configure localization and use translation hook in a sample page.
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
import LanguageDetector from 'i18next-browser-languagedetector';

i18n
  .use(Backend) // load translations using http (default public/locales)
  .use(LanguageDetector) // detect user language
  .use(initReactI18next) // pass the i18n instance to react-i18next.
  .init({
    fallbackLng: 'en',
    debug: true,
    interpolation: {
      escapeValue: false, // not needed for react as it escapes by default
    }
  });

export default i18n;
This code initializes i18next with an HTTP backend for loading translation files, a language detector to automatically detect the user's language, and integrates with React using react-i18next. It also sets a fallback language (English in this case) and turns on debug mode for development purposes.
import { useTranslation } from 'react-i18next';

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

  return (
    <div>
      <h1>{t('welcome_message')}</h1>
    </div>
  );
}

export default MyComponent;
This code uses the `useTranslation` hook from react-i18next within a functional component to translate a welcome message. The `t` function is used to retrieve the corresponding string from the loaded translation files based on the current language.
import { appWithTranslation } from 'next-i18next';

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

export default appWithTranslation(MyApp);
This code wraps the top-level Next.js custom App component with the `appWithTranslation` higher-order component from next-i18next, which provides the i18next configuration for the entire Next.js application. It ensures that the translations are ready and available at every level of the component tree.