next-auth

How to extend next-auth User type beta-20


I am using the current beta version

"next-auth": "5.0.0-beta.20"

I have extended the user database entity to include a role.

I have extended the callback:

callbacks: {
    //usually not needed bug in nextAuth
    async session({ session, user }: any) {
      if (session && user) {
        session.user.id = user.id;
        session.user.role = user.role;
      }
      return session;
    },
  },

When I use

const session = useSession();   
    const user = session.data?.user;

The variable user does not have the role attribute.

Please let me know how to get role included in the user type?

Many thanks,


Solution

  • Add type folder at the same level with auth.ts file. Then add a new file called next-auth.d.ts inside this folder.

    next-auth.d.ts

    import { DefaultSession } from "next-auth"
    
    declare module "next-auth" {
        interface User {
            //...
            role: string // <-- add this one
        }
    
        interface Session {
            user: User & DefaultSession["user"]
            expires: string
            error: string
        }
    }
    

    Now you should be able to access the role attribute using the following ways;

    Client Component

    "use client"
    
    import { useSession } from "next-auth/react" // you should wrap this component with SessionProvider in its parent component
    
    const ClientComponent = () => {
        const { data: session } = useSession()
        const role = session?.user?.role || undefined
    
        return (<></>)
    }
    

    Server Component

    import { auth } from "auth" // comes from your auth.ts file, NextAuth
    
    const ServerComponent = () => {
        const session = await auth()
        const role = session?.user?.role || undefined
    
        return (<></>)
    }