Skip to content

Instantly share code, notes, and snippets.

@odensc

odensc/util.ts Secret

Last active July 3, 2022 18:12
Show Gist options
  • Save odensc/216288159aaa2cb41fc924774fce5859 to your computer and use it in GitHub Desktop.
Save odensc/216288159aaa2cb41fc924774fce5859 to your computer and use it in GitHub Desktop.
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";
};
@abdessamad-zgor
Copy link

abdessamad-zgor commented Jul 3, 2022

is there a @translations/languages package that I am not aware of, I can't find it on npm, would I find it in my node_modules ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment