Maaz Zindani

Loading the index…

↑↓ move↵ openesc close4072 pages
Node.js, PHP and APIs

Discord OAuth2 login fails on the redirect_uri in an Express app

Errorinvalid_grant

Short answer

Discord compares the redirect_uri you send with the URL you registered for the application, and the token step must repeat the same value as the authorization step. In Express the usual causes are an unencoded value in the authorize link, a registered URL that differs by one character, two different strings in the two steps, or a JSON token request.

  • Applies to Express 5, Node.js 22, Discord OAuth2 authorization code grant
  • Updated
  • By Maaz Zindani, Senior Software Engineer

Fix it fast

  1. 1Find out which cause you have

    Print the redirect_uri your code uses in the authorize link and in the token request, then put both next to the value registered for the application in the Discord Developer Portal. All three must be the same string.

    console.log('authorize:', process.env.DISCORD_REDIRECT_URI);
    // and the same constant in the token request below
  2. 2Match what you see, then jump to its fix

    1. 1The authorize link contains a raw https://... or http://... value after redirect_uri=The redirect_uri in the authorize link is not URL-encodedFix
    2. 2The error appears at the authorize step, and the registered list does not hold the exact string your code sendsThe registered URL and the one sent differ by a characterFix
    3. 3The authorize page and the callback work, and the token request answers with invalid_grantThe token request sends a different redirect_uri than the authorize stepFix
    4. 4The callback receives ?code=... and the token request fails whatever redirect_uri you sendThe token request is sent as JSONFix

What does the error look like?

  • invalid_grant
  • invalid_request
  • The Discord authorize page does not accept the redirect_uri, so the user never reaches your callback

Cause 1 of 4

The redirect_uri in the authorize link is not URL-encoded

1Check

Discord's documentation shows the redirect_uri parameter as the registered URL, URL-encoded (https%3A%2F%2F...). A value pasted in raw is not the documented form.

console.log(authorizeUrl);

2Fix

Encode the value with encodeURIComponent when you build the link, and keep the scope separator as %20.

const redirectUri = encodeURIComponent(process.env.DISCORD_REDIRECT_URI);
const url =
  'https://discord.com/oauth2/authorize' +
  `?response_type=code&client_id=${process.env.DISCORD_CLIENT_ID}` +
  `&scope=identify&redirect_uri=${redirectUri}&state=${state}`;
res.redirect(url);

3Verify

The link in the address bar shows redirect_uri=https%3A%2F%2F... (or http%3A%2F%2F... for local testing).

curl -sI http://localhost:3000/auth/discord | grep -i '^location'

Confirmed by docs.discord.com

Did this fix it?

Cause 2 of 4

The registered URL and the one sent differ by a character

1Check

Discord says redirect_uri is whatever URL you registered for the application, and OAuth 2.0 (RFC 6749) tells a server that holds a full registered redirect URI to compare it as a plain string. So http against https, a trailing slash, a different port, a different path, or localhost against 127.0.0.1 all count as a different URL.

console.log(JSON.stringify(process.env.DISCORD_REDIRECT_URI));

2Fix

Register every URL you really use in your application's settings in the Discord Developer Portal, one entry per environment, and read the value from one environment variable so the code never retypes it.

# .env
DISCORD_REDIRECT_URI=https://example.com/auth/discord/callback

3Verify

Start the login again from the same environment and the authorize page opens without an error.

curl -sI https://example.com/auth/discord | grep -i '^location'

Confirmed by rfc-editor.org

Did this fix it?

Cause 3 of 4

The token request sends a different redirect_uri than the authorize step

1Check

In the token exchange Discord asks for the redirect_uri associated with this authorization. RFC 6749 requires the value to be identical to the one in the authorization request, and defines invalid_grant for a code issued with a different redirection URI.

grep -rn "redirect_uri" --include="*.js" --exclude-dir=node_modules .

2Fix

Use the same constant in both places. Do not type the value a second time in the token code.

const REDIRECT_URI = process.env.DISCORD_REDIRECT_URI;
// authorize link: encodeURIComponent(REDIRECT_URI)
// token body:     redirect_uri: REDIRECT_URI

3Verify

Run the whole login once; the token request returns a success status instead of invalid_grant.

console.log(tokenRes.status);

Confirmed by rfc-editor.org

Did this fix it?

Cause 4 of 4

The token request is sent as JSON

1Check

Discord's token URL accepts only application/x-www-form-urlencoded; JSON content is not permitted and returns an error. In Node.js a plain object given to a JSON helper (or an HTTP client that defaults to JSON) breaks this step.

grep -rn "oauth2/token" --include="*.js" --exclude-dir=node_modules .

2Fix

Send URLSearchParams as the body with the form content type, and authenticate with HTTP Basic using the client ID and secret, as in Discord's example.

const basic = Buffer.from(
  `${process.env.DISCORD_CLIENT_ID}:${process.env.DISCORD_CLIENT_SECRET}`
).toString('base64');

const tokenRes = await fetch('https://discord.com/api/oauth2/token', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    Authorization: `Basic ${basic}`,
  },
  body: new URLSearchParams({
    grant_type: 'authorization_code',
    code: req.query.code,
    redirect_uri: REDIRECT_URI,
  }),
});

3Verify

The token request returns a success status instead of an error.

console.log(tokenRes.status, await tokenRes.json());

Confirmed by docs.discord.com

Did this fix it?

How do I stop it coming back?

  • Keep one DISCORD_REDIRECT_URI per environment in configuration, and register exactly that string in the Developer Portal before you deploy.
  • Build the authorize link with encodeURIComponent and the token body with URLSearchParams; never concatenate raw values.
  • Send a state value with the authorize link and compare it on the callback, as Discord recommends.
  • Log the status and body of every failed token response; the error code tells you which rule was broken.

Sources

How was this page made?

I drafted this page with AI assistance from the official documents listed under Sources. Every cause above names the document that confirms it. I have not reproduced this fix on a machine of my own yet, so read it as documented guidance, not a test report. Found a mistake? Tell me.

Which stack is behind this page?

Projects of mine built on the same technologies:

Related fixes

Next step

Want this handled for good?

I look after servers, apps and releases end to end. Tell me what keeps breaking.