You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
@edit wrong repo. Wanted to ask in general i18next.
I've read that singleton in i18next might lead to problems in production, not sure if I understood it well.
I have this code:
import i18next from 'i18next';
import Backend from 'i18next-fs-backend';
import { join } from 'path';
import { readdirSync, lstatSync } from 'fs';
import appRootPath from "app-root-path";
import { match } from "@formatjs/intl-localematcher";
import Negotiator from "negotiator";
const localesFolder = join(appRootPath.toString(), './locales');
const languages = readdirSync(localesFolder).filter((fileName) => {
const joinedPath = join(localesFolder, fileName);
return lstatSync(joinedPath).isDirectory();
})
const matchLocale = (userLanguages) => {
try {
return match(userLanguages, languages, 'en');
} catch(_) {
return null;
}
}
i18next
.use(Backend)
.init({
initImmediate: false, // setting initImediate to false, will load the resources synchronously
fallbackLng: 'en',
preload: languages,
backend: {
loadPath: join(localesFolder, '{{lng}}/{{ns}}.json5')
}
});
function i18nMiddleware() {
return (req, res, next) => {
const acceptLanguages = new Negotiator(req).languages();
const langCookie = req.cookies.lang?.toLowerCase();
const lng = matchLocale([languages.includes(langCookie) && langCookie, ...acceptLanguages]) || matchLocale(acceptLanguages) || 'en';
// should i18n instance be created via createInstace() on every request?
req.t = i18next.getFixedT(lng);
// use like req.t('hello')
next();
}
}
export default i18nMiddleware
Is this code insecure in production? I've read "singleton" might cause troubles with concurrency, and overriding languages.
should i18n instance be created via createInstace() on every request?
I thought it's good to preload all languages + all namespaces once, and then the t(...) is just filtering languages and returning the one we want, but it seems the underlying mechanism is different?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
-
@edit wrong repo. Wanted to ask in general i18next.
I've read that singleton in i18next might lead to problems in production, not sure if I understood it well.
I have this code:
Is this code insecure in production? I've read "singleton" might cause troubles with concurrency, and overriding languages.
should i18n instance be created via createInstace() on every request?
I thought it's good to preload all languages + all namespaces once, and then the
t(...)
is just filtering languages and returning the one we want, but it seems the underlying mechanism is different?Beta Was this translation helpful? Give feedback.
All reactions