1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
|
import { CookieNames } from "$lib/configuration";
import { detectLocale, locales } from '$lib/i18n/i18n-util'
import type { Handle, RequestEvent } from '@sveltejs/kit'
import { sequence } from "@sveltejs/kit/hooks";
import { initAcceptLanguageHeaderDetector } from 'typesafe-i18n/detectors'
import { parse, serialize } from "cookie";
import { logDebug } from "$lib/logger";
const handleLocale: Handle = async ({ event, resolve }) => {
const cookies = parse(event.request.headers.get("Cookie") ?? '');
const localeCookie = cookies[CookieNames.locale];
const preferredLocale = getPreferredLocale(event);
let finalLocale = localeCookie ?? preferredLocale;
logDebug("Handling locale", {
locales,
localeCookie,
preferredLocale,
finalLocale
});
if (locales.findIndex((locale) => locale === finalLocale) === -1) finalLocale = "en";
if (!localeCookie) {
// Set a locale cookie
event.setHeaders({
"Set-Cookie": serialize(CookieNames.locale, finalLocale, {
path: "/",
expires: new Date(2099, 1, 1, 0, 0, 0, 0),
sameSite: "strict"
})
});
}
// replace html lang attribute with correct language
return resolve(event, { transformPageChunk: ({ html }) => html.replace('%lang%', finalLocale) });
}
function getPreferredLocale(event: RequestEvent) {
// detect the preferred language the user has configured in it's browser
// https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Language
const headers = transformHeaders(event)
const acceptLanguageDetector = initAcceptLanguageHeaderDetector({ headers })
return detectLocale(acceptLanguageDetector)
}
function transformHeaders({ request }: RequestEvent) {
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => (headers[key] = value))
return headers
}
export const handle = sequence(handleLocale);
|