To get a user's prefered locale we can query the
const locale = navigator.language; console.log(locale); // => "fr"
To change your language in Chrome go to
chrome://settings/languagesand add/edit the list of languages.
To get the full list of user languages we can use
navigator.languages. This returns an array of locales in order of preference.
console.log(navigator.languages); // => ["fr", "en", "en-US"]
Note: The locale value from
navigator.languageis just the first item from the array of locales;
node.js environment has no concept of the
navigator so we need to check for it and specify a fallback when it doesn't exist.
const locale = (navigator && navigator.language) || "en"; console.log(locale); // Client => "fr" console.log(locale); // Server => "en"
We can then use this preference to format content such as dates, currency and time for users to their local preferences.