Talkr icon indicating copy to clipboard operation
Talkr copied to clipboard

In SSR navigator is not defined

Open gshilin opened this issue 6 years ago • 11 comments

gshilin avatar Nov 06 '20 12:11 gshilin

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.

gshilin avatar Nov 07 '20 02:11 gshilin

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.

DoneDeal0 avatar Nov 07 '20 18:11 DoneDeal0

This happens in https://github.com/DoneDeal0/Talkr/blob/ed261f3bfffc28bbfc6478f0375bc696c02f0702/src/index.tsx#L23 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 :(

gshilin avatar Nov 08 '20 01:11 gshilin

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

DoneDeal0 avatar Nov 12 '20 16:11 DoneDeal0

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.

DoneDeal0 avatar Nov 12 '20 16:11 DoneDeal0

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

typeof navigator !== 'undefined'

gshilin-sdb avatar Nov 12 '20 17:11 gshilin-sdb

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

DoneDeal0 avatar Nov 12 '20 17:11 DoneDeal0

image

gshilin-sdb avatar Nov 12 '20 17:11 gshilin-sdb

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

gshilin-sdb avatar Nov 12 '20 17:11 gshilin-sdb

I did a pull request which fixes this issue.

https://github.com/DoneDeal0/Talkr/pull/6

lodmfjord avatar Nov 27 '20 09:11 lodmfjord

@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)!

DoneDeal0 avatar Nov 27 '20 15:11 DoneDeal0