fix(auth): public url

This commit is contained in:
Michael Zetterberg
2024-05-19 17:34:07 +02:00
parent a8d685c949
commit 068f19edb7
2 changed files with 13 additions and 6 deletions

4
.env
View File

@@ -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"

View File

@@ -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