diff --git a/lib/core/i18n/i18n.utils.ts b/lib/core/i18n/i18n.utils.ts index fc645a5dd0..c9c9763321 100644 --- a/lib/core/i18n/i18n.utils.ts +++ b/lib/core/i18n/i18n.utils.ts @@ -1,3 +1,4 @@ +import { Maybe } from "@trpc/server"; import parser from "accept-language-parser"; import { IncomingMessage } from "http"; @@ -6,9 +7,15 @@ import prisma from "@lib/prisma"; import { i18n } from "../../../next-i18next.config"; -export const getOrSetUserLocaleFromHeaders = async (req: IncomingMessage) => { +export function getLocaleFromHeaders(req: IncomingMessage): string { + const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe; + + return preferredLocale ?? i18n.defaultLocale; +} + +export const getOrSetUserLocaleFromHeaders = async (req: IncomingMessage): Promise => { const session = await getSession({ req }); - const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]); + const preferredLocale = parser.pick(i18n.locales, req.headers["accept-language"]) as Maybe; if (session?.user?.id) { const user = await prisma.user.findUnique({ diff --git a/server/createContext.ts b/server/createContext.ts index 44c526d65c..80e352706e 100644 --- a/server/createContext.ts +++ b/server/createContext.ts @@ -2,12 +2,14 @@ import * as trpc from "@trpc/server"; import { Maybe } from "@trpc/server"; import * as trpcNext from "@trpc/server/adapters/next"; +import { NextApiRequest } from "next"; import { getSession, Session } from "@lib/auth"; +import { getLocaleFromHeaders } from "@lib/core/i18n/i18n.utils"; import prisma from "@lib/prisma"; import { defaultAvatarSrc } from "@lib/profile"; -async function getUserFromSession(session: Maybe) { +async function getUserFromSession({ session, req }: { session: Maybe; req: NextApiRequest }) { if (!session?.user?.id) { return null; } @@ -30,6 +32,7 @@ async function getUserFromSession(session: Maybe) { createdDate: true, hideBranding: true, avatar: true, + locale: true, }, }); @@ -42,11 +45,14 @@ async function getUserFromSession(session: Maybe) { return null; } const avatar = user.avatar || defaultAvatarSrc({ email }); + + const locale = user.locale ?? getLocaleFromHeaders(req); return { ...user, avatar, email, username, + locale, }; } @@ -58,10 +64,13 @@ export const createContext = async ({ req, res }: trpcNext.CreateNextContextOpti // for API-response caching see https://trpc.io/docs/caching const session = await getSession({ req }); + const user = await getUserFromSession({ session, req }); + const locale = user?.locale ?? getLocaleFromHeaders(req); return { prisma, session, - user: await getUserFromSession(session), + user, + locale, }; };