-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
58 lines (46 loc) · 1.71 KB
/
Copy pathproxy.ts
File metadata and controls
58 lines (46 loc) · 1.71 KB
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
import { NextRequest, NextResponse } from 'next/server';
import { match } from '@formatjs/intl-localematcher';
import Negotiator from 'negotiator';
import { i18n } from './src/components/internationalization/config';
// Matcher config for proxy
export const config = {
matcher: ['/((?!api|_next|_static|favicon.ico|.*\\.[a-zA-Z0-9]+$).*)'],
};
function getLocale(request: NextRequest) {
// 1. Check cookie first for user preference
const cookieLocale = request.cookies.get('NEXT_LOCALE')?.value;
if (cookieLocale && i18n.locales.includes(cookieLocale as any)) {
return cookieLocale;
}
// 2. Get Accept-Language header
const headers = {
'accept-language': request.headers.get('accept-language') ?? '',
};
// Use negotiator to parse preferred languages
const languages = new Negotiator({ headers }).languages();
// Match against supported locales
return match(languages, i18n.locales, i18n.defaultLocale);
}
export function proxy(request: NextRequest) {
const { pathname } = request.nextUrl;
// Check if pathname already has a locale
const pathnameHasLocale = i18n.locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
);
// If locale exists in URL, continue
if (pathnameHasLocale) {
return NextResponse.next();
}
// Get best matching locale
const locale = getLocale(request);
// Redirect to localized URL
request.nextUrl.pathname = `/${locale}${pathname}`;
const response = NextResponse.redirect(request.nextUrl);
// Set cookie for future visits
response.cookies.set('NEXT_LOCALE', locale, {
maxAge: 365 * 24 * 60 * 60, // 1 year
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
});
return response;
}