Fix/LOY-483: Fix My Pages working in all languages * fix(LOY-483): add back specific handling of profile pages * fix(LOY-483): remove limit of 1 profiling consent config Approved-by: Chuma Mcphoy (We Ahead)
92 lines
2.5 KiB
TypeScript
92 lines
2.5 KiB
TypeScript
import { type NextMiddleware, NextResponse } from "next/server"
|
|
|
|
import {
|
|
myPages,
|
|
overview,
|
|
profile,
|
|
profileConsent,
|
|
profileEdit,
|
|
} from "@scandic-hotels/common/constants/routes/myPages"
|
|
import { logger } from "@scandic-hotels/common/logger"
|
|
import { findLang } from "@scandic-hotels/common/utils/languages"
|
|
import { resolve as resolveEntry } from "@scandic-hotels/trpc/utils/entry"
|
|
|
|
import { internalServerError, notFound } from "@/server/errors/next"
|
|
import { getPublicNextURL } from "@/server/utils"
|
|
|
|
import { getDefaultRequestHeaders } from "./utils"
|
|
|
|
import type { MiddlewareMatcher } from "@/types/middleware"
|
|
|
|
export const middleware: NextMiddleware = async (request) => {
|
|
const { nextUrl } = request
|
|
const lang = findLang(nextUrl.pathname)!
|
|
|
|
const myPagesRoot = myPages[lang]
|
|
if (nextUrl.pathname === myPagesRoot) {
|
|
const nextUrlPublic = getPublicNextURL(request)
|
|
const overviewUrl = overview[lang]
|
|
const redirectUrl = new URL(overviewUrl, nextUrlPublic)
|
|
logger.debug(`[myPages] redirecting to: ${redirectUrl}`)
|
|
return NextResponse.redirect(redirectUrl, {
|
|
status: 308,
|
|
})
|
|
}
|
|
|
|
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}`, "")
|
|
const { uid, contentType, error } = await resolveEntry(
|
|
pathNameWithoutLang,
|
|
lang
|
|
)
|
|
|
|
if (error) {
|
|
throw internalServerError(error)
|
|
}
|
|
if (!uid || !contentType) {
|
|
throw notFound(
|
|
`Unable to resolve CMS entry for locale "${lang}": ${pathNameWithoutLang}`
|
|
)
|
|
}
|
|
|
|
const headers = getDefaultRequestHeaders(request)
|
|
headers.set("x-uid", uid)
|
|
headers.set("x-contenttype", contentType)
|
|
|
|
if (profile[lang].startsWith(nextUrl.pathname)) {
|
|
return NextResponse.rewrite(new URL(`/${lang}/my-pages/profile`, nextUrl), {
|
|
request: {
|
|
headers,
|
|
},
|
|
})
|
|
} else if (profileEdit[lang].startsWith(nextUrl.pathname)) {
|
|
return NextResponse.rewrite(
|
|
new URL(`/${lang}/my-pages/profile/edit`, nextUrl),
|
|
{
|
|
request: {
|
|
headers,
|
|
},
|
|
}
|
|
)
|
|
} else if (profileConsent[lang].startsWith(nextUrl.pathname)) {
|
|
return NextResponse.rewrite(
|
|
new URL(`/${lang}/my-pages/profile/consent`, nextUrl),
|
|
{
|
|
request: {
|
|
headers,
|
|
},
|
|
}
|
|
)
|
|
}
|
|
|
|
return NextResponse.next({
|
|
request: {
|
|
headers,
|
|
},
|
|
})
|
|
}
|
|
|
|
export const matcher: MiddlewareMatcher = (request) => {
|
|
const lang = findLang(request.nextUrl.pathname)!
|
|
return request.nextUrl.pathname.startsWith(myPages[lang])
|
|
}
|