feat(SW-2111): add initial scandic-redirect * feat(SW-2111): add initial scandic-redirect * feat(SW-2112): add scandic-redirect call to middleware * chore: add redirect jsons per lang * fix: handle incorrect contentTypes * fix: handle lang * refactor: add json streaming * refactor: wrap redirect call in cacheOrGet * refactor: review Approved-by: Michael Zetterberg
70 lines
1.7 KiB
TypeScript
70 lines
1.7 KiB
TypeScript
import { type NextMiddleware, NextResponse } from "next/server"
|
|
|
|
import { notFound } from "@/server/errors/next"
|
|
|
|
import { getCacheClient } from "@/services/dataCache"
|
|
import { findLang } from "@/utils/languages"
|
|
|
|
import { getDefaultRequestHeaders } from "./utils"
|
|
|
|
import type { MiddlewareMatcher } from "@/types/middleware"
|
|
import type { Lang } from "@/constants/languages"
|
|
|
|
async function fetchAndCacheRedirect(lang: Lang, pathname: string) {
|
|
const cacheKey = `${lang}:redirect:${pathname}`
|
|
const cache = await getCacheClient()
|
|
|
|
return await cache.cacheOrGet(
|
|
cacheKey,
|
|
async () => {
|
|
const matchedRedirect = await fetch(
|
|
"https://redirect-scandic-hotels.netlify.app",
|
|
{
|
|
method: "POST",
|
|
body: JSON.stringify({ lang, pathname }),
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
}
|
|
)
|
|
|
|
if (matchedRedirect.ok) {
|
|
const result = await matchedRedirect.text()
|
|
|
|
if (result) {
|
|
return result
|
|
}
|
|
}
|
|
return null
|
|
},
|
|
// longer once tested
|
|
"1m"
|
|
)
|
|
}
|
|
|
|
export const middleware: NextMiddleware = async (request) => {
|
|
const lang = findLang(request.nextUrl.pathname)!
|
|
const headers = getDefaultRequestHeaders(request)
|
|
try {
|
|
const matchedRedirect = await fetchAndCacheRedirect(
|
|
lang,
|
|
request.nextUrl.pathname
|
|
)
|
|
|
|
if (matchedRedirect) {
|
|
const newUrl = new URL(matchedRedirect, request.nextUrl)
|
|
headers.set("Cache-control", "public, max-age=60")
|
|
return NextResponse.redirect(newUrl, {
|
|
headers,
|
|
})
|
|
}
|
|
} catch (e) {
|
|
console.error("Redirect error: ", e)
|
|
throw notFound()
|
|
}
|
|
}
|
|
|
|
export const matcher: MiddlewareMatcher = (_) => {
|
|
return true
|
|
}
|