Next.js Discord

Discord Forum

NextAuth on server side component

Unanswered
Broad-snouted Caiman posted this in #help-forum
Open in Discord
Broad-snouted CaimanOP
Hello guys, I have an API route /posts that returns all the posts of an user (im using nextauth for authentication & authorization). So, in the posts route i call await getServerSession(authOptions) to find out which user is sending the request. When i send GET request from clientside to /posts, it works fine. but when I fetch it from a serverside component, getServerSession(authOptions) returns null. Why is that?

Also, when i call await getServerSession(authOptions) directly in a server side component it works fine.

6 Replies

Blue horntail woodwasp
what you want to get from session?
you can directly get the user data from token with getToken() from next-auth/jwt.
hope it helps
Broad-snouted CaimanOP
i use it like this :
export async function getSession() { return await getServerSession(authOptions); } // this function is used to get the current user from the database export const getCurrentUser = async () => { try { // get the current session const session = await getSession(); // if there is no session, return null if (!session?.user?.email) { return null; } // find the user in the database const currentUser = await prisma.user.findUnique({ where: { email: session.user.email as string, }, }); // if there is no user, return null if (!currentUser) { return null; } // return the user return { ...currentUser, createdAt: currentUser.createdAt.toISOString(), updatedAt: currentUser.updatedAt.toISOString(), }; } catch (error: any) { return null; } };
Blue horntail woodwasp
as far as I know, getServerSession only works in Client Side, cmiiw