-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathmiddleware.ts
More file actions
129 lines (108 loc) · 3.53 KB
/
Copy pathmiddleware.ts
File metadata and controls
129 lines (108 loc) · 3.53 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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
// middleware.ts
import { DEFAULT_LOCALE, LOCALES } from '@/lib/optimizely/utils/language'
import { createUrl, leadingSlashUrlPath } from '@/lib/utils'
import type { NextRequest } from 'next/server'
import { NextResponse } from 'next/server'
import Negotiator from 'negotiator'
const COOKIE_NAME_LOCALE = '__LOCALE_NAME'
const HEADER_KEY_LOCALE = 'X-Locale'
function shouldExclude(path: string) {
return (
path.startsWith('/static') || path.includes('/api/') || path.includes('.')
)
}
function getBrowserLanguage(
request: NextRequest,
locales: string[]
): string | undefined {
const headerLanguage = request.headers.get('Accept-Language')
if (!headerLanguage) {
return undefined
}
// Create a negotiator instance with the Accept-Language header
const languages = new Negotiator({
headers: { 'accept-language': headerLanguage },
}).languages()
// Find the first language that matches our supported locales
for (const lang of languages) {
// Check for exact match
if (locales.includes(lang)) {
return lang
}
// Check for language match without region (e.g., 'pl-PL' should match 'pl')
const langPrefix = lang.split('-')[0]
if (locales.includes(langPrefix)) {
return langPrefix
}
}
return undefined
}
function getLocale(request: NextRequest, locales: string[]): string {
// First check if there's a locale cookie
const cookieLocale = request.cookies.get(COOKIE_NAME_LOCALE)?.value
if (cookieLocale && locales.includes(cookieLocale)) {
return cookieLocale
}
// If no cookie, try to use browser language
const browserLang = getBrowserLanguage(request, locales)
if (browserLang && locales.includes(browserLang)) {
return browserLang
}
// Fall back to default locale
return DEFAULT_LOCALE
}
function updateLocaleCookies(
request: NextRequest,
response: NextResponse,
locale?: string
): void {
const cookieLocale = request.cookies.get(COOKIE_NAME_LOCALE)?.value
const newLocale = locale || null
if (newLocale !== cookieLocale) {
if (newLocale) {
response.cookies.set(COOKIE_NAME_LOCALE, newLocale)
} else {
response.cookies.delete(COOKIE_NAME_LOCALE)
}
}
if (newLocale) {
response.headers.append(HEADER_KEY_LOCALE, newLocale)
} else {
response.headers.delete(HEADER_KEY_LOCALE)
}
}
export async function middleware(request: NextRequest) {
const pathname = request.nextUrl.pathname
let response = NextResponse.next()
if (shouldExclude(pathname)) {
return response
}
const localeInPathname = LOCALES.find(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (localeInPathname) {
const pathnameWithoutLocale = pathname.replace(`/${localeInPathname}`, '')
const newUrl = createUrl(
`/${localeInPathname}${leadingSlashUrlPath(pathnameWithoutLocale)}`,
request.nextUrl.searchParams
)
response = NextResponse.rewrite(new URL(newUrl, request.url))
updateLocaleCookies(request, response, localeInPathname)
return response
}
// Get locale with browser language preference
const locale = getLocale(request, LOCALES)
const newUrl = createUrl(
`/${locale}${leadingSlashUrlPath(pathname)}`,
request.nextUrl.searchParams
)
response =
locale === DEFAULT_LOCALE
? NextResponse.rewrite(new URL(newUrl, request.url))
: NextResponse.redirect(new URL(newUrl, request.url))
updateLocaleCookies(request, response, locale)
return response
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|favicon.ico).*)'],
}