Unable to get updated session in Supabase after password login

208 views Asked by At

I have this code which signs in a user in a sign in page:

else if (type === "password") {
            if (password1.length < 6) {
                toast.error("Password must be at least 6 characters long.");
                setIsLoading(false);
                return;
            }
            const { error } = await supabase.auth.signInWithPassword({ email: email1, password:password1 });
            if (error) {
              console.log(email1,password1)
              console.log("THE ERROR",error)
                toast.error(error.message);
            } else {
              // router.refresh()
                router.push(redirectURL);  // Redirect using Next.js router
                toast.success("Logged in successfully!");
            }

It then redirects the user to a dashboard which has this Layout.tsx:

import { ReactNode } from "react";
import { redirect } from "next/navigation";
import config from "@/config";
import { cookies } from "next/headers";
import { createServerComponentClient } from "@supabase/auth-helpers-nextjs";
import AppHeader from "@/components/AppHeader";

// This is a server-side component to ensure the user is logged in.
// If not, it will redirect to the login page.
// It's applied to all subpages of /dashboard in /app/dashboard/*** pages
export default async function LayoutPrivate({
  children,
}: {
  children: ReactNode;
}) {
  const supabase = createServerComponentClient({ cookies });

  const {
    data: { session },
  } = await supabase.auth.getSession();
  

  if (!session) {
    redirect("/");
  }



  return (
  <div>
        <AppHeader></AppHeader>
  <>{children}</>;
</div>
  )
}

I also have this middleware.tsx:

import { createMiddlewareClient } from "@supabase/auth-helpers-nextjs";
import { NextResponse, NextRequest } from "next/server";

// The middleware is used to refresh the user's session before loading Server Component routes
export async function middleware(req : NextRequest) {
  const res = NextResponse.next();
  const supabase = createMiddlewareClient({ req, res });
  await supabase.auth.getSession();
  return res;
}

The problem is that the user is getting redirected back from the dashboard to the homepage after they sign in. But, sometimes this does not happen and they are able to stay on the dashboard.

Why is the session not getting updated after the user signs in using the email and password?

0

There are 0 answers