how to get access token in api route from discord provider in next auth
Unanswered
American Chinchilla posted this in #help-forum
American ChinchillaOP
how can i get the access token in order to make request to discord api from next auth?
now lets say i have a route under
import { type NextAuthOptions } from "next-auth"
import DiscordProvider from "next-auth/providers/discord"
import { PrismaAdapter } from "@auth/prisma-adapter"
import { PrismaClient } from "@prisma/client"
const prisma = new PrismaClient()
const authOptions: NextAuthOptions = {
adapter: PrismaAdapter(prisma),
session: {
strategy: "jwt",
},
providers: [
DiscordProvider({
clientId: process.env.DISCORD_CLIENT_ID!,
clientSecret: process.env.DISCORD_CLIENT_SECRET!,
authorization: {
params: {
scope: "identify email guilds",
redirect_uri: process.env.REDIRECT_URI,
},
},
}),
],
}
export default authOptions this is my authOptions confignow lets say i have a route under
app/api/user/route.ts where i want to get the access token and make discord api request such as https://discord.com/api/v10/users/@me/guilds const res = await fetch(`https://discord.com/api/v10/users/@me/guilds`, {
headers: {
Authorization: `Bearer ${accessToken}`, # how to get accessToken
},
}); but for that i need access token provided by discord api19 Replies
@riský is this any help: <https://next-auth.js.org/v3/faq#how-do-i-get-refresh-tokens-and-access-tokens-for-an-oauth-account>
American ChinchillaOP
the problem is
callbacks: {
async jwt({ token, account }) {
console.log("Account", account)
return token
}
} when i create a jwt callbackand console log the account
its undefined
and yes i am logged in
can you manually assess the db with userid?
American ChinchillaOP
when i visit
/dashboard route import { getServerSession } from "next-auth"
import authOptions from "@/app/api/auth/options"
export default async function Dashboard() {
const session = await getServerSession(authOptions)
return (
<div>
<h1>{JSON.stringify(session)}</h1>
</div>
)
} it displays session data and it does indeed displays the data@riský can you manually assess the db with userid?
American ChinchillaOP
problem is user is also undefined from what i have tried
that is a whole another error... if your user is not defined... how should you get the oauth token...?
American ChinchillaOP

well then we are onto something
Account undefined
User undefined
Account undefined
User undefined async jwt({ token, account, user }) {
console.log("Account", account)
console.log("User", user)
return token
},results in console and callback used
American ChinchillaOP
@riský you maybe know how to solve it?
*i haven't tried discord with nextauth yet... *
@riský *i haven't tried discord with nextauth yet... *
American ChinchillaOP
hey so i managed to get it working but i have another problem now
i created my api route to return me guild objects from discord
and it works, but only when i query it manually by typing the api link to browser, now how can i get that data in component cause using this code
i created my api route to return me guild objects from discord
import { PartialGuild } from "@/app/types"
import { NextApiRequest } from "next"
import { getToken } from "next-auth/jwt"
import { NextResponse } from "next/server"
async function getGuilds(token: string): Promise<PartialGuild[]> {
const res = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: token,
},
})
return await res.json()
}
export async function GET(req: NextApiRequest) {
const token = await getToken({ req })
if (!token?.accessToken) {
return NextResponse.json({ error: "Unauthorized" }, { status: 401 })
}
const userGuilds = await getGuilds(`Bearer ${token.accessToken}`)
const botGuilds = await getGuilds(`Bot ${process.env.DISCORD_BOT_TOKEN}`)
const adminUserGuilds = userGuilds.filter(
({ permissions }) => (parseInt(permissions) & 0x8) === 0x8
)
const mutualGuilds = adminUserGuilds.filter((guild) =>
botGuilds.some((botGuild) => botGuild.id === guild.id)
)
return NextResponse.json({ adminUserGuilds, mutualGuilds })
} code for it ^and it works, but only when i query it manually by typing the api link to browser, now how can i get that data in component cause using this code
export default async function Dashboard() {
const res = await fetch("http://localhost:3000/api/user/getMutualGuilds")
const servers = await res.json()
console.log(servers)
return (
<div>
<h1>{JSON.stringify(servers, null, 2)}</h1>
</div>
)
} returns { "error": "Unauthorized" }do i need to make it a client component?
American ChinchillaOP
i moved it to #call to route handler from server component returns status 401 if you still want to help