Discord OAuth2 login fails on the redirect_uri in an Express app
invalid_grantShort 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.
Fix it fast
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 below2Match what you see, then jump to its fix
- 1
The authorize link contains a raw https://... or http://... value after redirect_uri=The redirect_uri in the authorize link is not URL-encodedFix - 2
The 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
The 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
The callback receives ?code=... and the token request fails whatever redirect_uri you sendThe token request is sent as JSONFix
- 1
What does the error look like?
invalid_grantinvalid_requestThe 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
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/callback3Verify
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
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_URI3Verify
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
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
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
Security
Google sign-in stops with Error 400: redirect_uri_mismatch
redirect_uri_mismatch
Google compares the redirect_uri in your request with the authorized redirect URIs of that OAuth client, character by character.
3 causes, each with a fixBack end
Angular app shows 'Cannot GET /' when served by a Node.js server
Cannot GET /dashboard
Cannot GET / is Express saying no route or file matches the request.
3 causes, each with a fixBack end
Axios call from a React app comes back 404
404 (Not Found)
Status code 404 means a server answered, but it has nothing at that path.
3 causes, each with a fixBack end
bcrypt.hash throws 'data and salt arguments required'
Error: data and hash arguments required
The bcrypt package throws this when hash gets null or undefined for the password or for the salt.
4 causes, each with a fixBack end
bcryptjs rejects hash() or compare() with Illegal arguments
Error: Illegal arguments: string, undefined
bcryptjs checks the types of its two arguments and, when either is wrong, throws Illegal arguments followed by the typeof of the first and the second.
3 causes, each with a fixBack end
Express warns 'body-parser deprecated undefined extended'
body-parser deprecated undefined extended
The warning appears because urlencoded() was called without the extended option, which body-parser 1.x has warned about since version 1.4.0.
3 causes, each with a fix