Preferred Locale
This is a monorepo containing the following packages:
Features
- Uses the Intl.Locale API (backwards compatible)
- Works on node & browsers
- Zero dependencies
Guaranteed Node / Browser Support
Package | Package Size |
Node | Chrome | Firefox | Safari | Edge |
---|---|---|---|---|---|---|
preferred-locale |
~600 bytes | 10+ | 69+ | 68+ | 12+ | 18+ |
Why?
Many web applications that automatically detect the browser language and serve the relevent translation are fundamentally broken.
A browser that signals the user prefers the following locales (index 0
being most preferred) should never return content in Japanese (ja-JP
) if the application has translations for Japanese and American English (en-US
):
[ 'en-GB', 'en', 'ja-JP', 'en-US', 'ja' ]
Instead, many applications (e.g Epic Games' store, help and documentation) will instead serve their users content in Japanese as they do not provide translations for British English, only American English and only check for exact matches.
preferred-locale
fixes this by traversing the supported node/browser languages in order of priority:
- If an exact match is found it uses that (e.g
en-GB
is translated). - If the node/browser language is supported but the region is not (e.g Australian English), the canonical region is looked up and tested against (e.g
en-AU
becomesen-US
), - If only a language is provided (e.g
en
), the canonical region is looked up and tested against (e.gen
becomesen-US
) - If no node/browser locale resolves to a translated locale, the fallback locale is returned
Live Demo
A step-by-step demonstration of how preferred-locale
works with your own browser locales is available at eehz9.csb.app.
Example Step-By-Step
Application has translations for en-US
and ja-JP
-
Raw browser locales
[ 'en-GB', 'en', 'ja-JP', 'en-US', 'ja' ]
-
Unify the browser locales
[ 'en-GB', 'en-US', 'ja-JP', 'en-US', 'ja-JP' ]
-
Deduplicate the locales
[ 'en-GB', 'en-US', 'ja-JP' ]
-
Remove locales not translated
[ 'en-US', 'ja-JP' ]
-
User gets content in
en-US
Contributing
See CONTRIBUTING
Releases
See Github Releases
License
All code released under MIT