sessionjwtnext-auth

How to extend session.user in Auth.js?


Below follows a question on Auth.js (formerly NextAuth.js).

Background:

I am using the jwt session strategy, but would still like to store more information about a user on session.user, than what is saved on the jwt by default (default: name, email, image). For instance, I would like to add a role and and the organization they belong to. Following the docs, I have done module augmentation to extend the types of the jwt and session.user.

Goal:

I have read the section on Extending the Session in the docs, but it only explains how to get the extra session data if it comes from the provider (i.e. Google). In my case, I would like to do a lookup in a database, in order to augment session.user.

Question:

How can the above goal be achieved? Do I just do the database call inside the provider's profile callback, or inside the jwt callback?

Since I am anyways calling the database on login/logout, am I loosing the leanness/scalability benefits of the jwt session strategy, and might just as well use the database session strategy directly?


Solution

  • Quite possible

    Let's say you are going to add role prop.

    To be able to use our own session props, we need to add type folder at the root level of the project and put next-auth.d.ts file inside it

    import { DefaultSession } from "next-auth"
    
    declare module "next-auth" {
        interface User {
            id: string
            email: string
            role: string
        }
    
        interface Session {
            user: User & DefaultSession["user"]
            expires: string
            error: string
        }
    }
    

    As to callback functions

    async jwt({ token, user, account, trigger, session }) {
        if (account && user) {
            token.id = user.id
            token.email = "admin@admin.com"
            token.role = "Administrator"
        }
        return token
    },
    async session({ session, token }) {
        return {
            ...session,
            user: {
                ...session.user,
                id: token.id as string,
                email: token.email as string,
                role: token.role as string,
            }
        }
    }
    

    That's it!