With NextAuth.js, how can I update a value inside the session object without signing out and in again?
For example, once a user signs in, I am using the URL stored in the session to display the avatar of the user.
I am also offering the user to change his avatar, so I would like the session.user.image
to be updated and persistent with the new path of the avatar. I am storing all the data in MongoDB. How can I achieve that? Right now the only solution is to ask the user to sign out and sign in again but that doesn't sound like an acceptable solution to me :)
My first idea would be to update this session object once the user updates his avatar but I can't find out how to do that.
import React from 'react'
import { signIn, signOut, useSession } from 'next-auth/client'
export default function Page() {
const [ session, loading ] = useSession()
return <>
{session && <>
<img src={session.user.image} />
<button onClick={signOut}>Sign out</button>
</>}
</>
}
To update any value stored in the session variable, start the session by calling session_start() function and then simply overwrite the vakue to update session variable. We just updated the value of userid in the session variable from 1 to 1111.
You can't set a server session variable directly from JS.
The best thing you can do is to modify data before sending session data to client. By using next-auth session callback we can easily do so.
callbacks: {
session: async (session, user) => {
const userDatabase = await CreateAccount.findOne({
email: user.email,
}); //finding user in DB.
const userData = {
name: userDatabase.username,
email: userDatabase.email,
image: userDatabase.avatar,
id: userDatabase._id,
} // creating payload
session.user = userData; //sending payload as session
return Promise.resolve(session);
},
},
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With