3

I'm using Nextjs and trying to make multi language application. Multi langugage working properly but when I'm trying get language code with cookie like 'en', getting error.

This way working;

initialLang = 'en';
setDefaultTranslations({en, fr});
setLanguage('en');

But when I'm trying to set initialLang with cookie not working.

This way not working

initialLang = Cookies.get('lang');
setDefaultTranslations({en, fr});
setLanguage(initialLang);

2 Answers2

0

To solve your problem you need to step back and understand the problem. The main problem about the cookie is you need to split your code to read&write cookie for server and client. js-cookie works for only client-side. Basically, it works on the client because it works with document.cookie. When it calls document in next.js SSR, the backend code is not able to read the document because it does not exist. If you would like to read cookie in SSR you need to catch it from expressjs request and pass into react state. I would recommend you to use https://github.com/andreizanik/cookies-next which already solves this problem (implementation)

hurricane
  • 6,521
  • 2
  • 34
  • 44
-1

Probably, you're not using them in componentDidMount hook:

componentDidMount() {
  // get cookie
  // set state to update the language
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231