2023-10-23 23:11:59 +02:00
|
|
|
import { NextResponse } from "next/server"
|
|
|
|
import type { NextRequest } from "next/server"
|
|
|
|
import { match } from "@formatjs/intl-localematcher"
|
|
|
|
import Negotiator from "negotiator"
|
2023-07-31 19:06:46 +02:00
|
|
|
|
2023-10-23 23:11:59 +02:00
|
|
|
import type { Locale, Theme } from "@/utils/constants"
|
2023-07-31 19:06:46 +02:00
|
|
|
import {
|
|
|
|
COOKIE_MAX_AGE,
|
|
|
|
DEFAULT_LOCALE,
|
2023-08-01 14:11:46 +02:00
|
|
|
DEFAULT_THEME,
|
|
|
|
LOCALES,
|
2023-10-23 23:11:59 +02:00
|
|
|
THEMES,
|
|
|
|
} from "@/utils/constants"
|
2023-07-31 19:06:46 +02:00
|
|
|
|
|
|
|
export const middleware = (request: NextRequest): NextResponse => {
|
|
|
|
const response = NextResponse.next()
|
|
|
|
|
2023-10-23 23:11:59 +02:00
|
|
|
let locale = request.cookies.get("locale")?.value
|
2023-08-01 14:11:46 +02:00
|
|
|
if (locale == null || !LOCALES.includes(locale as Locale)) {
|
2023-08-24 23:09:33 +02:00
|
|
|
try {
|
|
|
|
const headers = {
|
2023-10-23 23:11:59 +02:00
|
|
|
"accept-language":
|
|
|
|
request.headers.get("accept-language") ?? DEFAULT_LOCALE,
|
2023-08-24 23:09:33 +02:00
|
|
|
}
|
|
|
|
const languages = new Negotiator({ headers }).languages()
|
|
|
|
locale = match(languages, LOCALES.slice(), DEFAULT_LOCALE)
|
|
|
|
} catch {
|
|
|
|
locale = DEFAULT_LOCALE
|
2023-07-31 19:06:46 +02:00
|
|
|
}
|
2023-10-23 23:11:59 +02:00
|
|
|
response.cookies.set("locale", locale, {
|
|
|
|
path: "/",
|
|
|
|
maxAge: COOKIE_MAX_AGE,
|
2023-07-31 19:06:46 +02:00
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-10-23 23:11:59 +02:00
|
|
|
const theme = request.cookies.get("theme")?.value
|
2023-08-01 14:11:46 +02:00
|
|
|
if (theme == null || !THEMES.includes(theme as Theme)) {
|
2023-10-23 23:11:59 +02:00
|
|
|
response.cookies.set("theme", DEFAULT_THEME, {
|
|
|
|
path: "/",
|
|
|
|
maxAge: COOKIE_MAX_AGE,
|
2023-08-01 14:11:46 +02:00
|
|
|
})
|
|
|
|
}
|
2023-07-31 19:06:46 +02:00
|
|
|
|
|
|
|
return response
|
|
|
|
}
|
|
|
|
|
|
|
|
export const config = {
|
|
|
|
matcher: [
|
|
|
|
/*
|
|
|
|
* Match all request paths except for the ones starting with:
|
|
|
|
* - api (API routes)
|
|
|
|
* - _next/static (static files)
|
|
|
|
* - _next/image (image optimization files)
|
|
|
|
* - favicon.ico (favicon file)
|
|
|
|
*/
|
2023-10-23 23:11:59 +02:00
|
|
|
"/((?!api|_next/static|_next/image|favicon.ico).*)",
|
|
|
|
],
|
2023-07-31 19:06:46 +02:00
|
|
|
}
|