-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathmiddleware.ts
82 lines (68 loc) · 2.24 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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
import getAvailableLocales from '@/app/i18n/settings';
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
import { type NextRequest, NextResponse } from 'next/server';
import type { SiteLocale } from './graphql/types/graphql';
import {
type GlobalPageProps,
buildUrl as buildUrlForPage,
} from './utils/globalPageProps';
async function findBestLocaleForVisitor(
request: Request,
locales: SiteLocale[],
): Promise<SiteLocale> {
const headers = new Headers(request.headers);
const acceptLanguage = headers.get('accept-language');
if (acceptLanguage) {
headers.set('accept-language', acceptLanguage.replaceAll('_', '-'));
}
const headersObject = Object.fromEntries(headers.entries());
const languages = new Negotiator({ headers: headersObject }).languages();
const reformattedLocales = locales.map((locale) =>
locale.replaceAll('_', '-'),
);
const detectedLocale = match(
languages,
reformattedLocales,
reformattedLocales[0],
);
const detectedLocaleAsSiteLocale = detectedLocale.replaceAll(
'-',
'_',
) as SiteLocale;
return detectedLocaleAsSiteLocale;
}
function buildUrl(locale: SiteLocale, path: string) {
const simulatedPageProps: GlobalPageProps = {
params: {
locale,
},
};
return buildUrlForPage(simulatedPageProps, path);
}
export async function middleware(request: NextRequest) {
const { pathname } = request.nextUrl;
const locales = await getAvailableLocales();
const localeInPathname = locales.find((locale) =>
pathname.match(new RegExp(`^/${locale}($|/)`)),
);
const normalizedLocale =
localeInPathname || (await findBestLocaleForVisitor(request, locales));
const pathnameWithoutLocale = localeInPathname
? pathname.replace(new RegExp(`^/${localeInPathname}`), '')
: pathname;
const normalizedPathnameWithoutLocale =
pathnameWithoutLocale && pathnameWithoutLocale !== '/'
? pathnameWithoutLocale
: '/home';
const normalizedPathname = buildUrl(
normalizedLocale,
normalizedPathnameWithoutLocale,
);
if (pathname !== normalizedPathname) {
return NextResponse.redirect(new URL(normalizedPathname, request.url));
}
}
export const config = {
matcher: ['/((?!.*\\.|_next|api\\/).*)'],
};