I am building a multi-tenant NextJS app that uses next-auth for account authentication, tRPC for API's, and postgresql for a data store.
I am trying to find a way to dynamically update/set/mutate a session value based on some client-side interaction
The approach I am taking is similar to the one described in this article:
- a
User
is granted access to anOrganization
through aMembership
- a
User
may have aMembership
to >1Organization
- a
User
can change whichOrganization
they are "logged in" to through some client-side UI.
When the user authenticates, I want to:
- set
session.user.orgId
to some orgId (if they belong to an org)
When the user changes the org they are accessing through some client-side UI, I want to:
- update
session.user.orgId = newOrgId
(validating they have proper permissions before doing so, of course).
I have searched the net for ways to update/mutate session values, and as far as I can tell, it's only possible using next-auth's callbacks:
...
callbacks: {
async session({ session, user, token }) {
// we can modify session here, i.e `session.orgId = 'blah'`
// or look up a value in the db and attach it here.
return session
},
...
}
However, there is no clear way to trigger this update from the client, outside of the authentication flow. I.E, if the user clicks to change their org in some UI, how do I validate the change + update the session value, without requiring the user to re-authenticate?