Skip to content

How to Fix OAuth Token Expired / Invalid Grant Error

DodaTech Updated 2026-06-24 3 min read

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

  1. Mixing let bindings with <- bindings in do notation, producing type errors
  2. Overlapping type class instances that cause GHC to reject the program with ambiguous dispatch errors
  3. 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

### What causes "invalid_grant" in OAuth?

Common causes: expired authorization code, reuse of a single-use code, mismatched redirect URI, expired refresh token, or wrong grant type.

How long do authorization codes last?

Authorization codes typically expire within 1-10 minutes. If the user takes too long to complete the login flow, the code expires and you need a new one.

Can I use a refresh token indefinitely?

Some providers issue refresh tokens that never expire (Google offline access). Others expire after a period of inactivity. Check your provider's documentation for refresh token lifetime.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro