NextAuth and MongoDBAdapter with user roles
Unanswered
Acies posted this in #help-forum
AciesOP
Hello, I have a nextjs app with nextauth.js and a mongodpadapter which writes all new sign ins to my database. This part is working without any problems. Now what I need is to be able to give my users roles, i need a Customer, Customer Service Rep and Admin role.
My idea is to extend the MongoDBAdapter making a new field in user called "role" which defaults to "customer". I found some stuff online aswell as on GPT but I can't get it to work. Below is this code that I currently have, which is supposed to implement a callback which gives a new role field.
I'm looking for either a way to make this role populate in my DB, but im also open to other suggestions for how to store user role. Thanks for the help.
My idea is to extend the MongoDBAdapter making a new field in user called "role" which defaults to "customer". I found some stuff online aswell as on GPT but I can't get it to work. Below is this code that I currently have, which is supposed to implement a callback which gives a new role field.
I'm looking for either a way to make this role populate in my DB, but im also open to other suggestions for how to store user role. Thanks for the help.
import NextAuth from "next-auth"
import GithubProvider from "next-auth/providers/github"
import GoogleProvider from "next-auth/providers/google"
import { MongoDBAdapter } from "@auth/mongodb-adapter"
import clientPromise from "./lib/mongodb"
//auth options here
export default NextAuth({
...authOptions, // Spread the authOptions object
adapter: MongoDBAdapter(clientPromise), // Pass the clientPromise directly to MongoDBAdapter
callbacks: {
async session({ session, user }) {
// Add the user's role to the session object
session.user.role = user.role ?? "customer";
return session;
},
async createUser(user) {
console.log("createUser", user)
// Here, you modify the user object to include the role
// No need to manually insert the user into the database; NextAuth and the adapter handle it
user.role = "customer";
return user;
}
},
})
3 Replies
AciesOP
Ideally I'd like to extend the user model, but I can't figure out how to
Short-tailed Albatross
hi hi
did you get error=missingCSRF at some point with your application ?