-
-
Notifications
You must be signed in to change notification settings - Fork 638
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add browser language detector to automatically switch to defaul…
…t browser lang (#2022) Co-authored-by: Akshat Nema <[email protected]>
- Loading branch information
1 parent
9f5f7d3
commit 7eda8a3
Showing
3 changed files
with
52 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
const { i18n } = require("./../next-i18next-static-site.config"); | ||
|
||
// Converts languages like 'en-US' to 'en' | ||
const convertLanguageCode = (code) => { | ||
const baseLanguageCode = code.split('-')[0]; | ||
return baseLanguageCode; | ||
}; | ||
|
||
function browserLanguageDetector() { | ||
|
||
// Fetch the language stored inside localStorage | ||
const localStorageLanguage = localStorage.getItem('i18nLang'); | ||
|
||
if (localStorageLanguage) { | ||
return localStorageLanguage; | ||
} | ||
|
||
// Load available languages from i18n object | ||
const availableLanguages = i18n.languages; | ||
|
||
// Load user's default languages from browser settings | ||
const browserDefaultLanguages = navigator.languages; | ||
|
||
const convertedLanguages = browserDefaultLanguages.map((code) => convertLanguageCode(code)); | ||
|
||
// Check if the top priority language is available inside i18n object | ||
for (var i = 0; i < convertedLanguages.length; i++) { | ||
if (availableLanguages.includes(convertedLanguages[i])) { | ||
return convertedLanguages[i]; | ||
} | ||
} | ||
// Default to 'en' in all other cases | ||
return 'en'; | ||
} | ||
|
||
export default browserLanguageDetector; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters