Internationalization in the JSS sample app for Next.js

Current version: 20.x

A JSS Next.js application created based on the Next.js sample app comes preconfigured with the necessary settings to enable internationalization (i18n).

JSS Next.js applications support internationalized routing with sub-path routing. Domain routing requires custom implementation.

In the source directory of the Next.js JSS application, the file next.config.js contains definitions for the locales supported by the application and the defaultLocale:

RequestResponse
i18n: {
    locales: ['en', 'da-DK'],
    defaultLocale: packageConfig.language,
}
  • locales are all the languages you want to support in your application and must match (or at least be a subset of) the languages defined in Sitecore. This configuration option for Next.js has some limitations.

  • defaultLocale is the locale used when visiting a path that is not prefixed by a locale. The value is set to the value you configured in the file package.json for the config.language option.

Next.js does not provide additional i18n functionality and it is not opinionated about which content translation library you must use. To enable content localization, JSS Next.js apps use the next-localization library. In the App component, defined in the src/pages/_app.tsx file, the JSS Next.js application imports the i18n provider from the next-localization module and initializes it using the properties pageProps.locale, with a value provided by Next.js, and dictionary, with data from the Sitecore Dictionary Services. The properties are populated by the Page Props Factory:

RequestResponse
function App({ Component, pageProps }: AppProps): JSX.Element {
  const { dictionary, ...rest } = pageProps;

  return (
    <I18nProvider lngDict={dictionary} locale={pageProps.locale}>
      <Component {...rest} />
    </I18nProvider>
  );
}

For dynamic routes, JSS Next.js apps, using an instance of the SitecoreSitemapFetcher class, handle the retrieval of the locale field when preparing the static paths for the route with the function getStaticPaths.

Translating content

To translate the content of pages, you can use the useI18n hook. The hook provides a translation function t and the current language locale.

For example:

RequestResponse
import { useI18n } from 'next-localization';

const MultilingualComponent = (): JSX.Element => {
  const { t, locale } = useI18n();

  return (
    <div>
      <p>Translated text: {t('custom-key')}</p>
      <p>The current language is: {locale()}</p>
    </div>
  );
};

export default MultilingualComponent;

Do you have some feedback for us?

If you have suggestions for improving this article,