Next.js Discord

Discord Forum

Next-Auth getServerSession(options)

Answered
Transvaal lion posted this in #help-forum
Open in Discord
Avatar
Transvaal lionOP
Is anyone experienced in getting a users session data (id) in an api route in the app router?

I am currently trying to get the current authenticated users session data so the API route will be able to retrieve data for that specific users ID. I have tested this in regular components in the photo I have given, and returned the expected data in the console. But when i try something similar in my API route my user session returns null. I cant seem to find a solution to this in the official next-auth docs. Any help would be greatly appreciated.
Image
Image
Answered by Transvaal lion
Hey guys, i feel kind of foolish now, but it turns out the reason i was getting null as my response from getserversession was because I was accessing the API route from postman, and not my front end where my session cookie was created. So you need your session from the browser and that will validate your request.
View full answer

15 Replies

Avatar
ncls.
Can you share the code for your API route?
Avatar
Transvaal lionOP
Image
just trying to see if the data is there
Image
when i console log in a server component I receive the user object back, but i am now noticing that it only includes

user: {
name: 'my name'
email: 'my email i logged in with'
image: 'github profile image'
}
Image
so i am now realizing that i am not getting the id back either in this console.log
Avatar
Transvaal lionOP
Will continue to troubleshoot and provide my answer, because this seems to be a common issue. I need to understand the logic of cookies/sessions a little more.
Avatar
fuma 💙 joulev
As I remember, there’s no a id property by default in sessions

Generally, we will use custom callbacks to inject the user id: https://next-auth.js.org/configuration/callbacks
Avatar
ncls.
Try changing
import { getServerSession } from "next-auth";

to
import { getServerSession } from "next-auth/next";
Avatar
Transvaal lionOP
Image
Avatar
ncls.
Try passing it req, res, options
Avatar
fuma 💙 joulev
If you’re trying to get the session in a route handler, you must return a response
Avatar
Transvaal lionOP
Hey guys, i feel kind of foolish now, but it turns out the reason i was getting null as my response from getserversession was because I was accessing the API route from postman, and not my front end where my session cookie was created. So you need your session from the browser and that will validate your request.
Answer
Avatar
Transvaal lionOP
here is how get my current user that is accessing the database using getServerSession
Image
if anyone has any questions about this id be happy to help after I felt like i was eating crayons for the past week trying to figure this out!