Getting user locale with JavaScript
Nov 24, 2020
To get a user's prefered locale we can query the navigator.language
.
1const locale = navigator.language; console.log(locale); // => "fr"
To change your language in Chrome go to chrome://settings/languages
and 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.
1console.log(navigator.languages); // => ["fr", "en", "en-US"]
Note: The locale value from navigator.language
is just the first item from the array of locales;
If you need this value on a server side JavaScript build such as Gatsby then remember that the 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.
1const 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.