-
-
Save odensc/216288159aaa2cb41fc924774fce5859 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import langParser from "accept-language-parser"; | |
import { parse } from "cookie"; | |
import { IncomingMessage } from "http"; | |
import i18next from "i18next"; | |
import languageList from "@translations/languages"; | |
/** | |
* Copied util from i18next but with a few modifications: | |
* * It takes a custom i18n instance. | |
* * It's async so the namespaces can be loaded. | |
* * It only returns one language. | |
*/ | |
export const getInitialProps = async (i18n: i18next.i18n) => { | |
const namespaces: string[] = (i18n as any).reportNamespaces | |
? (i18n as any).reportNamespaces.getUsedNamespaces() | |
: []; | |
await i18n.loadNamespaces(namespaces); | |
const initialI18nStore: any = { [i18n.language]: {} }; | |
namespaces.forEach(ns => { | |
initialI18nStore[i18n.language][ns] = | |
i18n.getResourceBundle(i18n.language, ns) || {}; | |
}); | |
return { initialI18nStore, initialLanguage: i18n.language }; | |
}; | |
/** | |
* Determine a user's preferred language via (in order, highest to lowest weight): | |
* * `language` cookie. | |
* * Highest weight lang in Accept-Language header. | |
*/ | |
export const getPreferredLanguage = (req: IncomingMessage) => { | |
const acceptedLang = langParser.pick( | |
languageList, | |
req.headers["accept-language"] || "", | |
{ | |
loose: true | |
} | |
); | |
const cookieLang = parse(req.headers.cookie || "").language; | |
return cookieLang || acceptedLang || "en"; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
is there a
@translations/languages
package that I am not aware of, I can't find it on npm, would I find it in mynode_modules
?