i18next / i18next-browser-languageDetector

language detector used in browser environment for i18next
MIT License
865 stars 88 forks source link

Failed to read the 'cookie' property from 'Document': Cookies are disabled inside 'data:' URLs. #279

Closed m-nathani closed 9 months ago

m-nathani commented 9 months ago

🐛 Bug Report

To Reproduce

A minimal reproducible example.

We found a report on sentry about failing to read cookies cookies on specific env mentioned below.

import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import HttpApi from 'i18next-http-backend';
import { initReactI18next } from 'react-i18next';
...

export const initI18next = ({ languages, defaultLanguage }) => {
  const detectionOptions = {
    order: ['cookie', 'localStorage', 'navigator'],
    lookupCookie: 'i18next-widget',
    lookupLocalStorage: 'i18nextLng-widget',
    caches: ['localStorage', 'cookie'],
    excludeCacheFor: ['cimode'],
  };

  ...

  i18nInstance = i18n.use(HttpApi).use(LanguageDetector).use(initReactI18next);
  i18nInstance
    .init({
      load: 'currentOnly',
      supportedLngs,
      cleanCode: true,
      interpolation: {
        escapeValue: false,
      },
      detection: detectionOptions,
      ns: ['translation', 'common'],
      react: {
        useSuspense: true,
      },
      backend: {
        // locale files can be found in the `public` directory
        loadPath: `${getFilePath()}/locales/{{lng}}/{{ns}}.json`,
        // We don't want to cache the translation files
        requestOptions: {
          cache: 'no-store',
        },
        // Required when widget is embedded in partner website?
        crossDomain: true,
      },
    })
    .then(() => {
      // TODO: Lazy load moment locale?
      moment.locale(i18nInstance?.language);
    });

  return i18nInstance;
};

Expected behavior

Plugin for browser detection should have checks for reading cookies if they are enabled.

something similar to navigator.cookieEnabled : https://developer.mozilla.org/en-US/docs/Web/API/Navigator/cookieEnabled

P.S: will add these check in my code too.. however would be great to handle in detector itself to handle fallback.

Your Environment

adrai commented 9 months ago

You can do this yourself:

const detectionOptions = {
    order: navigator.cookieEnabled ? ['cookie', 'localStorage', 'navigator'] : ['localStorage', 'navigator'],
    lookupCookie: 'i18next-widget',
    lookupLocalStorage: 'i18nextLng-widget',
    caches: navigator.cookieEnabled ? ['localStorage', 'cookie'] : ['localStorage'],
    excludeCacheFor: ['cimode'],
  };
adrai commented 9 months ago

fyi: similar discussion: https://github.com/js-cookie/js-cookie/issues/823#issuecomment-1543972888

m-nathani commented 9 months ago

fyi: similar discussion: js-cookie/js-cookie#823 (comment)

Way to go, for creating a robust api ! 😆