-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmiddleware.ts
48 lines (45 loc) · 1.07 KB
/
middleware.ts
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
import { als } from "virtual:astro-i18n/als";
import { i18nextConfig, options, routes } from "virtual:astro-i18n/internal";
import { defineMiddleware } from "astro/middleware";
const extractLocaleFromUrl = (pathname: string) => {
for (const locale of options.locales) {
if (options.strategy === "prefix") {
if (pathname.startsWith(`/${locale}/`)) {
return locale;
}
} else if (options.strategy === "prefixExceptDefault") {
if (
locale !== options.defaultLocale &&
pathname.startsWith(`/${locale}`)
) {
return locale;
}
}
}
return options.defaultLocale;
};
export const onRequest = defineMiddleware((context, next) => {
const pathname = context.url.pathname;
const locale = extractLocaleFromUrl(pathname);
return als.run(
{
clientOptions: options.client,
translations: {
initialized: false,
i18nextConfig,
},
data: {
locale,
locales: options.locales,
defaultLocale: options.defaultLocale,
},
paths: {
pathname,
routes,
dynamicParams: {},
strategy: options.strategy,
},
},
next,
);
});