Loop
Loop
DIAdiscord.js - Imagine an app
Created by Loop on 9/15/2023 in #djs-questions
Using @discordjs/rest to make requests using Bearer access token
Is it possible to use the rest functions to fetch data for users with their OAuth access_token? Currently I've tried the following, the only option I got working was with a self made API call, I was wondering if I could utilize the REST class instead. DISCORD_CLIENT_TOKEN is the token for my bot/application accessToken is the bearer token for the user
const rest = new REST({ version: "10" }).setToken(DISCORD_CLIENT_TOKEN);
const rest2 = new REST({ version: "10" }).setToken(accessToken);

// Returns guilds for the application and not the user that the access token is for
const guilds = await rest.get(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

// DiscordAPIError[0]: 401: Unauthorized
const guilds2 = await rest2.get(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

// Error: Cannot use relative URL (/users/@me/guilds) with global fetch — use `event.fetch` instead: https://kit.svelte.dev/docs/web-standards#fetch-apis
const guilds3 = await fetch(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((res) => res.json());

// This works
const guilds4 = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((res) => res.json());
const rest = new REST({ version: "10" }).setToken(DISCORD_CLIENT_TOKEN);
const rest2 = new REST({ version: "10" }).setToken(accessToken);

// Returns guilds for the application and not the user that the access token is for
const guilds = await rest.get(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

// DiscordAPIError[0]: 401: Unauthorized
const guilds2 = await rest2.get(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
});

// Error: Cannot use relative URL (/users/@me/guilds) with global fetch — use `event.fetch` instead: https://kit.svelte.dev/docs/web-standards#fetch-apis
const guilds3 = await fetch(Routes.userGuilds(), {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((res) => res.json());

// This works
const guilds4 = await fetch("https://discord.com/api/users/@me/guilds", {
headers: {
Authorization: `Bearer ${accessToken}`,
},
}).then((res) => res.json());
6 replies