Skip to content

Commit ff2bd8f

Browse files
committed
feat(auth): implement callback route for session exchange and user retrieval, remove unused confirm route
1 parent 81024a4 commit ff2bd8f

File tree

5 files changed

+56
-26
lines changed

5 files changed

+56
-26
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { NextResponse } from "next/server";
2+
import { createClient } from "@/lib/supabase/server";
3+
4+
export async function GET(request: Request) {
5+
const { searchParams, origin } = new URL(request.url);
6+
const code = searchParams.get("code");
7+
const next = searchParams.get("next") ?? "/";
8+
9+
if (code) {
10+
const supabase = await createClient();
11+
const { error } = await supabase.auth.exchangeCodeForSession(code);
12+
13+
if (!error) {
14+
const forwardedHost = request.headers.get("x-forwarded-host");
15+
const isLocalEnv = process.env.NODE_ENV === "development";
16+
17+
if (isLocalEnv) return NextResponse.redirect(`${origin}${next}`);
18+
if (forwardedHost)
19+
return NextResponse.redirect(`https://${forwardedHost}${next}`);
20+
return NextResponse.redirect(`${origin}${next}`);
21+
}
22+
}
23+
24+
return NextResponse.redirect(`${origin}/auth/auth-code-error`);
25+
}

src/app/(public)/auth/confirm/route.ts

Lines changed: 0 additions & 26 deletions
This file was deleted.

src/hooks/use-auth-user.ts

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"use client";
2+
3+
import { useEffect, useState } from "react";
4+
import { createClient } from "@/lib/supabase/client";
5+
6+
export function useAuthUser() {
7+
const [user, setUser] = useState(null);
8+
const [loading, setLoading] = useState(true);
9+
const supabase = createClient();
10+
11+
useEffect(() => {
12+
const getUser = async () => {
13+
const { data } = await supabase.auth.getUser();
14+
setUser(data.user);
15+
setLoading(false);
16+
};
17+
18+
getUser();
19+
20+
const {
21+
data: { subscription },
22+
} = supabase.auth.onAuthStateChange((_event, session) => {
23+
setUser(session?.user ?? null);
24+
});
25+
26+
return () => subscription.unsubscribe();
27+
}, []);
28+
29+
return { user, loading };
30+
}

src/lib/supabase/middleware.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { NextResponse, type NextRequest } from "next/server";
33

44
const publicRoutes = ["/", "/auth/login", "/resources"];
55
const publicRoutePrefixes = [
6+
"/auth/",
67
"/resources/",
78
"/languages/",
89
"/frameworks-libraries/",

src/lib/utils.ts

Whitespace-only changes.

0 commit comments

Comments
 (0)