如何处理来自 supabase 登录的重定向?

How to handle redirect from supabase signin?

我希望有人能告诉我如何在 supabase 中处理重定向(到仪表板页面)。下面是我的代码示例(问题是我想在身份验证后重定向到帐户页面,但事实并非如此,所以我不得不根据用户会话显示仪表板组件)。请告知,因为我想改为重定向到仪表板。

这是我尝试过的:

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 { data, error } = useSWR(
    session ? ["/api/getUser", session.access_token] : null,
    fetcher
  );
  const [authView, setAuthView] = useState("sign_in");

  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);
        // 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();
    };
  }, []);

  const View = () => {
    if (!user)
      return (
        <Space direction="vertical" size={8}>
          <div>
            <a href="/">
              <img className="signlogo" src="/images/logo.png" width="96" />
            </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"
          />
        </Space>
      );

    return (
      <Space direction="vertical" size={6}>
        {authView === "forgotten_password" && (
          <Auth.UpdatePassword supabaseClient={supabase} />
        )}
        {user && (
          <>
            {async () =>
              await supabase.auth.signIn(
                { provider: "googole" },
                { redirectTo: "/dashboard" }
              )
            }
          </>
        )}
      </Space>
    );
  };

  return (
    <div style={{ maxWidth: "420px", margin: "96px auto" }}>
      <Card>
        <View />
      </Card>
    </div>
  );
};

export default Index;

您在验证后是否尝试过 Router.push()

Router.push({
    pathname:'/some-path',
    query: { example: 'something' },                // query is optional
}).then(() => {
    window.scrollTo(0, 0)
})

.then 也是可选的,但如果您想在重定向后滚动回到顶部,您可能会发现它很有帮助

您需要将路由器从 'next/router' 导入您的页面。 您也可以将它从 app.js 传递到每个组件,但可能不需要它,因此您可以只在需要它的页面上导入它。

方法一:

import Router from 'next/router' 
Router.push()

方法二:

import { useRouter } from 'next/router' 
const router = useRouter()
router.push

两者都有效