Branchwell

AI Resource Pro / website · airesourcepro.com / src / app / auth / callback / route.ts

Raw 1.5 KB on b7854f3692d64213a2fce644d0b5101d3e345b03
1import { NextResponse } from "next/server";
2import { cookies } from "next/headers";
3import { SKIP_ONBOARDING_COOKIE } from "@/lib/onboarding";
4import { accountStore } from "@/lib/account-store";
5import { sessionUser } from "@/lib/session-server";
6
7export const dynamic = "force-dynamic";
8
9// Better Auth returns here after the provider callback has created a session.
10export async function GET(request: Request) {
11 const url = new URL(request.url);
12 const nextParam = url.searchParams.get("next") ?? "/account";
13 let next = "/account";
14 if (nextParam.startsWith("/")) {
15 const target = URL.parse(nextParam, url.origin);
16 if (target?.origin === url.origin && !target.pathname.startsWith("//")) {
17 next = target.href.slice(url.origin.length);
18 }
19 }
20
21 const user = await sessionUser(request).catch(() => null);
22 if (!user) {
23 return NextResponse.redirect(new URL("/login?error=auth_error", url.origin));
24 }
25
26 const cookieStore = await cookies();
27
28 // Onboard anyone who hasn't answered the roadmap questions yet (answers given before sign-in carry over there)
29 if (!next.startsWith("/roadmap") && !cookieStore.get(SKIP_ONBOARDING_COOKIE)) {
30 try {
31 const profile = await accountStore(user).profile();
32 if (!profile) {
33 return NextResponse.redirect(new URL(`/roadmap/start?welcome=1&next=${encodeURIComponent(next)}`, url.origin));
34 }
35 } catch {
36 console.error("[auth/callback] Profile check failed");
37 }
38 }
39
40 return NextResponse.redirect(new URL(next, url.origin));
41}