How to Handle Expired Token in REST API Calls
expired token, detect the token expiration error from the API response, then prompt the user to re-authenticate or automatically refresh the token using a refresh token. This ensures your app stays secure and users don’t lose access unexpectedly.Why This Happens
Tokens expire because they are designed to be valid only for a limited time to protect security. When you use an expired token to access a REST API, the server rejects it and returns an error, usually a 401 Unauthorized status with a message about token expiration.
fetch('https://api.example.com/data', { headers: { 'Authorization': 'Bearer expired_token_here' } }) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
The Fix
Check the API response for an expired token error. When detected, use a refresh token to get a new access token without asking the user to log in again. Then retry the original request with the new token.
async function fetchData() { let accessToken = 'expired_token_here'; try { let response = await fetch('https://api.example.com/data', { headers: { 'Authorization': `Bearer ${accessToken}` } }); if (response.status === 401) { const errorData = await response.json(); if (errorData.error === 'token_expired') { // Refresh the token const refreshResponse = await fetch('https://api.example.com/refresh', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ refreshToken: 'your_refresh_token_here' }) }); const refreshData = await refreshResponse.json(); accessToken = refreshData.accessToken; // Retry original request with new token response = await fetch('https://api.example.com/data', { headers: { 'Authorization': `Bearer ${accessToken}` } }); } else { throw new Error('Unauthorized'); } } const data = await response.json(); console.log(data); } catch (error) { console.error('Error:', error.message); } } fetchData();
Prevention
To avoid expired token issues, always implement token refresh logic in your client app. Use short-lived access tokens with longer-lived refresh tokens. Also, handle 401 errors gracefully by prompting users to log in again if refresh fails. Keep tokens secure and never expose them in URLs or logs.
Related Errors
Other common token-related errors include:
- Invalid token: The token is malformed or tampered with.
- Revoked token: The token was manually invalidated by the server.
- Insufficient scope: The token lacks permission for the requested resource.
Fixes usually involve re-authentication or requesting proper permissions.