Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update session values without signing out?

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>
    </>}
  </>
}
like image 680
Armel Avatar asked Dec 14 '20 11:12

Armel


People also ask

How do I update my session data?

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.

Is it possible to set session in JavaScript?

You can't set a server session variable directly from JS.


1 Answers

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);
      },
    },
like image 68
CODING IN BLOOD Avatar answered Oct 03 '22 07:10

CODING IN BLOOD