Files
web/server/utils.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

63 lines
1.5 KiB
TypeScript

import { z } from "zod"
import { Lang } from "@/constants/languages"
import { env } from "@/env/server"
import type { NextRequest } from "next/server"
export const langInput = z.object({
lang: z.nativeEnum(Lang),
})
/**
* Helper function to convert Lang enum to API lang enum.
*/
export const toApiLang = (lang: Lang): string => {
const result = toApiLangMap[lang]
if (!result) {
throw new Error("Invalid language")
}
return result
}
const toApiLangMap: { [key in Lang]: string } = {
[Lang.en]: "En",
[Lang.sv]: "Sv",
[Lang.no]: "No",
[Lang.fi]: "Fi",
[Lang.da]: "Da",
[Lang.de]: "De",
}
/**
* Helper function to convert lang string to Lang enum.
*/
export function toLang(lang: string): Lang | undefined {
const lowerCaseLang = lang.toLowerCase()
return Object.values(Lang).find((l) => l === lowerCaseLang)
}
export function getPublicURL(request: NextRequest) {
if (env.PUBLIC_URL) {
return env.PUBLIC_URL
}
const host = request.nextUrl.host
const proto = request.nextUrl.protocol
return `${proto}//${host}`
}
export function getPublicNextURL(request: NextRequest) {
if (env.PUBLIC_URL) {
const publicNextURL = request.nextUrl.clone()
// Akamai in front of Netlify for dedicated environments
// require us to rewrite the incoming host and hostname
// to match the public URL used to visit Akamai.
const url = new URL(env.PUBLIC_URL)
publicNextURL.host = url.host
publicNextURL.hostname = url.hostname
return publicNextURL
}
return request.nextUrl
}