Skip to content

feat: implement silent access token refresh on 401#39

Merged
aji70 merged 2 commits into
MyFanss:mainfrom
libby-coder:feat/24-silent-token-refresh
Jun 21, 2026
Merged

feat: implement silent access token refresh on 401#39
aji70 merged 2 commits into
MyFanss:mainfrom
libby-coder:feat/24-silent-token-refresh

Conversation

@libby-coder

Copy link
Copy Markdown
Contributor

Summary

Closes #24

Implements silent access token refresh so expired tokens are transparently renewed without forcing the user to log in again.

  • src/lib/auth/token-store.ts — centralised read/write/clear for both access token and refresh token. Access token is mirrored to a cookie (for Next.js middleware); refresh token stays in localStorage only.
  • src/lib/auth/refresh.ts — single-flight refresh logic. Concurrent 401s queue behind one /auth/refresh call and all receive the same new token on success. On failure, all tokens are cleared and the user is redirected to /login.
  • src/lib/api/client.ts — 401 interceptor: on code: ACCESS_TOKEN_EXPIRED, calls refreshAccessToken() then retries the original request once (_retry flag prevents infinite loops).
  • src/lib/api/auth.tslogin() and signup() now persist the refresh token returned by the backend; logout() clears both tokens.
  • vitest.config.ts + unit tests — 24 tests covering queue behaviour (parallel 401s → single fetch), token rotation, and the full refresh-failure path (clear + redirect).
  • README.md — documents the cookie vs localStorage strategy and the silent refresh flow.

Acceptance criteria

  • Expired access token does not force login if refresh token is valid
  • Parallel 401s trigger only one refresh call
  • Invalid refresh token clears auth and redirects to /login
  • No infinite refresh loops (_retry flag)
  • Tokens are never logged to console in production (NODE_ENV guard)

Test plan

  • Run npm test — all 24 unit tests should pass
  • Start the dev server and log in; confirm normal navigation works
  • Manually expire the access token (shorten JWT TTL in backend) and confirm a protected request succeeds silently
  • Clear the refresh token from localStorage and confirm the next request redirects to /login

@aji70

aji70 commented Jun 21, 2026

Copy link
Copy Markdown
Contributor

@libby-coder resolve conflicts

@aji70 aji70 merged commit 6db9bb0 into MyFanss:main Jun 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Implement Silent Access Token Refresh on 401

2 participants