Reputation: 169
I am using next-i18next in my Next JS project to handle translations. I want to make a call to the backend when a key
is missing to store it in the database.
I have found that there are functions for this in i18next, specifically by setting saveMissing
and missingKeyHandler
functions (see here: https://www.i18next.com/overview/configuration-options)
However, when adding missingKeyHandler
to my next-i18next.config.js
file, I get this error: "error - SerializableError: Error serializing ._nextI18Next.userConfig.missingKeyHandler
returned from getServerSideProps
in "/dashboard/assettrack".
Reason: function
cannot be serialized as JSON. Please only return JSON serializable data types."
This is my next-i18next.config.js file:
module.exports = {
i18n: {
defaultLocale: "en",
locales: ["en","es","ca"]
},
localePath: path.resolve('./appdata/locales'),
localeStructure: '{{lng}}/{{ns}}',
debug: process.env.NODE_ENV === 'development',
reloadOnPrerender: process.env.NODE_ENV === 'development',
saveMissing: true,
missingKeyHandler: (lng, ns, key, fallbackValue) => {
const message = `Missing translation key [${key}] for [${lng}/${ns}], fallbackValue: ${fallbackValue}`;
console.warn(message);
return { message };
}
}
This of course makes sense, but then the question begs, how can one add their own missingKeyHandler
function?
I have also tried creating a custom useTranslation hook that extends the native useTranslation hook, but I have not had any success yet.
Upvotes: 1
Views: 1665
Reputation: 1
I had the same problem, but i could solve it by setting the serializeConfig
inside my next-i18next.config.js
to false
.
From the docs:
To fix this, you'll need to set config.serializeConfig to
false
, and manually pass your config intoappWithTranslation
So, the setup is something like this:
// next-i18next.config.js
module.exports = {
i18n: {
// your i18n config
},
// ... other configs
serializeConfig: false,
saveMissing: true,
missingKeyHandler: yourApiCallback,
}
// _app
import nextI18NextConfig from 'next-i18next.config';
const MyApp = ({ Component, pageProps }) => (
<Component {...pageProps} />
)
export default appWithTranslation(MyApp, nextI18NextConfig);
Keep in mind that with this setup i still call the next-i18next
config inside my next-config.js
as the docs suggests.
Upvotes: 0
Reputation: 847
that would be because you're returning a object instead of a value, also i wouldn't return message (because the expected translation would be replaced with the message) but the fallbackValue
missingKeyHandler: (lng, ns, key, fallbackValue) => {
const message = `Missing translation key [${key}] for [${lng}/${ns}], fallbackValue: ${fallbackValue}`;
console.warn(message);
return fallbackValue;
}
Upvotes: 0