How to handle fallback page with internationalization for dynamic page in Next.js?

Viewed 35

In Next.js documentation, there is a section for internationalized routing with dynamic routes and getStaticProps pages.

In the provided example, they use the fallback property set to true:

// pages/blog/[slug].js
export const getStaticPaths = ({ locales }) => {
  return {
    paths: [
      // if no `locale` is provided only the defaultLocale will be generated
      { params: { slug: 'post-1' }, locale: 'en-US' },
      { params: { slug: 'post-1' }, locale: 'fr' },
    ],
    fallback: true,
  }
}

I have a very similar project with 2 locales: 'en' and 'fr'. Everything is working fine when my blog article does exist. But if the article does not exists (or when the page has not been generated yet at build time), then I display my custom fallback page as explained here.

I could provide my getStaticProps function or fallback page. But it is very similar to the example defined on the doc as well, so very simple.

The issue is that when displaying my fallback page, I do not have any locale yet. So all my translations display keys instead of english or french value (not only for my fallback custom component but the whole main layout/page).

From what I understand the problem is that:

  1. Fallback page is displayed until getStaticProps has finished
  2. Fallback page props are empty
  3. Locale is returned by getStaticProps function

I feel like this should be a common scenario, and maybe I'm missing something. How could I know the locale when displaying the fallback page?

Please note that I use next-i18next on my project. So my URL is either: /articles/[slug] or /fr/articles/[slug].

1 Answers

It appears that the problem was not the locale. But since the not existing pages needs to be statically generated, then the serverSideTranslations function has not yet been called. So the react-i18next/i18next has not been yet initialized with the translations neither. This means there are not yet any translations in the client in that moment.

What I chose to do is to use the 'blocking' value of the fallback property. This is not perfect, but this is the better option in my opinion.

Related