feat: Add common package * Add isEdge, safeTry and dataCache to new common package * Add eslint and move prettier config * Fix yarn lock * Clean up tests * Add lint-staged config to common * Add missing dependencies Approved-by: Joakim Jäderberg
76 lines
1.9 KiB
TypeScript
76 lines
1.9 KiB
TypeScript
import { type NextMiddleware, NextResponse } from "next/server"
|
|
|
|
import { getCacheClient } from "@scandic-hotels/common/dataCache"
|
|
|
|
import { notFound } from "@/server/errors/next"
|
|
import { getPublicNextURL } from "@/server/utils"
|
|
|
|
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",
|
|
},
|
|
signal: AbortSignal.timeout(15_000),
|
|
}
|
|
)
|
|
|
|
if (matchedRedirect.ok) {
|
|
const result = await matchedRedirect.text()
|
|
|
|
if (result) {
|
|
return result
|
|
}
|
|
}
|
|
return null
|
|
},
|
|
// longer once tested
|
|
"1d"
|
|
)
|
|
}
|
|
|
|
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, getPublicNextURL(request))
|
|
headers.set("Cache-control", "public, max-age=14400") // 4 hours
|
|
return NextResponse.redirect(newUrl, {
|
|
headers,
|
|
status: 308,
|
|
})
|
|
}
|
|
headers.set("x-continue", "1")
|
|
return NextResponse.next({ headers })
|
|
} catch (e) {
|
|
console.error("Redirect error: ", e)
|
|
throw notFound()
|
|
}
|
|
}
|
|
|
|
export const matcher: MiddlewareMatcher = (_) => {
|
|
return true
|
|
}
|