What's the difference between additionalFields and customSession?
Hi, it's a bit unclear to me the difference between additionalFields and customSession plugin.
I am trying to migrate an app using Prisma, and I have a User schema that have many other fields.
My understanding is that I should add those fields under user.additionalFields in
auth.ts
. However, most of those fields are many to many relationships with other tables, so I cannot use the proper type in additionalFields.
For example, I have a table Role, and I want to be able to retrieve roles in my session, so should I do this?
I also a Preference table, and I want to have the user preferences in the session. Should I also add the preferences in the additionalFields?
That way of extending the User schema seems a bit weird to me.
Otherwise, I have tried to add the customSession plugin, like this:
Which is the way I would like to store those data in my session, the problem here is that the types are not inferred unless I also add additionalFields.
I guess my questions would be:
How can I simply add custom fields to my session that are also inferred?
Could you explain the difference between additionalFields and customSession?
Is there a way to have many-to-many relationships in additionalFields?6 Replies
Additinoal fields are just fields that needs to be added in the session table directly. While custom session is a custom fuction that changes the response of
/get-session
this is useful if you want to query and return additinoal data whenever you call getsession.
Regarding type inference, on the server it should automatically ifner it but for the client check the doc linked below.
https://www.better-auth.com/docs/concepts/typescript#inferring-additional-fields-on-clientTypeScript | Better Auth
Better Auth TypeScript integration.
@bekacru by doing that, additionalFields are not typed, any suggestions?
is it not inferring the additional fields on the user table?
@bekacru no, adding the
customSession
actually adds the userPermission
object to my response, but an error is reported in the code (example: )
same for all additionalFields declared, btw
yeah the issue is, it's not able to infer your additional types since both the custom session and your additional fields are defined in the same object. check the caveats section here on how to fix it
https://www.better-auth.com/docs/concepts/session-management#customizing-session-response
Session Management | Better Auth
Better Auth session management.
I've already tried this, but I can give it another try
Should I simply move the
customSession
to export const auth
?
Found where I went wrong in caveats, thank you a lot!