Next-Auth Getting Discord Guilds
Answered
Shawty posted this in #help-forum
ShawtyOP
i was wondering if it would be possible to get a users guilds list after they log in through next-auth. i have added the guilds scope but have no clue where to start to get the users guilds as it is not provided in session.
next auth:
next auth:
// pages/api/auth/[...nextauth].ts
import NextAuth from 'next-auth';
import Discord from "next-auth/providers/discord";
import {CLIENT_ID, CLIENT_SECRET} from "../../../../Constants";
export default NextAuth({
providers: [
Discord({
clientId: CLIENT_ID,
clientSecret: CLIENT_SECRET,
authorization: {params: { scope: 'identify guilds', prompt: 'none' }}
}),
],
secret: "randomthings",
callbacks: {
async signIn(params) {
// Access user, account, and profile using params object
return true; // Allow sign-in
},
async redirect(params) {
// Access url and baseUrl using params object
const {url, baseUrl} = params;
return url.startsWith(baseUrl) ? url : baseUrl;
},
},
pages: {
error: '/error',
signIn: '/signin'
},
});Answered by @ts-ignore
9 Replies
@@ts-ignore you'll need to call discord api yourself with the token to get guilds
ShawtyOP
yes i finished that, but now is it possible to assign it to the session?
Answer
ShawtyOP
awesome. thank you man
ShawtyOP
hold up wait
its saying unauthorized
{ message: '401: Unauthorized', code: 0 }the token is undefined in session callback but isnt in signIn callback which is weird
ShawtyOP
jwt: async ({user, token, profile, account}) => {
// adding profile items to the token
if (user) {
token.profile = profile;
token.accessToken = account?.accessToken;
//the access token doesnt get set even when account?.accessToken is valid
token.refreshToken = account?.refreshToken;
}
return Promise.resolve(token);
},
session: async ({session, token}) => {
// copy token information into session
// @ts-ignore
session.user.accessToken = token.accessToken;
// @ts-ignore
session.user.refreshToken = token.refreshToken;
// @ts-ignore
session.user.profile = token.profile;
// add user's guilds into session
const res = await fetch('https://discord.com/api/v10/users/@me/guilds', {
method: 'GET',
headers: {
Authorization: `Bearer ${token.accessToken}`,
},
});
const data = await res.json();
console.log(data)
// @ts-ignore
session.user.profile.guilds = data;
return session;
},