Skip to content

Instantly share code, notes, and snippets.

View Daanieeel's full-sized avatar

Daanieeel

View GitHub Profile
@Daanieeel
Daanieeel / next-auth-race-condition-fix.md
Last active September 22, 2025 02:07
Defeat race condition with next-auth jwt token refresh

Defeat race condition with next-auth jwt token refresh

Problem

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.