Shahriyar
Shahriyar
TTCTheo's Typesafe Cult
Created by Shahriyar on 2/25/2023 in #questions
Will next-auth fetch the account information from API every-time I page refreshes or changes?
Or maybe useSession or getServerSession call? If it does how can I prevent this, because I am using discord provider and even with a 1/2 users using the website its getting 429 Ratelimited very often. Code of my auth.ts
const fetchGuilds = async (token: string, old_guilds?: Array<Guild>) => {
const response = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: `Bearer ${token}`,
},
})

if (!response.ok) {
if (response.status == 429) {
console.log("Got Rate limited") // I do get this message printed. Many times
return old_guilds ?? []
}

throw new Error(`${response.status}: ${response.statusText}`)
}

const guilds = (await response.json()) as Array<Guild>
return guilds
}

export const authOptions: NextAuthOptions = {
callbacks: {
session: ({ session, token }) => {
session.user = token.user
session.guilds = token.guilds

return session
},
jwt: async ({ token, user, account }) => {
if (account && user) {
token.guilds = await fetchGuilds(account.access_token as string, [])
token.user = user
return token
}

return token
},
},
providers: [
DiscordProvider({
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
authorization: {
params: {
scope: "identify guilds email",
state: crypto.randomBytes(16).toString("hex"),
prompt: "none",
},
},
checks: "state",
}),
],
pages: {
signIn: "/",
error: "/",
signOut: "/",
},
secret: process.env.JWT_SECRET,
}
const fetchGuilds = async (token: string, old_guilds?: Array<Guild>) => {
const response = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: `Bearer ${token}`,
},
})

if (!response.ok) {
if (response.status == 429) {
console.log("Got Rate limited") // I do get this message printed. Many times
return old_guilds ?? []
}

throw new Error(`${response.status}: ${response.statusText}`)
}

const guilds = (await response.json()) as Array<Guild>
return guilds
}

export const authOptions: NextAuthOptions = {
callbacks: {
session: ({ session, token }) => {
session.user = token.user
session.guilds = token.guilds

return session
},
jwt: async ({ token, user, account }) => {
if (account && user) {
token.guilds = await fetchGuilds(account.access_token as string, [])
token.user = user
return token
}

return token
},
},
providers: [
DiscordProvider({
clientId: env.DISCORD_CLIENT_ID,
clientSecret: env.DISCORD_CLIENT_SECRET,
authorization: {
params: {
scope: "identify guilds email",
state: crypto.randomBytes(16).toString("hex"),
prompt: "none",
},
},
checks: "state",
}),
],
pages: {
signIn: "/",
error: "/",
signOut: "/",
},
secret: process.env.JWT_SECRET,
}
20 replies