forked from privacy-scaling-explorations/pse.dev
-
Notifications
You must be signed in to change notification settings - Fork 0
/
middleware.ts
48 lines (40 loc) · 1.39 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
import { NextResponse } from "next/server"
import acceptLanguage from "accept-language"
import { cookieName, fallbackLng, languages } from "./app/i18n/settings"
acceptLanguage.languages(languages as any)
export const config = {
//matcher: "/:lang*",
matcher: ["/((?!api|_next/static|_next/image|assets|favicon.ico|sw.js).*)"],
}
const PUBLIC_FILE = /\.(.*)$/
export function middleware(req: any) {
const COOKIE_NAME = cookieName ?? "i18next"
let lang
if (req.cookies.has(COOKIE_NAME))
lang = acceptLanguage.get(req.cookies.get(COOKIE_NAME).value)
if (!lang) lang = acceptLanguage.get(req.headers.get("Accept-Language"))
if (!lang) lang = fallbackLng
// Keep the file from public folder
if (PUBLIC_FILE.test(req.nextUrl.pathname)) {
return
}
// Redirect if lang in path is not supported
if (
!languages.some((loc) => req.nextUrl.pathname.startsWith(`/${loc}`)) &&
!req.nextUrl.pathname.startsWith("/_next")
) {
return NextResponse.redirect(
new URL(`/${lang}${req.nextUrl.pathname}`, req.url)
)
}
if (req.headers.has("referer")) {
const refererUrl = new URL(req.headers.get("referer"))
const langInReferer = languages.find((l) =>
refererUrl.pathname.startsWith(`/${l}`)
)
const response = NextResponse.next()
if (langInReferer) response.cookies.set(COOKIE_NAME, langInReferer)
return response
}
return NextResponse.next()
}