I have an callback inside my next auth api for session in which I'm getting user data from database, which works fine, but the session is called multiple times when the user is browsing the website, so it is overflowing the database. So I want to somehow modify the session, so it doesn't have to call the database every time, but store the user data in the session itself, either store the user data when signed in or first time the session is called, but I am unsuccessful so far.
This is function which works fine, but every time the session is called, there is a call to database:
async session({ session }) {
const { user: { image, email }} = session
const provider = image.includes('google') ? 'google' : 'facebook'
const account = (await getAccountsFromDb({ email, type: provider }))[0]
return account
},
I tried multiple things, f.e. this, but in the next session there is no session.account
async session({ session }) {
const { user: { image, email }} = session
const provider = image.includes('google') ? 'google' : 'facebook'
const account = (await getAccountsFromDb({ email, type: provider }))[0]
session.account = account
return account
},
I found out the answer, you can't change the session, but you can change the token inside jwt, so this code is working how I wanted now.
async jwt({ token }) {
const { picture, email } = token
const provider = picture.includes('google') ? 'google' : 'facebook'
if (!token.account) {
const account = (await getAccountsFromDb({ email, type: provider }))[0]
token.account = account
}
return token
},
async session({ token }) {
return token.account
},