i18next / next-i18next

The easiest way to translate your NextJs apps.
https://next.i18next.com
MIT License
5.61k stars 762 forks source link

Translation keys are briefly shown when using `getStaticPaths` with fallback = `true` #1611

Closed marnixhoh closed 2 years ago

marnixhoh commented 2 years ago

Describe the bug

When using getStaticPaths to dynamically render pages with fallback set to true, the translation keys are briefly shown when loading a dynamic page directly.

Occurs in next-i18next version

8.9.0

Steps to reproduce

pages/Item/[id].js

import { useTranslation } from 'next-i18next'
import { serverSideTranslations } from 'next-i18next/serverSideTranslations'

const Item = () => {
    const { t } = useTranslation('myTranslations')

    return (
        <h1>{t(`myTitle`)}</h1>
    )
}

export default Item

export const getStaticPaths = () => {
    return { paths: [], fallback: true }
}

export const getStaticProps = async ({ locale }) => ({
    props: {
        ...await serverSideTranslations(locale, ['myTranslations']),
    }
})

Now when navigating to example.com/item/123 directly, the page will briefly show myTitle, before showing the actual translation.

Note that when navigating to example.com/item/123 from another page, this doesn't happen. (As I assume the translations are already loaded and available at this point?)

Expected behaviour

I expect that using fallback: true, does not result in the rendering of the translation key, but instead immediately shows the actual translation.

OS (please complete the following information)

Additional context

Perhaps I don't understand the inner workings of next-i18next with next.js well enough and this is expected behavior? But if this is the case, are there are any workarounds?

isaachinman commented 2 years ago

Have you read the docs on fallback pages?

Basically, a fallback page doesn't run any data-fetching methods, and next-i18next needs those data-fetching methods (getStaticProps/getServerSideProps) to pass translations as props.

There are probably several possible workarounds for this, like importing the global i18n instance directly, and waiting for initialisation, but fallback: 'blocking' is probably the quickest fix.

Let me know if you have any other questions.

marnixhoh commented 2 years ago

Thank you for your reply and explanation!

Does this then mean that next-i18next can not be used with a fallback page without showing the translation keys?

Perhaps an option to make the default an empty string, instead of the translation key would be a good feature?

isaachinman commented 2 years ago

It would be possible, if you followed this guide to load translations on the client side, dynamically.

However, unless your SSR process is extremely high latency, I think requesting namespaces from the client side would be a much worse solution than just blocking SSR.

Perhaps an option to make the default an empty string

That kind of behaviour is handled by i18next directly.