使用Supabase+Facebook登录后URL残留#符号,如何解决?
解决Supabase Facebook登录后URL残留#号的问题
这个#号是因为Supabase默认采用hash模式处理OAuth回调导致的,下面提供两种可行的解决方式:
方式一:自定义回调URL并清理路径
在调用signIn时指定redirectTo参数,指向一个专门的回调页面(或首页),同时在Supabase控制台的认证 > 外部OAuth提供商里添加这个回调URL(比如https://your-domain.com/callback)。
修改你的登录函数:
const signIn = async () => await supabase.auth.signIn({ provider: "facebook", }, { redirectTo: `${window.location.origin}/callback` // 自定义回调地址 });
接着在回调页面(或App组件的useEffect里)处理登录状态后,清理URL:
useEffect(() => { const session = supabase.auth.session(); setCurrentSession(session); // 登录成功后清理URL中的# if (session && window.location.hash) { window.history.replaceState({}, document.title, window.location.pathname); } const { data: authListener } = supabase.auth.onAuthStateChange( (event, session) => { setCurrentSession(session); // 监听登录事件,触发时清理URL if (event === 'SIGNED_IN' && window.location.hash) { window.history.replaceState({}, document.title, window.location.pathname); } } ); return () => { authListener?.unsubscribe(); }; }, []);
方式二:直接在认证状态变更时清理URL
如果不需要自定义回调页,也可以在onAuthStateChange的回调逻辑里直接处理:
const { data: authListener } = supabase.auth.onAuthStateChange( (event, session) => { setCurrentSession(session); // 仅在登录成功且URL存在#时清理 if (event === 'SIGNED_IN' && window.location.hash) { // 替换当前历史记录,不会触发页面刷新 window.history.replaceState({}, document.title, window.location.pathname); } } );
另外注意你代码里的一个小错误:cost App应该改为const App,避免语法报错。
内容的提问来源于stack exchange,提问作者Kasper Verner
相关产品推荐
相关产品推荐

