-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware.ts
38 lines (33 loc) · 1.15 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
import { NextRequest, NextResponse } from 'next/server'
import Negotiator from 'negotiator'
import { defaultLanguage, availableLanguages } from './i18n/settings'
const getNegotiatedLanguage = (
headers: Negotiator.Headers,
): string | undefined => {
return new Negotiator({ headers }).language([...availableLanguages])
}
export const config = {
matcher: ['/((?!api|_next/static|_next/image|.*\\.png$).*)'],
}
export function middleware(request: NextRequest) {
const headers = {
'accept-language': request.headers.get('accept-language') ?? '',
}
const preferredLanguage = getNegotiatedLanguage(headers) || defaultLanguage
const pathname = request.nextUrl.pathname
const pathnameIsMissingLocale = availableLanguages.every(
(lang) => !pathname.startsWith(`/${lang}/`) && pathname !== `/${lang}`,
)
if (pathnameIsMissingLocale) {
if (preferredLanguage !== defaultLanguage) {
return NextResponse.redirect(
new URL(`/${preferredLanguage}${pathname}`, request.url),
)
} else {
return NextResponse.rewrite(
new URL(`/${defaultLanguage}${pathname}`, request.url),
)
}
}
return NextResponse.next()
}