When using Next.js with next-auth (auth.js) and a backend API (e.g., via tRPC), you may encounter a race condition during JWT token refresh. This typically happens when:
- Middleware checks the user's session and refreshes the access token if expired.
- Immediately after, the client (e.g., tRPC) makes a request using the (now stale) access token, triggering another refresh attempt.
- Both refresh attempts use the same old refresh token, but only the first one succeeds. The second fails with a 401 error because the refresh token has already been invalidated.