81 lines
2.1 KiB
TypeScript
81 lines
2.1 KiB
TypeScript
import { NextResponse } from "next/server"
|
|
|
|
import { findLang } from "@/constants/languages"
|
|
import { notFound } from "@/server/errors/next"
|
|
|
|
import { resolve as resolveEntry } from "@/utils/entry"
|
|
|
|
import type { NextMiddleware } from "next/server"
|
|
|
|
import { MiddlewareMatcher } from "@/types/middleware"
|
|
|
|
export const middleware: NextMiddleware = async (request) => {
|
|
const { nextUrl } = request
|
|
const lang = findLang(nextUrl.pathname)
|
|
|
|
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}`, "")
|
|
const searchParams = new URLSearchParams(request.nextUrl.searchParams)
|
|
|
|
const { contentType, uid } = await resolveEntry(pathNameWithoutLang, lang)
|
|
|
|
if (!contentType || !uid) {
|
|
throw notFound()
|
|
}
|
|
|
|
const isCurrent = contentType ? contentType.indexOf("current") >= 0 : false
|
|
|
|
if (request.nextUrl.pathname.includes("/preview")) {
|
|
if (isCurrent) {
|
|
searchParams.set("uri", pathNameWithoutLang.replace("/preview", ""))
|
|
return NextResponse.rewrite(
|
|
new URL(`/${lang}/preview-current?${searchParams.toString()}`, nextUrl)
|
|
)
|
|
}
|
|
|
|
return NextResponse.rewrite(
|
|
new URL(
|
|
`/${lang}/preview/${contentType}/${uid}?${searchParams.toString()}`,
|
|
nextUrl
|
|
),
|
|
{
|
|
request: {
|
|
headers: new Headers({
|
|
"x-uid": uid,
|
|
}),
|
|
},
|
|
}
|
|
)
|
|
}
|
|
|
|
if (isCurrent) {
|
|
return NextResponse.rewrite(
|
|
new URL(
|
|
`/${lang}/current-content-page?${searchParams.toString()}`,
|
|
nextUrl
|
|
)
|
|
)
|
|
}
|
|
|
|
return NextResponse.rewrite(
|
|
new URL(
|
|
`/${lang}/${contentType}/${uid}?${searchParams.toString()}`,
|
|
nextUrl
|
|
),
|
|
{
|
|
request: {
|
|
headers: new Headers({
|
|
"x-uid": uid,
|
|
}),
|
|
},
|
|
}
|
|
)
|
|
}
|
|
|
|
export const matcher: MiddlewareMatcher = (request) => {
|
|
// Do not process paths with file extension.
|
|
// Only looking for dot might be too brute force/give false positives.
|
|
// It works right now but adjust accordingly when new use cases/data emerges.
|
|
const lastPathnameSegment = request.nextUrl.pathname.split("/").pop()
|
|
return lastPathnameSegment?.indexOf(".") === -1
|
|
}
|