feat: implement JWT token auto-refresh mechanism#37
Merged
Conversation
- Add TokenRefreshService with singleton pattern for managing refresh requests - Implement request queue to prevent multiple simultaneous refresh attempts - Add Axios response interceptor for automatic 401 error handling - Create refreshToken method in ApiService using direct axios call - Add refreshToken async thunk to Redux auth slice with proper state management - Create useTokenRefresh custom hook for easy access to refresh functionality - Add TokenRefreshExample component demonstrating the auto-refresh features - Implement token expiration detection using JWT payload parsing - Add comprehensive error handling and fallback to login on refresh failure - Ensure localStorage synchronization for token persistence - Support TypeScript with proper typing throughout the implementation This provides seamless JWT token management with automatic refresh on API failures.
|
@gelluisaac is attempting to deploy a commit to the Fishon Amos' projects Team on Vercel. A member of the Team first needs to authorize it. |
|
@gelluisaac Great news! 🎉 Based on an automated assessment of this PR, the linked Wave issue(s) no longer count against your application limits. You can now already apply to more issues while waiting for a review of this PR. Keep up the great work! 🚀 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
closes #16
Summary
This PR implements a comprehensive JWT token auto-refresh system that automatically handles token expiration and renewal, ensuring seamless user authentication without requiring manual intervention.
Problem Solved
Previously, when JWT tokens expired, users would experience authentication failures and need to manually re-login. This implementation automatically detects expired tokens and refreshes them in the background, providing a smooth user experience.
Changes Made
🏗️ Core Services
src/services/tokenRefreshService.ts)🔧 API Service Enhancements
src/services/api.ts)refreshToken()method for manual refresh capabilities📦 Redux Store Integration
src/store/slices/authSlice.ts)refreshTokenasync thunk for centralized state management🪝 Custom Hooks
src/hooks/useTokenRefresh.ts)🎨 UI Components
src/components/examples/TokenRefreshExample.tsx)Features Implemented
✅ Automatic Token Refresh - Background token renewal on 401 errors
✅ Request Queue Management - Prevents duplicate refresh requests
✅ Token Expiration Detection - JWT payload parsing for proactive refresh
✅ Redux State Management - Centralized authentication state
✅ Error Handling - Comprehensive error handling with user feedback
✅ TypeScript Support - Full type safety throughout the system
✅ LocalStorage Sync - Persistent token storage and cleanup
✅ Retry Mechanism - Automatic retry of failed requests after refresh
✅ Security Best Practices - No circular dependencies, secure token handling
How It Works
Automatic Flow
/auth/refreshendpointManual Flow
useTokenRefresh()hookisTokenExpired()checks JWT payloadrefreshToken()forces token renewalrefreshTokenIfNeeded()only refreshes if expiredUsage Examples
Automatic Usage (Recommended)
Manual Usage with Hook
Redux Dispatch
Security Considerations
🔒 Circular Dependency Prevention: Refresh endpoint uses direct axios call
🔒 Request Deduplication: Queue prevents multiple simultaneous refreshes
🔒 Token Validation: JWT expiration checking before API calls
🔒 Secure Storage: Proper localStorage management with cleanup
🔒 Error Boundaries: Comprehensive error handling prevents data leaks
Testing
The implementation includes:
Performance Impact
⚡ Minimal Overhead: Only activates on 401 errors
⚡ Request Deduplication: Prevents unnecessary API calls
⚡ Efficient Queue Management: Non-blocking refresh operations
⚡ Optimized State Updates: Minimal Redux re-renders
Breaking Changes
None. This is a non-breaking addition that enhances existing authentication functionality.
Migration Guide
No migration required. Existing code will automatically benefit from the new token refresh mechanism.
Future Enhancements
Testing Checklist
Impact
This implementation significantly improves user experience by:
The JWT token auto-refresh mechanism is now fully integrated and ready for production use.