#Store User Guilds Once Upon Authentication

1 messages · Page 1 of 1 (latest)

vivid salmon
#

I had my user guild fetch function inside a component which would rerun the fetch upon every refresh or mount. I tried adding it to the session callback but it achieves the same outcome. I'm a big of a beginner so if anyone could help that would be great.

import NextAuth from 'next-auth';
import DiscordProvider from 'next-auth/providers/discord';
import axios from 'axios'

export default NextAuth({
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET,
      authorization: { params: { scope: 'identify guilds email' } },
    }),
  ],
  callbacks: {
    async jwt({ token, account }) {
      if (account) {
        token.accessToken = account.access_token;
      }
      return token
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken;
      console.log(session)
      if (session.user.guilds) {
        return session;
      } else {
        try {
          const result = await axios({
            url: 'https://discord.com/api/v10/users/@me/guilds',
            method: 'GET',
            headers: {
              Authorization: `Bearer ${token.accessToken}`,
            },
          })
          session.user.guilds = result.data;
        } catch (err) {
          session.user.guilds = [];
        }
        return session;
      }
    },
  },
})
dim muskBOT
#

Hi @vivid salmon. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave:

#

Based on the information provided in the extracts, it seems like you're trying to store user guilds upon authentication using NextAuth.js and DiscordProvider. Your current approach is to fetch the user guilds in the session callback and store them in the session object.

However, it's important to note that the session callback is called whenever a session is checked, which can happen frequently. This could explain why you're seeing the fetch operation being performed on every refresh or mount.

Unfortunately, the extracts do not provide a direct solution to your problem. However, they do provide some insights into how NextAuth.js and its callbacks work. For instance, the jwt callback is only called during sign in or when a session is updated (source: Github Issue (closed): In API folder if i pass data in body, it's not recognizing headers and returning as null > Original post Part 1 (https://github.com/vercel/next.js/issues/50160)). You might want to consider fetching the user guilds in the jwt callback instead of the session callback.

Remember to handle errors and edge cases appropriately. For example, in the session callback, you're setting session.user.guilds to an empty array if the fetch operation fails. You might want to do something similar in the jwt callback.

Please refer to the NextAuth.js documentation (https://next-auth.js.org/getting-started/introduction) for more information on how to use NextAuth.js and its callbacks.

Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: