import { NextResponse } from "next/server"; import { cookies } from "next/headers"; import { SKIP_ONBOARDING_COOKIE } from "@/lib/onboarding"; import { accountStore } from "@/lib/account-store"; import { sessionUser } from "@/lib/session-server"; export const dynamic = "force-dynamic"; // Better Auth returns here after the provider callback has created a session. export async function GET(request: Request) { const url = new URL(request.url); const nextParam = url.searchParams.get("next") ?? "/account"; let next = "/account"; if (nextParam.startsWith("/")) { const target = URL.parse(nextParam, url.origin); if (target?.origin === url.origin && !target.pathname.startsWith("//")) { next = target.href.slice(url.origin.length); } } const user = await sessionUser(request).catch(() => null); if (!user) { return NextResponse.redirect(new URL("/login?error=auth_error", url.origin)); } const cookieStore = await cookies(); // Onboard anyone who hasn't answered the roadmap questions yet (answers given before sign-in carry over there) if (!next.startsWith("/roadmap") && !cookieStore.get(SKIP_ONBOARDING_COOKIE)) { try { const profile = await accountStore(user).profile(); if (!profile) { return NextResponse.redirect(new URL(`/roadmap/start?welcome=1&next=${encodeURIComponent(next)}`, url.origin)); } } catch { console.error("[auth/callback] Profile check failed"); } } return NextResponse.redirect(new URL(next, url.origin)); }