nextauthjs / next-auth

Authentication for the Web.
https://authjs.dev
ISC License
24.67k stars 3.47k forks source link

Problem with typescript while extending user type #6455

Closed manuelsechi closed 1 year ago

manuelsechi commented 1 year ago

Question 💬

Hello, I extended the session returned in the callBack with some additional property from the db:

callbacks: { async session({ session, token, user }) { // Send properties to the client, like an access_token from a provider. session.user = { id: user.id, email: user.email, isAdmin: user.isAdmin, }; return session; } }

and I added them to next-auth.d.ts declare module "next-auth" { interface Session { user: { id: string; email: string; isAdmin: boolean; }; } }

unfortunatelly when building I am still getting an error, for the isAdmin field only. The others are fine: Type error: Property 'isAdmin' does not exist on type 'User | AdapterUser' Am I doing it correctly? I am also starting to wonder if this is the correct way to expose additional properties in the session. thanks

How to reproduce ☕️

Contributing 🙌🏽

No, I am afraid I cannot help regarding this

balazsorban44 commented 1 year ago

https://next-auth.js.org/getting-started/typescript

https://next-auth.js.org/getting-started/example#extensibility

manuelsechi commented 1 year ago

I am using an adapter (mongo) so I can't use JWT https://next-auth.js.org/configuration/options#session

Also I am basing my configurartion on this: https://next-auth.js.org/getting-started/typescript#module-augmentation

This is all working, I just don't get how to typehint the property isAdmin: user.isAdmin

balazsorban44 commented 1 year ago

using JWT is not a requirement for type safety. Mentioned in the docs under https://next-auth.js.org/getting-started/typescript#popular-interfaces-to-augment you need to augment the User interface for correct typing on the user object.