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
the way that I fixed it was by doing:
import UsersList from "../components/UsersList";
import { createClient } from "@/utils/supabase/server";
export default async function Home() {
const supabase = createClient();
const {
data: { error, user },
} = await supabase.auth.getUser();
if (error) {
console.error("Error fetching user:", error.message);
} else {
console.log("user:", user);
}
return (
<div>
<UsersList />
</div>
);
}
in main page.tsx