Gatsby - SSR i18n translation are loaded on client - reactjs

I have a multilingual gatsby website, I try to improve the lighthouse performance score, so i followed this guide to generate my page with the translation in the html. Here is my gatsby-ssr.js file
import { renderToString } from 'react-dom/server'
import Backend from 'i18next-sync-fs-backend'
import i18n from "./src/locales/i18n"
const namespaces = [...my ns...];
export const replaceRenderer = ({ bodyComponent, replaceBodyHTMLString }) => {
i18n
.use(Backend)
.init({
initImmediate: false,
backend: {
loadPath: 'src/locales/{{lng}}/{{ns}}.json',
},
})
// load the common namespace
.loadNamespaces(namespaces, (err) => {
replaceBodyHTMLString(renderToString(bodyComponent))
})
}
My i18n.js file :
import i18n from "i18next";
import Backend from "i18next-xhr-backend";
import LanguageDetector from "i18next-browser-languagedetector";
import { reactI18nextModule } from "react-i18next";
i18n
.use(Backend)
.use(LanguageDetector)
.use(reactI18nextModule)
.init({
fallbackLng: "fr",
ns: ['translation'],
defaultNS: 'translation',
load: 'languageOnly',
debug: false,
interpolation: {
escapeValue: false, // not needed for react!!
},
react: {
wait: true,
},
});
export default i18n;
I use the HOC withNamespaces from react-i18next (v8) in my page like that export default withNamespaces('home')(IndexPage);
This works well because the generated HTML has all the text translated but when I access to my page the client will load a second time the translation and re-render the page, this cause a flickering on the page and big layout shift so lighthouse really not like it. I believe this is in relation with i18next-xhr-backend but I'm stuck.
I expect my page to not load the translation on page load, because the html has already the text translated so I don't need to load translation again

Related

i18next missing key but other key was found

I dont understand nothing anymore.
I use i18next and want to access to my key but it does not work.
i18next::translator: missingKey de translation profile profile
i18next::translator: missingKey de translation profile profile
i18next::translator: missingKey de translation profile profile
this is my translation.json
{
"app_name": "Test (NEW DE)",
"profile": "ss"
}
this works:
<Text>{ t('app_name') }</Text>
this not working:
<Text>{ t('profile') }</Text>
can anyone explain me why its not working correctly ?
i18next
import i18next from "i18next";
import { initReactI18next } from "react-i18next";
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from 'i18next-http-backend';
i18next
.use(HttpApi)
.use(LanguageDetector)
.use(initReactI18next)
.init({
react: {
useSuspense: false
},
fallbackLng: 'en',
compatibilityJSON: 'v3',
lng: 'de',
debug: process.env.NODE_ENV === 'development',
backend: {
loadPath: `http://192.168.0.249:4000/public/locales/{{lng}}/translation.json`,
},
interpolation: {
escapeValue: false,
},
keySeparator: '.',
});
export default i18next;
I suspect, you're calling the t function too early and are not waiting for the translations to be fully loaded.
If you're not using suspense: useSuspense: false you need to make sure you check for the ready flag instead.
https://react.i18next.com/latest/usetranslation-hook#not-using-suspense
// additional ready will state if translations are loaded or not
const { t, i18n, ready } = useTranslation('ns1');
https://react.i18next.com/latest/withtranslation-hoc#not-using-suspense
// use tReady prop in MyComponent to check if translations
// are already loaded or not
const ExtendedComponent = withTranslation()(MyComponent);
<ExtendedComponent />

Loading in i18n translations without showing translation ids

I've implemented i18next in my nextjs project, and I'm having the issue, that I can briefly see all the text-id's before the translations get fully loaded. Is there any way to avoid showing these text ID's as it causing a bit of flickering on load? It's especially obvious when refreshing the page quickly.
I have tried different ways with both useSuspense and wait in the config and App file. Currently this is what I have (translation files are located in public/locales/xx/translation.json):
i18n.jsx
import i18n from 'i18next';
import { initReactI18next } from 'react-i18next';
import Backend from 'i18next-http-backend';
i18n
.use(Backend)
.use(initReactI18next)
.init({
debug: true,
fallbackLng: 'en',
interpolation: {
escapeValue: false, // not needed for react as it escapes by default
},
react: {
useSuspense: true
}
});
export default i18n;
Usage:
import { useTranslation } from 'react-i18next';
export default function Text () {
const { t } = useTranslation();
return (<Text>{t('text.string.here')}</Text>)
App
import { Suspense } from 'react'
import i18n from 'components/i18n'
function MyApp({ Component, pageProps }) {
<Suspense fallback="loading">
<Component {...pageProps}/>
</Suspense>
}

React-i18next does not load translations on page reload

I am using react-I18next in my nextjs application. I don't want to use next-I18next because I tried to use it but couldn't make it work. But react-i18next is working in my application for now and I am able to change language from english to german and back. However if I reload the page I get this error.
TypeError: i18n.changeLanguage is not a function
What could be the possibel cause of this error and how can I fix it?
P.S In my app.ts file I am not using Suspense because it gives me this error
ReactDOMServer does not yet support Suspense.
Here is my i18.ts file
/* eslint-disable no-duplicate-imports */
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import backend from 'i18next-xhr-backend';
import { initReactI18next } from 'react-i18next';
import loginDE from '../../public/locales/de/loginDE.json';
import loginEN from '../../public/locales/en/loginEN.json';
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: loginEN,
},
de: {
translation: loginDE,
},
};
void i18n
.use(backend)
.use(LanguageDetector)
.use(initReactI18next) // passes i18n down to react-i18next
.init({
fallbackLng: 'en',
interpolation: {
escapeValue: false, // react already safes from xss
},
resources,
lng: 'en',
keySeparator: false, // we do not use keys in form messages.welcome
react: {
useSuspense: true,
},
});
export default i18n;
ReactDOMServer does not yet support Suspense.
Change your useSuspense value like that:
react: { useSuspense: false },
TypeError: i18n.changeLanguage is not a function
Make sure you wrapped a component with I18nextProvider

Set i18next language based on HTML tag

OK, so I'm experimenting with ReactJS and i18next.
I want to set my translation language on the initial page load based on
some html tag.
For example if I have <html lang="de"> when the page is loaded I would like to have
the lng set to de before any translations take place.
Here's the content of my i18n.js file:
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
// the translations
// (tip move them in a JSON file and import them)
const resources = {
en: {
translation: {
"Welcome to React": "Translation in English"
}
},
de: {
translation: {
"Welcome to React": "Translation in German"
}
}
};
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: "en",
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
}
});
export default i18n;
From here
const htmlLang = document.documentElement.lang; // for <html lang=".."> not xml-lang:".."
Now you can put this constant in youe i18n declaration
i18n
.use(initReactI18next) // passes i18n down to react-i18next
.init({
resources,
lng: htmlLang,
keySeparator: false, // we do not use keys in form messages.welcome
interpolation: {
escapeValue: false // react already safes from xss
},
fallbackLng: ['en', //'fr', ...]
});
I also add a fallback language

i18n load translations from s3bucket

I am using the i18n module in my react app which is hosted as an app (which I will refer to as live app) on S3 and has cloudfront sitting in front of it.
I want to store the s3 url in a config file as to avoid having it hardcoded in my app so that I can work against translation files stored locally in the public/locales folder when I'm developing.
Initially I had my backend options set-up so that it would always try and look up the files in the locales path. And this worked locally but stopped working on S3 although the locales folder was present in the S3 bucket. I also noticed that no request was being sent from the app to retrieve the translation files.
backend: {
loadPath: 'locales'
}
I then decided to upload the translation files to another S3 bucket and host them there to see if this would fix the issue.
I changed my config to hardcode the s3 bucket path. This worked both locally and on the live app. But this means that I can't use my config file to determine the loadPath option.
backend: {
loadPath: '<myhardcoded-s3-bucket-url>/{{lng}}/translation.json',
crossDomain: true
}
I then thought I could construct the url in place as so:
/*global AWS_CONFIG */
/*eslint no-undef: "error"*/
...
...
...
backend: {
loadPath: `${AWS_CONFIG.aws_app_translations_path}/{{lng}}/translation.json`,
crossDomain: true
}
Strangely again this worked locally when AWS_CONFIG.aws_app_translations_path was both http://localhost:3000/locales and <myhardcoded-s3-bucket-url>.
However once I pushed it live, it failed again. This time making a request to https://<my-apps-base-path>/undefined/en-GB/translation.json for example. So it's trying to use the app path and append what I have defined in loadPath.
I then saw that I could have loadPath as a function to construct my url. This didn't work for the live app either, but again worked locally.
backend: {
loadPath: function (lng) {
return `${AWS_CONFIG.aws_app_translations_path}/${lng}/translation.json`
},
crossDomain: true
}
This is my entire i18n file
/*global AWS_CONFIG */
/*eslint no-undef: "error"*/
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
const options = {
order: ['navigator', 'localStorage'],
caches: ['localStorage'],
fallbackLng: "en-GB",
debug: true,
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
backend: {
loadPath: function (lng) {
return `${AWS_CONFIG.aws_app_translations_path}/${lng}/translation.json`
},
crossDomain: true
}
}
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init(options);
export default i18n;
What could explain this odd behaviour? Am I missing configuration here?
Based on your responses in the comments, looks like you are missing the translation part, and it pre-appending undefined as a namespace in the url.
Try this:
// i18n
const options = {
order: ['navigator', 'localStorage'],
caches: ['localStorage'],
fallbackLng: "en-GB",
debug: true,
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
backend: {
loadPath: function () {
return `${AWS_CONFIG.aws_app_translations_path}/{{lng}}/{{ns}}.json`
},
crossDomain: true
}
}
Based on the loadPath config doc:
path where resources get loaded from, or a function
returning a path:
function(lngs, namespaces) { return customPath; }
The returned path will interpolate lng, ns if provided like giving a static path
Once I changed the way I was importing the config file it worked. I am guessing there is a loading issue on live, but having changed my i18n file from
/*global AWS_CONFIG */
/*eslint no-undef: "error"*/
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
const options = {
order: ['navigator', 'localStorage'],
caches: ['localStorage'],
fallbackLng: "en-GB",
debug: true,
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
backend: {
loadPath: function (lng) {
return `${AWS_CONFIG.aws_app_translations_path}/${lng}/translation.json`
},
crossDomain: true
}
}
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init(options);
export default i18n;
to
import i18n from "i18next";
import LanguageDetector from "i18next-browser-languagedetector";
import Backend from "i18next-http-backend";
import { initReactI18next } from "react-i18next";
import {config} from './config';
const {aws_app_translations_path} = config;
const options = {
order: ['navigator', 'localStorage'],
caches: ['localStorage'],
fallbackLng: "en-GB",
debug: true,
defaultNS: 'translation',
load: 'currentOnly',
interpolation: {
escapeValue: false // not needed for react as it escapes by default
},
backend: {
loadPath: (lng, ns) => {
return `${aws_app_translations_path}/${lng}/${ns}.json`;
},
crossDomain: true
}
}
i18n
.use(Backend)
.use(LanguageDetector)
.use(initReactI18next)
.init(options);
export default i18n;
Fixed it. Initially AWS_CONFIG was being returned as undefined despite working for the rest of the entire app. Changing the config file to live in the root directory of the project and the way it was imported solved the issue.

Resources