I manage to update my session serverside, with new user data, but event after assigning it to my session object in [...nextauth.js], my session client side remains the old one. It doesn't refresh, event if I use getSession()
.
This code works for the back-end :
callbacks.session = async function session({ session, token }) {
// we can fetch info from back end here to add it to the session
session.user = token.user;
session.jti = token.jti;
// If user is logged, we refresh his session
if (token?.user?.id) {
const url = routes.api.entities.shop.get.byId.build(token?.user?.id);
let apiResp = await axios.get(url, {});
session.user = { ...apiResp.data };
token.user = { ...apiResp.data };
}
return session;
};
How can I refresh the session in front-end ?
UPDATE 2023: There is now an official way to do it as of v4.22.1. See here and the updated docs
You now get an update function like this:
const { update } = useSession();
Note: update
fn doesn't sync up the session object between tabs, so if you have multiple tabs open, each tab needs to do reloadSession()
separately.
PREVIOUS ANSWER:
There is no easy official way to do it, it is still in discussion among contributors.
That said, there is a way. Next-auth does refresh session if you click on another tab, then on the one of your app. It happens, it is a javascript event we can reproduce.
So just define a method to do it :
const reloadSession = () => {
const event = new Event("visibilitychange");
document.dispatchEvent(event);
};
Call it, and .. you're done. Session did refresh.
reloadSession();
For more information, this behaviour comes from this part of the code
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