I have implemented next-auth in Next.js project and I have this JWT and session:
export const { signIn, signOut, auth } = NextAuth({
...authConfig,
providers: [
CredentialsProvider({
async authorize(credentials) {
try {
const user = await login(credentials);
return user;
} catch (error) {
return null;
}
},
}),
],
callbacks: {
async jwt({ token, user }: { token: any; user: any }) {
if (user) {
token.id = (user as CustomUser).id;
token.username = (user as CustomUser).username;
token.img = (user as CustomUser).img;
token.isAdmin = (user as CustomUser).isAdmin;
}
return token;
},
async session({ session, token }: { session: any; token: any }) {
if (token) {
session.user = {
name: token.username,
image: token.img,
id: token.id,
isAdmin: token.isAdmin,
};
}
return session;
},
},
});
I am adding isAdmin
also in session so that I can use it in my code.
const session = await auth();
console.log(session?.user?.isAdmin)
And I am getting this error message:
Property 'isAdmin' does not exist on type '{ name?: string | null | undefined; email?: string | null | undefined; image?: string | null | undefined; }'.ts(2339)
Can someone tell me how to add more data in session?
This is my user:
{
_id: new ObjectId('random'),
username: 'admin',
email: '[email protected]',
password: '',
isAdmin: true,
isActive: true,
phone: '',
address: 'no ',
}
You need to create a types/next-auth.d.ts
file, and add the additional field you want to the session, as the doc shows:
import NextAuth, { DefaultSession } from "next-auth"
declare module "next-auth" {
interface Session {
user: {
isAdmine?: boolean
} & DefaultSession["user"]
}
}