Next.js Discord

Discord Forum

AuthJS Discord Refresh Token

Unanswered
Atlantic menhaden posted this in #help-forum
Open in Discord
Atlantic menhadenOP
Hey :Wave:, i'm looking to implement refreshing the access token once it expires in my logic.

Can anyone assist me please :) Thank you!


import NextAuth from 'next-auth';
import DiscordProvider from 'next-auth/providers/discord';
import { Resend } from 'resend';
export default NextAuth({
  providers: [
    DiscordProvider({
      clientId: process.env.DISCORD_CLIENT_ID,
      clientSecret: process.env.DISCORD_CLIENT_SECRET,
      authorization: { params: { scope: 'identify guilds email guilds.join' } },
    }),
  ],
  callbacks: {
    async jwt({ token, account }) {

      if(token.email){
        const resend = new Resend(process.env.RESEND_KEY)

        await resend.contacts.create({
          email: token.email,
          firstName: token.name,
          unsubscribed: false,
          audienceId: process.env.RESEND_AUDIENCE
        }).catch((e) => console.error(e))

      }

      if (account) {
        
        token.accessToken = account.access_token;
        const apiUrl = `https://discord.com/api/v9/guilds/1065917561146974268/members/${account.providerAccountId}`;
        fetch(apiUrl, {
          method: 'PUT',
          headers: {
            'Authorization': `Bot ${process.env.DISCORD_TOKEN}`,
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            access_token: account.access_token,
          }),
        })
          .then(response => {
            if (!response.ok) {
              throw new Error(`Failed to add user to guild: ${response.statusText}`);
            }
            console.log('User added to guild successfully.');
          })
          .catch(error => {
            console.error(error);
          });

      }
      return token
    },
    async session({ session, token }) {
      session.user.id = token.sub;
      session.accessToken = token.accessToken;
      return session
    },
  },
})

0 Replies