From 19d5b7ef990ea116b503874589caaed69f7d9099 Mon Sep 17 00:00:00 2001 From: ilia Date: Sun, 4 Jan 2026 22:15:47 -0500 Subject: [PATCH] refactor: Enhance cookie handling and error management in authentication - Updated `proxy.ts` to explicitly define cookie names based on the request protocol, improving clarity in cookie management. - Refactored `auth.ts` to always throw an error for missing `NEXTAUTH_SECRET` at runtime, ensuring critical configuration is validated consistently. --- lib/auth.ts | 9 ++------- proxy.ts | 8 +++++--- 2 files changed, 7 insertions(+), 10 deletions(-) diff --git a/lib/auth.ts b/lib/auth.ts index 1932825..d5984de 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -9,13 +9,8 @@ import { logger } from "./logger" function getNextAuthSecret(): string { const secret = process.env.NEXTAUTH_SECRET if (!secret) { - // Only throw in non-build contexts (runtime) - // During build, Next.js might not have env vars available - if (process.env.NEXT_PHASE !== "phase-production-build") { - throw new Error("NEXTAUTH_SECRET is not set. Define it to enable authentication.") - } - // Return a placeholder during build - will fail at runtime if not set - return "build-time-placeholder" + // Always throw at runtime - this is a critical configuration error + throw new Error("NEXTAUTH_SECRET is not set. Define it to enable authentication.") } return secret } diff --git a/proxy.ts b/proxy.ts index 8f4a1d0..891dbfd 100644 --- a/proxy.ts +++ b/proxy.ts @@ -13,12 +13,14 @@ export async function proxy(request: NextRequest) { // Get token (works in Edge runtime) // For HTTPS, NextAuth adds __Secure- prefix automatically - // Don't specify cookieName - let getToken auto-detect the correct cookie name - // It will automatically look for both prefixed and non-prefixed versions + // getToken should handle the prefix, but we specify the base name + const isHttps = request.url.startsWith("https://") + const cookieName = isHttps ? `__Secure-authjs.session-token` : `authjs.session-token` + const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET, - // Don't specify cookieName - getToken will auto-detect __Secure- prefix for HTTPS + cookieName: cookieName, }) // User activity logging - track all page visits and API calls