aboutsummaryrefslogtreecommitdiffstats
path: root/src/routes/+layout.server.ts
blob: 605c013444922994bfe114505ba9948393ef0c1b (plain) (blame)
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
import { auth, get } from "$lib/utils";
import {
	locales,
	loadTranslations,
	translations,
	defaultLocale,
} from "$lib/translations/index";

export let load = async ({ cookies, request, url }) => {
	let { host, pathname } = url;
	let user;
	let token = cookies.get("token");
	if (token) {
		try {
			user = await get("/me", auth(cookies));
		} catch (e) {}
	}

	// Try to get the locale from cookie
	let locale = user?.language || (cookies.get("lang") || "").toLowerCase();

	// Get user preferred locale
	if (!locale) {
		locale = `${`${request.headers.get("accept-language")}`.match(
			/[a-zA-Z]+?(?=-|_|,|;)/,
		)}`.toLowerCase();
	}

	// Get defined locales
	let supportedLocales = locales.get().map((l) => l.toLowerCase());

	// Use default locale if current locale is not supported
	if (!supportedLocales.includes(locale)) {
		locale = defaultLocale;
	}

	await loadTranslations(locale, pathname); // keep this just before the `return`

	return {
		host,
		pathname,
		i18n: { locale, route: pathname },
		user,
		translations: translations.get(),
	};
};