import { type NextRequest, NextResponse } from "next/server" import { AuthError } from "next-auth" import { Lang } from "@scandic-hotels/common/constants/language" import { logger } from "@scandic-hotels/common/logger" import { isValidLang } from "@scandic-hotels/common/utils/languages" import { env } from "@/env/server" import { internalServerError } from "@/server/errors/next" import { getPublicURL } from "@/server/utils" import { signOut } from "@/auth" export async function GET( request: NextRequest, context: RouteContext<"/[lang]/logoutSafely"> ) { const publicURL = getPublicURL(request) const params = await context.params const lang = isValidLang(params.lang) ? params.lang : Lang.en const redirectToSearchParamValue = request.nextUrl.searchParams.get("redirectTo") const redirectToFallback = `/${lang}` let redirectTo: string = redirectToSearchParamValue || redirectToFallback // Make relative URL to absolute URL if (redirectTo.startsWith("/")) { redirectTo = new URL(redirectTo, publicURL).href } try { redirectTo = `${env.CURITY_ISSUER_USER}/authn/authenticate/logout?redirect_uri=${encodeURIComponent(redirectTo)}` logger.debug(`[logoutSafely] final redirectUrl: ${redirectTo}`) const redirectUrlObj = await signOut({ redirectTo, redirect: false, }) return NextResponse.redirect(redirectUrlObj.redirect) } catch (error) { if (error instanceof AuthError) { logger.error("signOutSafelyAuthError", { signOutAuthError: error }) } else { logger.error("signOutSafelyError", { signOutError: error }) } } return internalServerError() }