Search code examples
sessionnext.jsnext-authserverside-javascript

Why can't I extract the id from my session.user, serverside in nextjs 13


I can't seem to get the id from my session.user(next-auth) when everything is properly set. Here is some of my code.

/Api/getId/index.ts in the following code I am trying to access my session through the getServerSession, and I actually do get back my session intact. However, when I try to access the user.id in the session I get the following error

Property 'id' does not exist on type '{ name?: string | null | undefined; email?: string | null | undefined; image?: string | null | undefined; }'.

import { NextApiRequest, NextApiResponse } from "next";
import { getServerSession } from "next-auth";
import { authOptions } from "../../auth/[...nextauth]";
import Prisma from '../../../../libs/prismadb'
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
    try{
        const session = await getServerSession(req, res, authOptions)
        console.log(session?.user.id, '1')
        if(session?.user){
            // const admin = await Prisma.owner.findUnique({
            //     where: {
            //         id: session?.user?.id
            //     }
            // })
            console.log(session, '2')
        }
        res.status(200).json({session})
    }catch(err: any){
        throw new Error(err)
    }
}

But it does exist on that type

export interface DefaultSession {
  user?: {
    name?: string | null
    email?: string | null
    image?: string | null
    id?: string | null
  }
  expires: ISODateString
}

I tried restarting my typescript server, even restarting vscode but nothing seems to work. Even when I try to console.log(session) I see that id does exist inside the user object. Please help if you know what is wrong as this is a large project I am working on and I can't afford to fall behind on it


Solution

  • First you need to make sure that you included the session.user.id in the Nextauth callbacks. It should look something like this:

    callbacks: {
        session({ session, user }) {
          if (session.user) {
            session.user.id = user.id;
          }
          return session;
        },
      },
    

    If that is there, you need to use "module augmentation" to add the id to the the types of DefaultSession like this:

    // next-auth.d.ts
    
    import { DefaultSession } from "next-auth";
    
    declare module "next-auth" {
      interface Session {
        user?: {
          id: string;
        } & DefaultSession["user"];
      }
    }
    

    ^ takes the default session and adds it the id string. You can also use module augmentation to add some other fields to it like role for example.

    More info: https://next-auth.js.org/getting-started/typescript#module-augmentation

    If it still does not work, make sure that the id exist in the database schema

    Let me know if worked :)