Middle+
Look at this SSR code with a singleton i18n class. Find a serious problem that could spoil the HTML delivered to the user. How to fix it?
sobes.tech AI
Answer from AI
The problem with the singleton i18n class in SSR is that the localization state is stored globally and shared among all requests. This leads to a situation where, during parallel requests, users might receive HTML with the wrong language — localization data can be overwritten.
How to fix:
- Do not use a singleton to store the localization state.
- Create a separate instance of i18n for each request to keep localization isolated.
- Pass the required language explicitly to the rendering function.
Example:
function createI18n(lang) {
return new I18n(lang);
}
app.get('*', (req, res) => {
const i18n = createI18n(req.language);
const html = renderApp({ i18n });
res.send(html);
});
This way, we avoid race conditions and ensure the correct language for each user.