如何处理Supabase登录成功后重定向到指定仪表盘页面的问题
Supabase 认证完成后自动重定向到仪表盘实现方案
核心修改点
- 实例化已经引入的
useRouter路由实例,用于跳转 - 在
onAuthStateChange监听回调中新增登录成功事件判断,触发跳转 - 新增监听
user状态的副作用,避免页面初始化时已存在登录态无法跳转的问题 - 移除无效代码,修正第三方登录provider的拼写错误
- 给
Auth组件显式配置redirectTo参数,适配第三方登录回调场景
修改后完整代码
import useSWR from "swr"; import { Auth, Card, Typography, Space } from "@supabase/ui"; import { supabase } from "../utils/supabaseClient"; import { useEffect, useState } from "react"; import Dashboard from "./dashboard/index"; import { useRouter } from "next/router"; const fetcher = (url, token) => fetch(url, { method: "GET", headers: new Headers({ "Content-Type": "application/json", token }), credentials: "same-origin", }).then((res) => res.json()); const Index = () => { const { user, session } = Auth.useUser(); const router = useRouter(); // 实例化路由 const { data, error } = useSWR( session ? ["/api/getUser", session.access_token] : null, fetcher ); const [authView, setAuthView] = useState("sign_in"); // 监听用户登录态变化,存在登录态直接跳转 useEffect(() => { if (user) { router.push('/dashboard') } }, [user, router]) useEffect(() => { const { data: authListener } = supabase.auth.onAuthStateChange( (event, session) => { if (event === "PASSWORD_RECOVERY") setAuthView("forgotten_password"); if (event === "USER_UPDATED") setTimeout(() => setAuthView("sign_in"), 1000); // 登录成功触发跳转 if (event === "SIGNED_IN" && session) { router.push('/dashboard') } // Send session to /api/auth route to set the auth cookie. // NOTE: this is only needed if you're doing SSR (getServerSideProps)! fetch("/api/auth", { method: "POST", headers: new Headers({ "Content-Type": "application/json" }), credentials: "same-origin", body: JSON.stringify({ event, session }), }).then((res) => res.json()); } ); return () => { authListener.unsubscribe(); }; }, [router]); const View = () => { if (!user) return ( <Space direction="vertical" size={8}> <div> <a href="/"> <img className="signlogo" src="/images/logo.png" width="96" alt="logo"/> </a> <Typography.Title level={3} className="text-center"> Welcome to fluidFlats </Typography.Title> </div> <Auth supabaseClient={supabase} providers={["google"]} view={authView} socialLayout="horizontal" socialButtonSize="xlarge" redirectTo="/dashboard" // 配置认证成功跳转地址 /> </Space> ); return ( <Space direction="vertical" size={6}> {authView === "forgotten_password" && ( <Auth.UpdatePassword supabaseClient={supabase} /> )} </Space> ); }; return ( <div style={{ maxWidth: "420px", margin: "96px auto" }}> <Card> <View /> </Card> </div> ); }; export default Index;
额外注意事项
- 如果你使用的是Supabase v2版本,
onAuthStateChange的返回结构有调整,不需要加.data取监听实例,直接写const authListener = supabase.auth.onAuthStateChange(...)即可 - 要在Supabase控制台的认证设置里把
/dashboard加入到重定向URL白名单,否则会跳转失败
内容的提问来源于stack exchange,提问作者Chrissy
相关产品推荐
相关产品推荐

