-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmiddleware.ts
More file actions
51 lines (44 loc) · 1.3 KB
/
Copy pathmiddleware.ts
File metadata and controls
51 lines (44 loc) · 1.3 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
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import {
LANGUAGE_COOKIE_KEY,
LEGACY_LANGUAGE_COOKIE_KEY,
isSupportedLanguage,
} from '@/lib/i18n/language-cookie';
export function middleware(request: NextRequest) {
const response = NextResponse.next();
const current = request.cookies.get(LANGUAGE_COOKIE_KEY)?.value;
const legacy = request.cookies.get(LEGACY_LANGUAGE_COOKIE_KEY)?.value;
const existing = isSupportedLanguage(current)
? current
: isSupportedLanguage(legacy)
? legacy
: undefined;
if (existing) {
if (!isSupportedLanguage(current) && isSupportedLanguage(legacy)) {
response.cookies.set(LANGUAGE_COOKIE_KEY, legacy, {
path: '/',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'lax',
});
}
return response;
}
const acceptLanguage = request.headers
.get('accept-language')
?.split(',')[0]
?.split('-')[0];
const detected =
acceptLanguage && isSupportedLanguage(acceptLanguage)
? acceptLanguage
: 'en';
response.cookies.set(LANGUAGE_COOKIE_KEY, detected, {
path: '/',
maxAge: 60 * 60 * 24 * 365,
sameSite: 'lax',
});
return response;
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico|.*\\..*).*)'],
};