DoneDeal0/Talkr

In SSR navigator is not defined

gshilin opened this issue ยท 11 comments

In SSR navigator is not defined

navigator is not defined when is SSR mode. You use it to detect browser's language, but in this case it's impossible, so 'en' may be good enough instead of crash.

Hi Gshilin, thanks for using Talkr! Automatic language detection is an option. You can simply write

  <Talkr languages={{ en, fr }} defaultLanguage="en">
    <App />
  </Talkr>

to let the lib use "en" by default. However, I'll definitely add a fix in the future to avoid any crash with automatic browser detection in case it is not supported.

This happens in

const browserLanguage = navigator.language.split("-")[0];
and that's not inside any condition.
The solution I found is to simulate navigator:

if (typeof navigator === 'undefined') {
  navigator = {
    language: 'en-US',
  };
}

But it's quite ugly :(

I've just implemented the fix. It should be available on npm very soon.

The correct version is 2.0.2 or superior. The 2.0.1 has an export bug. Npm hasn't updated the package yet, please wait for this version to be available before updating your own package.

Looked at it. Unfortunately it'll return
Uncaught ReferenceError: navigator is not defined.
You have to use

typeof navigator !== 'undefined'

Why? The script checks if navigator exists, so it should not crash if the latter is undefined. detectBrowserLanguage && navigator ? browserLanguage : defaultLanguage.

The script checks if navigator has truthful value, but if it doesn't exist if will crash

I did a pull request which fixes this issue.

#6

@gshilin Sorry for the huge delay in my answer, I had a lot of work and completely forgot to tweak this undefined navigator issue in ssr. Thanks @lodmfjord for taking care of that! I'll push the patch on npm by monday (hopefully this evening)!