Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle redirect from supabase signin?

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;
like image 722
Chrissy Avatar asked Jan 23 '26 08:01

Chrissy


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

like image 159
msabic22 Avatar answered Jan 25 '26 00:01

msabic22



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!