Users get logged out suddenly when their JWT access token expires. You want to refresh the token automatically without requiring re-login, but struggling with the implementation.
Implement a refresh token strategy: issue a short-lived access token (15min) and a long-lived refresh token (7 days). Intercept 401 responses and use the refresh token to get a new access token.
Step-by-Step Guide
Backend: Generate two tokens on login: accessToken (15min) and refreshToken (7 days)
Store refreshToken in httpOnly cookie (more secure than localStorage)
Frontend: On 401 response, call /refresh endpoint with refreshToken
If refresh succeeds, retry the original request with new accessToken
If refresh fails (expired/invalid), redirect to login
Use axios interceptors for automatic retry logic
Backend: Maintain a refreshToken whitelist in Redis for revocation support
Implement token rotation: issue new refresh token on each refresh
Found an issue with this solution?