-
-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathmiddleware.ts
More file actions
47 lines (37 loc) · 1.33 KB
/
Copy pathmiddleware.ts
File metadata and controls
47 lines (37 loc) · 1.33 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
// file: middleware.ts
import { NextRequest, NextResponse } from 'next/server'
import { match } from '@formatjs/intl-localematcher'
import Negotiator from 'negotiator'
const supportedLocales = ['en', 'zh', 'ja']
const defaultLocale = 'zh'
function getLocale(request: NextRequest): string {
const localeCookie = request.cookies.get('NEXT_LOCALE')?.value
if (localeCookie && supportedLocales.includes(localeCookie)) {
return localeCookie
}
const headers: Record<string, string> = {}
request.headers.forEach((value, key) => (headers[key] = value))
const languages = new Negotiator({ headers }).languages()
try {
return match(languages, supportedLocales, defaultLocale)
} catch (e) {
return defaultLocale
}
}
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const pathnameHasLocale = supportedLocales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) {
return
}
const locale = getLocale(request)
request.nextUrl.pathname = `/${locale}${pathname}`
return NextResponse.redirect(request.nextUrl)
}
export const config = {
matcher: [
'/((?!api|_next/static|_next/image|_next|_proxy|auth/callback|_auth|static|assets|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp|ico|json|xml|txt|webmanifest)).*)',
],
}