Files
web/middlewares/myPages.ts
Michael Zetterberg 4a846540c3 feat: improve handling of deployment env vars
These are now defined in Netlify UI for dedicated environments (test, stage, production):

AUTH_URL
NEXTAUTH_URL
PUBLIC_URL

Code now falls back to incoming request host. Mainly used for
deployment previews which do not have Akamai in front, meaning
we do not need the above workaround as incoming request host
matches the actual public facing host. When Akamai is in front,
we lose the public facing host in Netlify's routing layer as they
internally use `x-forwarded-for` and we can't claim it for our usage.
2024-10-15 17:03:36 +02:00

78 lines
2.1 KiB
TypeScript

import { NextResponse } from "next/server"
import {
myPages,
overview,
profile,
profileEdit,
} from "@/constants/routes/myPages"
import { env } from "@/env/server"
import { internalServerError, notFound } from "@/server/errors/next"
import { getPublicNextURL } from "@/server/utils"
import { findLang } from "@/utils/languages"
import { fetchAndCacheEntry, getDefaultRequestHeaders } from "./utils"
import type { NextMiddleware } from "next/server"
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)
console.log(`[myPages] redirecting to: ${redirectUrl}`)
return NextResponse.redirect(redirectUrl)
}
const pathNameWithoutLang = nextUrl.pathname.replace(`/${lang}`, "")
const { uid, contentType } = await fetchAndCacheEntry(
pathNameWithoutLang,
lang
)
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])
}