we are doing the auth on our website using next-auth. When the user is logged in, we receive the access token and the expiration date. Then, according to our BE model, we need to make other calls to get the user’s information, such as email, name, address, etc. Currently, we receive user details in the session callback:
const getAccessToken = (loginData) => ({
accessToken: loginData?.token,
accessTokenExpires: new Date(loginData?.expires).getTime(),
});
callbacks: {
async jwt({ token, user}) {
// Initial login
if (user) {
return {
...token,
...getAccessToken(user),
};
}
// Return previous token if the access token has not expired yet
if (Date.now() < token.accessTokenExpires) {
return token;
}
const validatedToken = await validateToken(token.accessToken);
if (!validatedToken.ok) {
return {
...token,
error: 'RefreshAccessTokenError'
}
return {
...tokenFromNextAuth,
...getAccessToken(validatedToken),
};
},
async session({ session, token})
session.user = await fetchUserData(token.accessToken);
return session;
},
Is it the right place to do so? Because we can not add a condition here to check if the user object already contains some of the fields and prevent this call every time, the session user contains undefined fields each time after calling the JWT callback:
if (!session?.user?.name) { // We can not do that
session.user = await fetchUserData(token.accessToken);
}
return session;
Maybe we need to put the fetchUserData in the JWT callback with the same condition? Could someone please help with it and give us advice? Thank you.
Expected result: try to minimize the fetchUserData call
Anna is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.