-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathproxy.ts
More file actions
45 lines (37 loc) · 1.87 KB
/
proxy.ts
File metadata and controls
45 lines (37 loc) · 1.87 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
import { NextRequest, NextResponse } from "next/server"
import acceptLanguage from "accept-language"
import { fallbackLng, languages, cookieName, headerName } from "@/app/i18n/settings"
acceptLanguage.languages(languages)
export const config = {
// Avoid matching for static files, API routes, etc.
matcher: ["/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js|site.webmanifest).*)"],
}
export function proxy(req: NextRequest) {
// Ignore paths with "icon" or "chrome"
if (req.nextUrl.pathname.indexOf("icon") > -1 || req.nextUrl.pathname.indexOf("chrome") > -1)
return NextResponse.next()
let lng
// Try to get language from cookie
if (req.cookies.has(cookieName)) lng = acceptLanguage.get(req.cookies.get(cookieName)?.value)
// If no cookie, check the Accept-Language header
if (!lng) lng = acceptLanguage.get(req.headers.get("Accept-Language"))
// Default to fallback language if still undefined
if (!lng) lng = fallbackLng
// Check if the language is already in the path
const lngInPath = languages.find((loc) => req.nextUrl.pathname.startsWith(`/${loc}`))
const headers = new Headers(req.headers)
headers.set(headerName, lngInPath || lng)
// If the language is not in the path, redirect to include it
if (!lngInPath && !req.nextUrl.pathname.startsWith("/_next")) {
return NextResponse.redirect(new URL(`/${lng}${req.nextUrl.pathname}${req.nextUrl.search}`, req.url))
}
// If a referer exists, try to detect the language from there and set the cookie accordingly
if (req.headers.has("referer")) {
const refererUrl = new URL(req.headers.get("referer") || "", req.url)
const lngInReferer = languages.find((l) => refererUrl.pathname.startsWith(`/${l}`))
const response = NextResponse.next({ headers })
if (lngInReferer) response.cookies.set(cookieName, lngInReferer)
return response
}
return NextResponse.next({ headers })
}