How to Fix OAuth Token Expired / Invalid Grant Error
In this tutorial, you'll learn about How to Fix OAuth Token Expired / Invalid Grant Error. We cover key concepts, practical examples, and best practices to help you understand and apply this topic effectively.
The Problem
Your API client receives:
{
"error": "invalid_grant",
"error_description": "The authorization grant is invalid, expired, or revoked"
}
Or the API returns:
HTTP/1.1 400 Bad Request
{"error": "token_expired"}
The OAuth token or authorization code is invalid, expired, or was already used.
Quick Fix
1. Refresh the access token
Use the refresh token to get a new access token:
// OAuth token refresh
const refreshResponse = await fetch('https://auth.example.com/oauth/token', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
refresh_token: storedRefreshToken,
client_id: process.env.CLIENT_ID,
client_secret: process.env.CLIENT_SECRET
})
})
if (!refreshResponse.ok) {
// Refresh failed — user needs to re-authenticate
redirectToLogin()
}
const { access_token, refresh_token } = await refreshResponse.json()
2. Check the authorization code is single-use
Authorization codes can only be used once. If you reuse a code:
# Wrong — using the same code twice
curl -X POST https://auth.example.com/oauth/token \
-d "grant_type=authorization_code&code=abc123&client_id=app&client_secret=secret"
# Second call with the same code fails with invalid_grant
Always request a new authorization code for each login.
3. Check the grant type
The grant_type must match the OAuth flow:
# Wrong — authorization_code grant but no code
curl -X POST https://auth.example.com/oauth/token \
-d "grant_type=authorization_code&client_id=app&client_secret=secret"
# Right — include the code
curl -X POST https://auth.example.com/oauth/token \
-d "grant_type=authorization_code&code=valid_code&redirect_uri=https://app.com/callback&client_id=app&client_secret=secret"
4. Check the redirect URI
The redirect URI in the token request must match the one used in the authorization request:
// Wrong — mismatched redirect URIs
// Authorization request used: https://app.com/callback
// Token request uses:
fetch('https://auth.example.com/oauth/token', {
body: new URLSearchParams({
redirect_uri: 'https://app.com/auth/callback', // different!
code: 'abc123'
})
})
5. Handle PKCE (Proof Key for Code Exchange)
If using PKCE, ensure the code verifier matches:
// Generate and store code verifier
const codeVerifier = generateRandomString()
localStorage.setItem('code_verifier', codeVerifier)
// In token request, use the same verifier
fetch('https://auth.example.com/oauth/token', {
body: new URLSearchParams({
grant_type: 'authorization_code',
code: authCode,
code_verifier: localStorage.getItem('code_verifier'), // must match
redirect_uri: 'https://app.com/callback',
client_id: 'app'
})
})
6. Check token expiry time
Access tokens are short-lived (typically 15-60 minutes):
// Decode JWT to check expiry
function isTokenExpired(token) {
const payload = JSON.parse(atob(token.split('.')[1]))
return Date.now() >= payload.exp * 1000
}
Prevention
- Implement automatic token refresh before the access token expires.
- Store refresh tokens securely (httpOnly cookies or secure storage).
- Use PKCE for mobile and single-page applications.
- Monitor OAuth error rates in your application logs.
- Set up alerts for frequent invalid_grant errors.
Common Mistakes with oauth token expired
- Mixing let bindings with <- bindings in do notation, producing type errors
- Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
- Non-exhaustive pattern matches that compile with warnings then crash at runtime
These mistakes appear frequently in real-world API code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro