From c506311787410c53ac9b9c87952fd43ba22c737a Mon Sep 17 00:00:00 2001 From: Mike Eling Date: Tue, 4 May 2021 02:16:29 +0200 Subject: [PATCH] :bug: Fix crashes on SSR when detecting locale --- CHANGELOG.md | 2 ++ src/utils/methods.ts | 14 ++++++++++++-- 2 files changed, 14 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 1234aa1..0b8586d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -3,6 +3,8 @@ All notable changes to this project will be documented in this file. ## [Unreleased] +### Fixed +- Crashes on SSR when detecting locale. ## [2.2.1] - 2021-05-03 ### Changed diff --git a/src/utils/methods.ts b/src/utils/methods.ts index 47c2704..340cb9b 100644 --- a/src/utils/methods.ts +++ b/src/utils/methods.ts @@ -8,10 +8,20 @@ export const validateLocale = (l: string, p: RegExp) => { return Boolean(new RegExp(_p).test(l)); } +/** + * Detects the preferred locale and parses it. + * @returns Detected browser locale or null. + */ export const detectDeviceLocale = () => { - const browserLocale = tryParseLocale(window.navigator.language); + let browserLocale = null; + + if(window?.navigator?.language) + browserLocale = tryParseLocale(window.navigator.language) + + if(window?.navigator?.languages?.length > 0) + browserLocale = tryParseLocale(window.navigator.languages[0]); - if(!browserLocale) console.warn("Locale not detected."); + if(!browserLocale) console.warn("Littera could not determine the preferred locale."); return browserLocale || null; }