@narando/negotiate-accepted-language
A custom Accept-Language
parser. You can use this package to localize your
clients based on the http headers.
Getting Started
You need to have nodejs
and npm
installed.
$ npm install @narando/negotiate-accepted-language
Usage
Based on the priority the best matching language will be returned.
import negotiateAcceptedLanguage from "@narando/negotiate-accepted-language";
const supportedLanguages = ["de-DE", "en-US"];
const acceptedLanguages = "de-DE,de;q=0.9,en;q=0.8,en-US;q=0.7";
negotiateAcceptedLanguage(supportedLanguages, acceptedLanguages);
In case no one of the accepted languages will match the supported languages exactly.
The function tries to find the closest match.
To find the closest match the country tag will be ignored.
import negotiateAcceptedLanguage from "@narando/negotiate-accepted-language";
const supportedLanguages = ["de-AT", "en-US"];
const acceptedLanguages = "de-DE,en-CA;q=0.9";
negotiateAcceptedLanguage (supportedLanguages, acceptedLanguages);
Usage as express middleware
Implement this function as an express middleware.
import negotiateAcceptedLanguage from "@narando/negotiate-accepted-language";
function getLanguageMiddleware(req, res, next) {
const supportedLanguages = ["de-DE", "en-US"];
const acceptedLanguages = req.get("accept-language");
const language = negotiateAcceptedLanguage(
supportedLanguages,
acceptedLanguages
);
req.i18n.setLanguage(language);
req.language = language;
next();
}
app.use(getLanguageMiddleware);
Error handling
The function wil return null if the languagesToParse
are not supported.
import negotiateAcceptedLanguage from "@narando/negotiate-accepted-language";
const supportedLanguages = ["de-DE", "en-US"];
const acceptedLanguages = "af,ch-ZH;q=0.8";
const matchingLanguage = negotiateAcceptedLanguage(
supportedLanguages,
acceptedLanguages
);