diff --git a/lib/auth.ts b/lib/auth.ts index 7806325..1932825 100644 --- a/lib/auth.ts +++ b/lib/auth.ts @@ -4,9 +4,20 @@ import { prisma } from "./prisma" import bcrypt from "bcryptjs" import { logger } from "./logger" -const nextAuthSecret = process.env.NEXTAUTH_SECRET -if (!nextAuthSecret) { - throw new Error("NEXTAUTH_SECRET is not set. Define it to enable authentication.") +// Lazy check for NEXTAUTH_SECRET - only validate when actually needed +// This prevents build-time errors when the secret isn't available +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" + } + return secret } // Determine if we should use secure cookies based on AUTH_URL/NEXTAUTH_URL @@ -155,5 +166,5 @@ export const { handlers, auth, signIn, signOut } = NextAuth({ }, } : undefined, // Let Auth.js defaults handle HTTPS envs (prefixes + Secure) - secret: nextAuthSecret, + secret: getNextAuthSecret(), }) diff --git a/proxy.ts b/proxy.ts index 70754c5..8f4a1d0 100644 --- a/proxy.ts +++ b/proxy.ts @@ -1,7 +1,6 @@ import { NextResponse } from "next/server" import type { NextRequest } from "next/server" import { getToken } from "next-auth/jwt" -import { SESSION_COOKIE_NAME } from "./lib/constants" import { logActivity } from "./lib/activity-log" export async function proxy(request: NextRequest) { @@ -13,11 +12,13 @@ export async function proxy(request: NextRequest) { } // Get token (works in Edge runtime) - // Use constant for cookie name to match NextAuth config + // 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 const token = await getToken({ req: request, secret: process.env.NEXTAUTH_SECRET, - cookieName: SESSION_COOKIE_NAME + // Don't specify cookieName - getToken will auto-detect __Secure- prefix for HTTPS }) // User activity logging - track all page visits and API calls