-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
51 lines (44 loc) · 1.62 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
import { defaultLocale, localeCookie, locales } from '@/app/i18n/settings'
import acceptLanguage from 'accept-language'
import { type NextRequest, NextResponse } from 'next/server'
acceptLanguage.languages(locales.map((locale) => locale))
export const middleware = (req: NextRequest) => {
const cookie = req.cookies.get(localeCookie)
const header = req.headers.get('Accept-Language')
const lang =
// Get preferred language from cookie
(cookie && acceptLanguage.get(cookie.value)) ??
// Otherwise from header
acceptLanguage.get(header ?? `${defaultLocale}`) ??
defaultLocale
// Redirect if the path does not start with a supported locale
const path = req.nextUrl.pathname
if (
!locales.some(
(locale) => path.startsWith(`/${locale}/`) || path === `/${locale}`
) &&
!path.startsWith('/api')
) {
return NextResponse.redirect(new URL(`/${lang}${path}`, req.url))
}
// Set the language cookie based on the referer (sent during language switch)
const referer = req.headers.get('referer')
if (referer) {
const refererUrl = new URL(referer)
const localeInReferer = locales.find(
(locale) =>
refererUrl.pathname.startsWith(`/${locale}/`) ||
refererUrl.pathname === `/${locale}`
)
const response = NextResponse.next()
if (localeInReferer) response.cookies.set(localeCookie, localeInReferer)
return response
}
return NextResponse.next()
}
export const config = {
matcher: [
'/((?!api|_next|images).*)',
// '/'
],
}