You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Supabase Auth登出,避免自动跳转至登出页并跳转首页?

解决Next.js中Supabase登出后跳转至主页的问题

情况1:手动调用signOut后自行处理跳转

如果你的代码是直接调用supabase.auth.signOut(),默认Supabase不会触发自动跳转,你可以在登出成功后手动添加路由跳转逻辑:

// 客户端组件示例
import { supabase } from '@/lib/supabase';
import { useRouter } from 'next/navigation';

const handleSignOut = async () => {
  const { error } = await supabase.auth.signOut();
  if (!error) {
    // 跳转到主页
    router.push('/');
  }
};

情况2:使用Supabase Auth UI组件

若你用了Supabase官方的Auth UI组件,可在初始化时配置redirectTo参数指定跳转目标:

import { createClientComponentClient } from '@supabase/auth-helpers-nextjs';
import { Auth } from '@supabase/auth-ui-react';
import { ThemeSupa } from '@supabase/auth-ui-shared';

export default function AuthPage() {
  const supabase = createClientComponentClient();

  return (
    <Auth
      supabaseClient={supabase}
      appearance={{ theme: ThemeSupa }}
      providers={['email']}
      // 配置登出后跳转至主页
      redirectTo={window.location.origin + '/'}
    />
  );
}

情况3:通过Supabase Auth中间件处理跳转

如果项目使用了Supabase的Auth中间件,检查middleware.ts中的路由规则,确保登出后没有强制跳转到其他页面:

// middleware.ts
import { createMiddlewareClient } from '@supabase/auth-helpers-nextjs';
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export async function middleware(req: NextRequest) {
  const res = NextResponse.next();
  const supabase = createMiddlewareClient({ req, res });

  const { data: { user } } = await supabase.auth.getUser();

  // 仅在未登录访问授权页面时跳转登录页,其余情况正常放行
  if (!user && req.nextUrl.pathname.startsWith('/dashboard')) {
    return NextResponse.redirect(new URL('/login', req.url));
  }

  return res;
}

export const config = {
  matcher: ['/dashboard/:path*', '/'],
};

额外排查点

  • 检查项目中是否存在authStateChange监听逻辑,若有则修改登出事件的跳转目标:
    supabase.auth.onAuthStateChange((event, session) => {
      if (event === 'SIGNED_OUT') {
        window.location.href = '/';
      }
    });
    
  • 确认Supabase控制台Auth -> URL Configuration中的Site URL和Redirect URLs配置正确,避免平台级强制跳转。

内容的提问来源于stack exchange,提问作者Turing Vang

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 23:50:59