Search code examples
javascripttypescriptdiscordoauthdiscord.js

How to fix Discord OAuth2 returning "Invalid 'code' in request'"?


I'm currently trying to build an authentication app however I keep getting Invalid "code" in request when trying to get a refresh token from the code discord provided.

Here's a snapshot of my request:

const response = await fetch(`https://discord.com/api/oauth2/token`, {
    method: "POST",
    headers: {
        "Content-Type": "application/x-www-form-urlencoded"
    },
    body: new URLSearchParams({
        grant_type: "authorization_code",
        code: code,
        redirect_uri: redirectURI,
        client_id: process.env.DISCORD_CLIENT_ID as string,
        client_secret: process.env.DISCORD_CLIENT_SECRET as string,
        scope: 'identify email'
    }).toString()
})

I'm using exactly the same scopes, redirect uri and code. I have ensured that my credentials are correct and the JSON returned is { error: 'invalid_grant', error_description: 'Invalid "code" in request.' }

What's the solution to this? Many thanks.


Solution

  • The issue went away after not converting the body search params to a string and not including the scope in the body.