Next.js Discord

Discord Forum

how do i add role to the session in nextauth ?

Answered
American Wirehair posted this in #help-forum
Open in Discord
American WirehairOP
const user = await res.json()
user object have a value called role
how do i pass this to session ?

in session only name email and image comes

export const authOptions: NextAuthOptions = {
  adapter: PrismaAdapter(prisma) as Adapter,
  secret: process.env.NEXTAUTH_SECRET,
  session: { strategy: "jwt", maxAge: 24 * 60 * 60 },

  jwt: {
    secret: process.env.NEXTAUTH_SECRET,
    maxAge: 60 * 60 * 24 * 30,
  },

  pages: {
    signIn: "/login",
    // signOut: "/login",
    // error: "/login",
  },
  providers: [
    CredentialsProvider({
      type: "credentials",
      credentials: {},
      async authorize(credentials, req) {
        const { email, password } = credentials as {
          email: string
          password: string
        }

        const res = await fetch(
          `${process.env.NEXT_PUBLIC_NEXTAUTH_URL}/api/user/login`,
          {
            method: "POST",
            body: JSON.stringify({
              email,
              password,
            }),
            headers: {
              "Content-Type": "application/json",
            },
          }
        )
        const user = await res.json()

        if (res.ok && user) {
          return user
        } else {
          return null
        }
      },
    }),
  ],
  callbacks: {
    async jwt({ token, user }) {
      const isSignedIn = user ? true : false

      if (isSignedIn) {
        token.accessToken =
          user.id.toString() + "-" + user.email + "-" + user.name
      }

      return await token
    },
    async session({ session, token, user }) {
      if (user !== null) {
        session.user = user
      }
      return await session
    },
  },
}
Answered by Komondor
This is how I have mine working. I added some role stuff as an example
async session({ session, token }) {
      
  session.user.id = token.sub;

  // get user from database
  const user = getUserFromDb();
  session.user.role = user.role;

  return session;
},
View full answer

6 Replies

American WirehairOP
anyone help pls
American WirehairOP
is this server dead?
Komondor
In that session callback, I see you are setting session.user. You can also set other things, such as role.
Komondor
This is how I have mine working. I added some role stuff as an example
async session({ session, token }) {
      
  session.user.id = token.sub;

  // get user from database
  const user = getUserFromDb();
  session.user.role = user.role;

  return session;
},
Answer
Komondor
I think I had to do this towards the top of that file to tell nextauth about the other stuff in the session token

declare module 'next-auth' {
  interface User {
    id: string;
  }

  interface Session extends DefaultSession {
    user?: User;
  }
}


So you will probably have this, if your role is a string

declare module 'next-auth' {
  interface User {
    id: string;
    role: string;
  }

  interface Session extends DefaultSession {
    user?: User;
  }
}
Komondor
The NextAuth docs show setting other things in the session
https://next-auth.js.org/configuration/callbacks