I’m using the version of next.js 14 with its app routing feature and NextAuth.
I’m looking to secure the API but I’m getting a null object when using the getServerSession( authOptions )
method when requesting a protected endpoint with Postman at http://localhost:3000/api/user/clotdcsk0001kvjmg8bvbkxy7
.
I tried passing a Bearer Token in the Authorization part of the request, which is the next-auth.session-token
cookie, this makes posible to pass the middleware protection and hit the endpoint, but I’m not able to get the session object inside the GET method for custom logic.
Here is my /api/user/[id]/route.ts
file.
export async function GET ( req : NextRequest, ds : DynamicSegment ) {
const session = await getServerSession( options )
console.log(session) //prints null
// Custom logic to handle the request...
}
If I use the same approach of using the getServerSession
method in a page.tsx file to get the session object it works fine (via the explorer). What I’m missing to make possible work with a session object when requesting from Postman?
2
Answers
I found out that the cookie of the next-auth.session-token should be passed in the request, when calling from the browser or postman.
Where sessionToken is the cookie value fetched from
page.tsx
you can try this