-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
78 lines (62 loc) · 2.16 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
import { NextResponse } from 'next/server'
import type { NextRequest } from 'next/server'
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
import { COOKIES } from './constants'
import { i18n, I18nConfig } from './i18n.config'
function getLocale(request: NextRequest, i18nConfig: I18nConfig): string {
const { locales, defaultLocale } = i18nConfig
const negotiatorHeaders: Record<string, string> = {}
request.headers.forEach((value, key) => (negotiatorHeaders[key] = value))
const languages = new Negotiator({ headers: negotiatorHeaders }).languages(
locales
)
return match(languages, locales, defaultLocale)
}
export function middleware(request: NextRequest) {
let response
let nextLocale
const { locales, defaultLocale } = i18n
const pathname = request.nextUrl.pathname
const excludedPaths = [
'/api',
'/_next',
'/public',
'/fonts',
'/images',
'/videos',
'/opengraph-image',
'/favicon.ico'
]
if (excludedPaths.some((path) => pathname.includes(path))) {
return
}
const pathLocale = locales.find(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathLocale) {
const isDefaultLocale = pathLocale === defaultLocale
if (isDefaultLocale) {
let pathWithoutLocale = pathname.slice(`/${pathLocale}`.length) || '/'
if (request.nextUrl.search) pathWithoutLocale += request.nextUrl.search
response = NextResponse.redirect(new URL(pathWithoutLocale, request.url))
}
nextLocale = pathLocale
} else {
const isFirstVisit = !request.cookies.has(COOKIES.locale)
const locale = isFirstVisit ? getLocale(request, i18n) : defaultLocale
let newPath = `/${locale}${pathname}`
if (request.nextUrl.search) newPath += request.nextUrl.search
response =
locale === defaultLocale
? NextResponse.rewrite(new URL(newPath, request.url))
: NextResponse.redirect(new URL(newPath, request.url))
nextLocale = locale
}
if (!response) response = NextResponse.next()
if (nextLocale)
response.cookies.set(COOKIES.locale, nextLocale, {
sameSite: 'strict'
})
return response
}