client-login: hydrate Supabase session from API response before redirect
The wp-login API sets the auth cookie via NextResponse, but a
client-side router.push() doesn't always pick up the new cookie before
the destination page's AuthContext snapshots auth state — leading to a
brief 'logged out' flash on /contributor right after a successful
login.
Fix: after a successful POST to /api/auth/wp-login, call
supabase.auth.setSession({ access_token, refresh_token }) using the
session payload returned by the API. That hydrates the Supabase
browser client (and therefore AuthContext) immediately, so the next
render is authenticated. router.refresh() is also called to invalidate
the Next.js Router Cache for any stale RSC payloads.
Also adds console.error on both the !res.ok branch and the catch block
so login failures are inspectable in DevTools.
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
|
||||
import { useState } from 'react';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { createClient } from '@/lib/supabase/client';
|
||||
|
||||
export default function ClientLoginPage() {
|
||||
const [email, setEmail] = useState('');
|
||||
@@ -9,6 +10,7 @@ export default function ClientLoginPage() {
|
||||
const [error, setError] = useState('');
|
||||
const [loading, setLoading] = useState(false);
|
||||
const router = useRouter();
|
||||
const supabase = createClient();
|
||||
|
||||
const handleLogin = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
@@ -27,13 +29,27 @@ export default function ClientLoginPage() {
|
||||
|
||||
if (!res.ok) {
|
||||
setError(data.error || 'Login failed');
|
||||
console.error('Login error:', data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Redirect to contributor dashboard
|
||||
// Hydrate Supabase client with the session from the API response so
|
||||
// AuthContext picks it up immediately and the next render of
|
||||
// /contributor sees an authenticated user (no flash of logged-out
|
||||
// state, no race against cookie propagation).
|
||||
if (data.session?.access_token && data.session?.refresh_token) {
|
||||
await supabase.auth.setSession({
|
||||
access_token: data.session.access_token,
|
||||
refresh_token: data.session.refresh_token,
|
||||
});
|
||||
}
|
||||
|
||||
// Redirect to contributor dashboard (fresh session in AuthContext)
|
||||
router.push('/contributor');
|
||||
router.refresh();
|
||||
} catch (err: any) {
|
||||
setError(err.message || 'An error occurred');
|
||||
console.error('Login exception:', err);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user