Next.js Discord

Discord Forum

Struggling to get my NextJS 14 App router site to work with Discord's API

Unanswered
Doc posted this in #help-forum
Open in Discord
DocOP
So I've been using Next-Auth (until today using JWT with Discord's OAuth2 provider, but now I've added the UpstashRedisAdapter) and the main issue I've been having is fetching a logged in user's Discord guilds and being unable to keep my application from sending out requests to Discord's api/users/@me/guilds endpoint too quickly and then having my application throw errors when it tries to take a rate limited request and filter it for servers that the user has the ability to manage.

I'm just working on building a dashboard for users to configure my Discord bot in their server/servers.

## My /app/api/guilds/route.ts:
import { getManageableGuilds } from '@/lib/discord'
import { Guild } from '@/types/discord'
import { NextRequest, NextResponse } from 'next/server'

export async function GET(req: NextRequest) {
    const session = req.headers.get('Authorization')

    if (session) {
        const response = await fetch('https://discord.com/api/users/@me/guilds', {
            headers: {
                Authorization: `${session}`
            }
        })

        const guilds = (await response.json()) as Guild[]
        const manageableGuilds = getManageableGuilds({ guilds })
        return NextResponse.json(manageableGuilds, { status: 200 })
    }

    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}

The getManageableGuilds function is the one that's doing the filtering, but obviously you can't filter through a Guild[] object when the response is a rate limit response.

## This here is the relevant portion of my /bot/page.tsx file:
export default async function BotPage() {
    const session = await auth()

    if (!session || !session.user.accessToken) {
        return <AccessDenied />
    }

    const res = await fetch(`${process.env.NEXTAUTH_URL}/api/guilds`, {
        headers: {
            Authorization: `Bearer ${session.user.accessToken}`
        }
    })

    if (res.status !== 200) {
        return (
            <div>
                ...
            </div>
        )
    }

## And here's the important parts of my auth.ts file for next-auth:
const redis = Redis.fromEnv()

export const config = {
    adapter: UpstashRedisAdapter(redis) as Adapter,
    session: { strategy: 'database' },
    providers: [
        Discord(...)
    ],
    callbacks: {
        async signIn({ user, account }) {
            if (account) {
                // Add access token to user
                user.accessToken = account.access_token
                return true
            }
            return false
        },
        async redirect({ url, baseUrl }) {
            // Allows relative callback URLs
            if (url.startsWith('/')) return `${baseUrl}${url}`
            // Allows callback URLs on the same origin
            else if (new URL(url).origin === baseUrl) return url
            return baseUrl
        }
    },
    theme: {
        logo: '/logo.png',
        colorScheme: 'dark'
    },
    pages: {
        signIn: '/',
        error: '/api/auth/error'
    }
} satisfies NextAuthConfig

export const { handlers: { GET, POST }, auth, signIn, signOut } = NextAuth(config)


I'm still going through all the documentation working to find the best way to use Upstash's Redis service to store a user's guilds for their session (considering the 1s rate limiting issue and how it's always throwing errors any time my /bot page gets reloaded too quickly) and I figured now might be a good time to just post here and see about getting some advice/suggestions.

TL;DR: Trying to setup a Discord bot dashboard using Next-Auth, NextJS 14 and Upstash Redis but struggling to figure out the best way to handle fetching a user's guilds from Discord's API (without getting rate limited) to filter through them and show the ones that the user can manage on the main page for the panel.

Thanks for any help you might be able to provide.

0 Replies