-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
52 lines (42 loc) · 1.53 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
/*
* For more info see
* https://nextjs.org/docs/app/building-your-application/routing/internationalization
* */
import { type NextRequest, NextResponse } from 'next/server'
import Negotiator from 'negotiator'
import linguiConfig from '@/lingui.config'
const { locales } = linguiConfig
export function middleware(request: NextRequest) {
const { pathname } = request.nextUrl
const pathnameHasLocale = locales.some(
(locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
)
if (pathnameHasLocale) return
// Redirect if there is no locale
const locale = getRequestLocale(request.headers)
request.nextUrl.pathname = `/${locale}${pathname}`
// e.g. incoming request is /products
// The new URL is now /en/products
return NextResponse.redirect(request.nextUrl)
}
function getRequestLocale(requestHeaders: Headers): string {
const langHeader = requestHeaders.get('accept-language') || undefined
const languages = new Negotiator({
headers: { 'accept-language': langHeader }
}).languages(locales.slice())
const activeLocale = languages[0] || locales[0] || 'en'
return activeLocale
}
export const config = {
matcher: [
/*
* Match all request paths except:
* - _next/static (static files)
* - _next/image (image optimization files)
* - favicon.ico (favicon file)
* - images - .svg, .png, .jpg, .jpeg, .gif, .webp
* Feel free to modify this pattern to include more paths.
*/
'/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)'
]
}