Server side auth in Supabase with NextJS -- how to handle session?
Answered
West African Lion posted this in #help-forum
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:
When I log in then I can see that a cookie is being created, but session logs as null
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?18 Replies
@West African Lion 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:
js
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
don't check your auth inside your layout. It can leak and you get unexpected data (like you now see). You can read more about this here: https://github.com/eric-burel/securing-rsc-layout-leak
TL;DR:
checking authentication in a middleware
checking authentication in the page
checking authentication in the data fetching method
TL;DR:
checking authentication in a middleware
checking authentication in the page
checking authentication in the data fetching method
West African LionOP
ok, thanks
will try in page next
I made main page like so:
but
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 nullafter I login and get redirected to main page
@B33fb0n3
@West African Lion I made main page like so:
js
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
It looks like you need to do something with the cookies to access your session. Right now, you get them, but you don't do anything with them. Try to pass them as variables somewhere
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:
Like that a new network request is made to the supabase servers to get the currect session of the current user.
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 serverWest African LionOP
@B33fb0n3 thanks
I tried doing:
in main
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 Lion <@301376057326567425> thanks
I tried doing:
js
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`
It looks like you are not logged in yet. Can you confirm, that you are logged in?
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