Next.js Discord

Discord Forum

Server side auth in Supabase with NextJS -- how to handle session?

Answered
West African Lion posted this in #help-forum
Open in Discord
West African LionOP
I have followed the following guide for setting up server side auth with Supabase and NextJS (with App Router):

https://supabase.com/docs/guides/auth/server-side/nextjs?queryGroups=router&router=app

I am trying to get session and perform logic with it in main layout.tsx file:

export default async function RootLayout({ children }: RootLayoutProps) {
  // Get cookies from the request to access the session
  const cookieStore = cookies();
  const accessToken = cookieStore.get("sb-access-token")?.value;

  // Fetch the current session
  const {
    data: { session },
    error,
  } = await supabase.auth.getSession();

  if (error) {
    console.error("Error fetching session:", error.message);
  } else {
    console.log("Session:", session); // Log session for debugging
  }

  return (
    <html lang="en">
      <body>
        <TopNav />
        {children}
      </body>
    </html>
  );
}


When I log in then I can see that a cookie is being created, but session logs as null
Answered by B33fb0n3
And how to you create the supabase client when you want to access the data? In the shared case you do it by const supabase = createClient();. How do you do it when accessing it?
View full answer

18 Replies

West African LionOP
ok, thanks
will try in page next
I made main page like so:

import UsersList from "../components/UsersList";
import { supabase } from "../lib/supabaseClient"; // Import your Supabase client
import { cookies } from "next/headers"; // For handling cookies in the App Router

export default async function Home() {
  // Get cookies from the request to access the session
  const cookieStore = cookies();
  const accessToken = cookieStore.get("sb-access-token")?.value;

  // Fetch the current session
  const {
    data: { session },
    error,
  } = await supabase.auth.getSession();

  if (error) {
    console.error("Error fetching session:", error.message);
  } else {
    console.log("Session:", session); // Log session for debugging
  }

  return (
    <div>
      <UsersList />
    </div>
  );
}


but session still logs null
after I login and get redirected to main page
@B33fb0n3
West African LionOP
TBQH, I was just trying some code provided by chatgpt.. I'm having a hard time finding proper way to do it in docs.. I'll keep looking
@West African Lion TBQH, I was just trying some code provided by chatgpt.. I'm having a hard time finding proper way to do it in docs.. I'll keep looking
Do it like this:
const { data: { user } } = await supabase.auth.getUser()

Like that a new network request is made to the supabase servers to get the currect session of the current user. getSession is insecure on the server
West African LionOP
@B33fb0n3 thanks

I tried doing:

export default async function Home() {
  // Get cookies from the request to access the session
  const cookieStore = cookies();
  const accessToken = cookieStore.get("sb-access-token")?.value;

  // Fetch the current session
  const {
    data: { error, user },
  } = await supabase.auth.getUser();

  if (error) {
    console.error("Error fetching user:", error.message);
  } else {
    console.log("user:", user); // Log session for debugging
  }

  return (
    <div>
      <UsersList />
    </div>
  );
}


in main page.tsx but user is also logging undefined
West African LionOP
@B33fb0n3 I think so, since I see this cookie get created
how do you create your supabase instance await supabase.auth?
West African LionOP
export async function login(formData: FormData) {
  const supabase = createClient();

  // type-casting here for convenience
  // in practice, you should validate your inputs
  const data = {
    email: formData.get("email") as string,
    password: formData.get("password") as string,
  };

  const { error } = await supabase.auth.signInWithPassword(data);

  if (error) {
    redirect("/error");
  }

  revalidatePath("/", "layout");
  redirect("/");
}
And how to you create the supabase client when you want to access the data? In the shared case you do it by const supabase = createClient();. How do you do it when accessing it?
Answer
West African LionOP
thanks, you just made me realize that I should be doing const supabase = createClient();
and I'm now able to log a user
happy to help