How to retain profile information in JWT using callbacks when the callback runs again ?
I'm trying to add screen_name attribute from Twitter Oauth and am able to access it through the jet callback. But when I refresh the page, the jwt changes and doesn't include the profile attribute.
_JWT before signing in_
null
_JWT after signing in_
{
"name": "XXXX",
"email": "XXX",
"picture": "XXXX",
"profile": {
"id": "XXX",
"id_str": "XXX",
}
_JWT on page refresh_
{
"name": "XXXX",
"email": "XXX",
"picture": "XXXX",
}
This is the jwt callback
jwt: async (token, user, account, profile, isNewUser) => {
token.profile=profile;
return Promise.resolve(token);
},
I did a console log in the callback and found that on subsequent callbacks after the first one, the profile object is undefined. And the callback is run multiple time (twice after login and 4 times on refresh)
I'm not able to understand what's causing this. What I'm trying to do is to add few attributes from the profile to jwt token so those can be used for api queries from the server.
Documentation refers to searching through online documentation, code comments and issue history. The example project refers to next-auth-example.
If you take a look at the example you probably want to take a similar approach and only assign the profile the first time it is called (or if it's not set).
jwt: async (token, user, account, profile, isNewUser) => {
if (!token.profile) token.profile = profile
return Promise.resolve(token)
},
The jwt callback is called any time a session is accessed, so that you can easily rotate access tokens or other data in it before it's returned to the client, so what's happening is the .profile property is being overwritten with a null value on subsequent calls, as it's only available the fist time it's invoked after initial sign in.
That solved my case. Thank you!
Most helpful comment
If you take a look at the example you probably want to take a similar approach and only assign the profile the first time it is called (or if it's not set).
The
jwtcallback is called any time a session is accessed, so that you can easily rotate access tokens or other data in it before it's returned to the client, so what's happening is the .profile property is being overwritten with a null value on subsequent calls, as it's only available the fist time it's invoked after initial sign in.