Skip to content

Commit 807d259

Browse files
fix(auth): handle implicit flow tokens in OAuth callback
1 parent 2a1153f commit 807d259

1 file changed

Lines changed: 33 additions & 10 deletions

File tree

app/auth/callback/page.tsx

Lines changed: 33 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -13,29 +13,52 @@ export default function AuthCallbackPage() {
1313
const code = params.get("code");
1414
const errorParam = params.get("error");
1515
const errorDescription = params.get("error_description");
16+
const hashParams = new URLSearchParams(window.location.hash.slice(1));
17+
const accessToken = hashParams.get("access_token");
1618

1719
if (errorParam) {
1820
setError(errorDescription || errorParam);
1921
setTimeout(() => router.push("/login"), 3000);
2022
return;
2123
}
2224

23-
if (!code) {
24-
router.push("/dashboard");
25+
if (code) {
26+
// PKCE flow: exchange code for session
27+
supabase.auth
28+
.exchangeCodeForSession(code)
29+
.then(({ error: exchangeError }) => {
30+
if (exchangeError) {
31+
console.error("[auth/callback] Exchange error:", exchangeError);
32+
setError(exchangeError.message);
33+
setTimeout(() => router.push("/login"), 3000);
34+
} else {
35+
router.push("/dashboard");
36+
}
37+
});
2538
return;
2639
}
2740

28-
supabase.auth
29-
.exchangeCodeForSession(code)
30-
.then(({ error: exchangeError }) => {
31-
if (exchangeError) {
32-
console.error("[auth/callback] Exchange error:", exchangeError);
33-
setError(exchangeError.message);
34-
setTimeout(() => router.push("/login"), 3000);
35-
} else {
41+
if (accessToken) {
42+
// Implicit flow: supabase client auto-detects the hash and fires SIGNED_IN.
43+
// Wait for the session to be established before navigating.
44+
const { data: { subscription } } = supabase.auth.onAuthStateChange((event) => {
45+
if (event === "SIGNED_IN") {
46+
subscription.unsubscribe();
3647
router.push("/dashboard");
3748
}
3849
});
50+
// Fallback in case onAuthStateChange doesn't fire (session already set)
51+
supabase.auth.getSession().then(({ data: { session } }) => {
52+
if (session) {
53+
subscription.unsubscribe();
54+
router.push("/dashboard");
55+
}
56+
});
57+
return;
58+
}
59+
60+
// No code or token — just go to dashboard (handles direct navigation to this route)
61+
router.push("/dashboard");
3962
}, [router]);
4063

4164
if (error) {

0 commit comments

Comments
 (0)