#A better way to get and store user guilds.

3 messages · Page 1 of 1 (latest)

marble lance
#

This is how i currently get and store user guilds:

import NextAuth from 'next-auth';
import DiscordProvider from 'next-auth/providers/discord';
import axios from 'axios';
import mongoConnect from '@util/mongo-connect';

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;
        try {
          const result = await axios({
            url: 'https://discord.com/api/v10/users/@me/guilds',
            method: 'GET',
            headers: {
              Authorization: `Bearer ${account.access_token}`,
            },
          })
          token.guilds = result.data;
        } catch (err) {
          token.guilds = [];
        }
      }
      return token
    },
    async session({ session, token }) {
      session.accessToken = token.accessToken;
      session.user.guilds = token.guilds
      return session  
    },
  },
})

i do it in the login callback so the guilds are only fetched upon login in. I do this to prevent api abuse and rate limiting from discord. But if the user is in a lot of servers i get a 431 where the headers are too large for the request. So i was wondering if anyone had any tips to store the guilds better.

deft crowBOT
#

🔎 This post has been indexed in our web forum and will be seen by search engines so other users can find it outside Discord

🕵️ Your user profile is private by default and won't be visible to users outside Discord, if you want to be visible in the web forum you can add the "Public Profile" role in id:customize

✅ You can mark a message as the answer for your post with Right click -> Apps -> Mark Solution
(if you don't see the option, try refreshing Discord with Ctrl + R)

azure walrus
# marble lance This is how i currently get and store user guilds: ```js import NextAuth from 'n...

Store only necessary data: Instead of storing all the guilds in the session, you could store only the necessary information. For example, you might only need the guild IDs and not the entire guild objects.

OR

Use a database: You could store the guilds in a database and only keep the user ID in the session. When you need the guilds, you can fetch them from the database using the user ID. This would require a database query each time you need the guilds, but it would keep your session data small.