Search code examples
javascriptsessionnext.jspostmannext-auth

How to get a session object in the server side in next.js 14?


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?


Solution

  • 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.

    let response = await fetch(`/api/users/${userId}`, {
      method: "GET",
      headers: { 
        "Content-Type": "application/json",
        "Cookie": `next-auth.session-token=${sessionToken};path=/;expires=Session`    
      },
       cache: 'no-store',
    });
    

    Where sessionToken is the cookie value fetched from

    page.tsx

    import { cookies } from 'next/headers'
       
       // ...
       
       // Get sessionToken object
       const cookieStore = cookies()
       let sessionTokenCookie = cookieStore.get('next-auth.session-token')
       let sessionToken = sessionTokenCookie.value;