From 068f19edb76a43c4ea2b2b074899a3f7d9faf137 Mon Sep 17 00:00:00 2001 From: Michael Zetterberg Date: Sun, 19 May 2024 17:34:07 +0200 Subject: [PATCH] fix(auth): public url --- .env | 4 ++-- middlewares/authRequired.ts | 15 +++++++++++---- 2 files changed, 13 insertions(+), 6 deletions(-) diff --git a/.env b/.env index f54eeae72..881737c28 100644 --- a/.env +++ b/.env @@ -1,3 +1,3 @@ # See update-dotenv.mjs -PUBLIC_URL="https://www.google.com" -NEXTAUTH_URL="https://www.google.com/api/web/auth" +PUBLIC_URL="REPLACED-ON-NETLIFY-BUILD" +NEXTAUTH_URL="REPLACE-ON-NETLIFY-BUILD" diff --git a/middlewares/authRequired.ts b/middlewares/authRequired.ts index 26a98024b..be7ce5fa9 100644 --- a/middlewares/authRequired.ts +++ b/middlewares/authRequired.ts @@ -4,6 +4,7 @@ import { findLang } from "@/constants/languages" import { authRequired } from "@/constants/routes/authRequired" import { login } from "@/constants/routes/handleAuth" import { env } from "@/env/server" +import { internalServerError } from "@/server/errors/next" import { auth } from "@/auth" @@ -46,16 +47,22 @@ export const middleware = auth(async (request) => { return NextResponse.next() } - const publicUrl = nextUrl.clone() - publicUrl.host = env.PUBLIC_URL! + if (!env.PUBLIC_URL) { + throw internalServerError("Missing value for env.PUBLIC_URL") + } + + const publicUrl = new URL(env.PUBLIC_URL) + const nextUrlClone = nextUrl.clone() + nextUrlClone.host = publicUrl.host + nextUrlClone.hostname = publicUrl.hostname const headers = new Headers() headers.append( "set-cookie", - `redirectTo=${encodeURIComponent(publicUrl.href)}; Path=/; HttpOnly; SameSite=Lax` + `redirectTo=${encodeURIComponent(nextUrlClone.href)}; Path=/; HttpOnly; SameSite=Lax` ) const loginUrl = login[lang] - return NextResponse.redirect(new URL(loginUrl, publicUrl), { + return NextResponse.redirect(new URL(loginUrl, nextUrlClone), { headers, }) }) as NextMiddleware // See comment above