Files
web/i18n/serverContext.ts
Joakim Jäderberg 873183ec2f * move setLang() to a root layout
* fix: findLang only returns acceptable languages
* fix: fallback to use header x-lang if we haven't setLang yet
* fix: languageSchema, allow uppercase

Approved-by: Linus Flood
2025-02-19 09:06:37 +00:00

35 lines
844 B
TypeScript

import "server-only"
import { headers } from "next/headers"
import { cache } from "react"
import { Lang } from "@/constants/languages"
import { languageSchema } from "@/utils/languages"
const getRef = cache(() => ({ current: undefined as Lang | undefined }))
/**
* Set the language for the current request
*
* It works kind of like React's context,
* but on the server side, per request.
*
* @param newLang
*/
export function setLang(newLang: Lang) {
const parseResult = languageSchema.safeParse(newLang)
getRef().current = parseResult.success ? parseResult.data : Lang.en
}
/**
* Get the global language set for the current request
*/
export function getLang(): Lang {
const contextLang = getRef().current
const headerLang = headers().get("x-lang") as Lang
const l = contextLang || headerLang || Lang.en
return l
}