jshttp / negotiator

An HTTP content negotiator for Node.js
MIT License
309 stars 33 forks source link

Language negotiator returns first item of availableLanguages array no matter what #66

Closed EverlyScott closed 9 months ago

EverlyScott commented 9 months ago

I'm writing a Next.JS application that uses negotiator to find the best language to use from what we have translated.

This is our code currently:

  let lang = cookies.get("lang")?.value; // use the user's set language first

  if (!lang) { // if the user has not set their language, negotiate
    const acceptLanguageHeader = headers.get("Accept-Language") ?? "en-US,en;q=0.9";
    console.log(acceptLanguageHeader);
          // ^ "en-US,en;q=0.9"
    const negotiator = new Negotiator({ headers: { "Accept-Language": acceptLanguageHeader } });

    lang = negotiator.language(ALL_LOCALES) ?? "en";
                             // ^ ['cs', 'de', 'en', 'es', 'fil', 'fr', 'sv']
    console.log(lang);
          // ^ will always the first item of the array (cs) no matter what headers were given
  }

Am I doing something wrong?

dougwilson commented 9 months ago

The module expects a Node.js HTTP request object, and as such, the keys in your headers object needs to be all lower case, no upper letters.

dougwilson commented 9 months ago

https://nodejs.org/dist/latest-v21.x/docs/api/http.html#messageheaders

Key-value pairs of header names and values. Header names are lower-cased.

EverlyScott commented 9 months ago

Alright it works now; thank you