Files
web/apps/scandic-web/middlewares/myPages.ts
Joakim Jäderberg daf765f3d5 Merged in feature/wrap-logging (pull request #2511)
Feature/wrap logging

* feat: change all logging to go through our own logger function so that we can control log levels

* move packages/trpc to using our own logger

* merge


Approved-by: Linus Flood
2025-07-03 12:37:04 +00:00

82 lines
2.3 KiB
TypeScript

import { type NextMiddleware, NextResponse } from "next/server"
import {
myPages,
overview,
profile,
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)
// Handle profile and profile edit routes, which are not CMS entries
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,
},
}
)
}
return NextResponse.next({
request: {
headers,
},
})
}
export const matcher: MiddlewareMatcher = (request) => {
const lang = findLang(request.nextUrl.pathname)!
return request.nextUrl.pathname.startsWith(myPages[lang])
}