How to handle redirect from supabase signin?

Viewed 1796

I was hoping someone would show me how to handle redirect (to dashboard page) in supabase. Here below is a sample of my code (the issue is I would like to redirect to an account page after authentication but it wouldn't so I had to show the dashboard component based on user session). Please advise as I would like to redirect to dashboard instead.

Here is what I have tried:

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;
1 Answers

Have you tried with Router.push() after authentification

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

.then is also optional, but you may find it helpful if you want to scroll back to top after redirect

You need to import router from 'next/router' to your page. You can also pass it down from app.js to every component, but there is probably no need for it, so you can import it only on the pages you need it.

Approach 1. :

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

Approach 2. :

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

Both are valid

Related