resolve-accept-language

Resolve the preferred locale based on the value of an `Accept-Language` HTTP header.

Usage no npm install needed!

<script type="module">
  import resolveAcceptLanguage from 'https://cdn.skypack.dev/resolve-accept-language';
</script>

README

resolve-accept-language

License npm download Coverage Dependencies Known Vulnerabilities

Resolve the preferred locale based on the value of an Accept-Language HTTP header.

Usage

Add the package as a dependency:

npm install resolve-accept-language

Code example:

import resolveAcceptLanguage from 'resolve-accept-language';

console.log(
  resolveAcceptLanguage('fr-CA;q=0.01,en-CA;q=0.1,en-US;q=0.001', ['en-US', 'fr-CA'], 'en-US')
);

Output:

fr-CA

Why another Accept-Language package?

The Accept-Language header has been around since 1999. Like many other standards that deal with languages, the headers is based on BCP 47 language tags. Language tags can be as simple as fr (non country specific French) or more complex, for example sr-Latn-RS would represent latin script Serbian.

One of the main challenge is that BCP 47 language tags can be either overly simple or too complex. This is one of the problem this library will try to address by focusing on locales identifier using the language-country format instead of trying to provide full BCP 47 language tags support. The main reasons for this:

  • Using 2 letter language codes is rarely sufficient. Without being explicit about the targeted country for a given language, it is impossible to provide the right format for some content such as dates and numbers. Also, while languages are similar across countries, there are different ways to say the same thing. Our hypothesis is that by better targeting the audience, the user experience will improve.
  • About 99% of all cases can be covered using the language-country format. We could possibly extend script support in the future given a valid use case, but in the meantime our goal is to keep this library as simple as possible, while providing the best matches.

How does the resolver work?

As per RFC 4647, this solution uses the "lookup" matching scheme. This means that it will always produce exactly one match for a given request.

The matching strategy will use the following rules:

  1. Extract all supported locales and languages and sort them by quality factor.
  2. If the first result with the highest quality is a locale, return this as the best match.
  3. Otherwise, if that result is a language, find the first supported locale with that language (the default locale is always checked first).
  4. Otherwise, if no locale or language matches, check if there is a match with an unsupported locale that had a supported language (the default locale is always checked first).
  5. When all fails, return the default locale.

Additional references