-
Notifications
You must be signed in to change notification settings - Fork 27
Nextjs Middleware: simplified JWT token verification and legacy token migration #4169
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
📝 WalkthroughWalkthroughReworks middleware token handling: verification now returns boolean, refresh always attempts when refresh token exists, transient errors preserve tokens, legacy migration is a fallback, and token cleanup is consolidated into a single sequential flow before locale handling. ApiError is introduced for client-error classification. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Middleware
participant TokenVerifyAPI as "Verify API"
participant TokenRefreshAPI as "Refresh API"
participant CookieMgr as "AuthCookieManager"
Client->>Middleware: request (cookies: access?, refresh?, legacy?)
Middleware->>CookieMgr: read access token
alt access token exists and not expired
Middleware->>TokenVerifyAPI: verify access token
TokenVerifyAPI-->>Middleware: valid / invalid
alt valid
Middleware->>CookieMgr: keep tokens (session established)
else invalid
Middleware->>CookieMgr: read refresh token
alt refresh token exists
Middleware->>TokenRefreshAPI: refresh tokens
TokenRefreshAPI-->>Middleware: success / client-error / transient-error
alt success
Middleware->>CookieMgr: apply new tokens
else client-error
Middleware->>CookieMgr: clear JWT & legacy tokens
else transient-error
Middleware->>CookieMgr: preserve existing tokens (log)
end
else no refresh token
Middleware->>CookieMgr: clear JWT & legacy tokens (if any)
end
end
else no access token
Middleware->>CookieMgr: read refresh token
alt refresh token exists
Middleware->>TokenRefreshAPI: refresh tokens
TokenRefreshAPI-->>Middleware: success / client-error / transient-error
alt success
Middleware->>CookieMgr: apply new tokens
else client-error
Middleware->>CookieMgr: clear JWT & legacy tokens
else transient-error
Middleware->>CookieMgr: preserve existing tokens (log)
end
else no tokens
Middleware->>CookieMgr: attempt legacy migration (fallback)
end
end
Middleware->>Client: continue (locale handling / response)
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 2✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
🧹 Recent nitpick comments
📜 Recent review detailsConfiguration used: Organization UI Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
🔇 Additional comments (5)
✏️ Tip: You can disable this entire section by setting Comment |
ncarazon
left a comment
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
lgtm
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
🤖 Fix all issues with AI agents
In `@front_end/src/middleware.ts`:
- Around line 60-89: The code currently unconditionally clears tokens when
verifyToken() or refreshTokens() returns false; change this so tokens are only
cleared when the underlying API indicates explicit invalid credentials (e.g.,
400/401) and preserved on transient/network/5xx errors. Update verifyToken() and
refreshTokens(requestAuth, responseAuth) to return a richer result (e.g., { ok:
boolean, invalidCredentials?: boolean } or throw errors with a
status/statusCode) and use that result here to only call
responseAuth.clearAuthTokens() and response.cookies.delete("auth_token") when
invalidCredentials is true; otherwise leave tokens intact and treat the check as
a transient failure. Also ensure handleLegacyTokenMigration is only attempted
when tokens truly do not exist or have been explicitly invalidated.
📜 Review details
Configuration used: Organization UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (2)
front_end/src/middleware.tsfront_end/src/services/auth_tokens_migration.ts
🧰 Additional context used
🧬 Code graph analysis (1)
front_end/src/middleware.ts (3)
front_end/src/services/api/auth/auth.server.ts (2)
refreshTokens(29-36)verifyToken(54-56)front_end/src/services/auth_tokens.ts (2)
AuthCookieReader(82-114)AuthCookieManager(120-156)front_end/src/services/auth_tokens_migration.ts (1)
handleLegacyTokenMigration(20-54)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (4)
- GitHub Check: Build Docker Image / Build Docker Image
- GitHub Check: integration-tests
- GitHub Check: Frontend Checks
- GitHub Check: Backend Checks
🔇 Additional comments (3)
front_end/src/services/auth_tokens_migration.ts (1)
10-10: Import cleanup looks good.Removing
AuthCookieReaderfrom the import list matches the updated function signature and keeps the dependency surface tidy.front_end/src/middleware.ts (2)
15-34: LGTM — refresh path now applies tokens to the response.This aligns with the new flow and keeps the mutation localized to
responseAuth.
36-47: Auth forwarding is already implemented—no action needed.The access token is automatically forwarded as an Authorization header. When
verifyToken()callsServerAuthApi.verifyToken(), theserverFetchfunction retrieves the token viaawait getAuthCookieManager()and adds it to the request asAuthorization: Bearer <token>. This works correctly in the middleware async context with Next.js 15.2.4.
✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.
🧹 Preview Environment Cleaned UpThe preview environment for this PR has been destroyed.
Cleanup triggered by PR close at 2026-01-27T17:17:49Z |
Previous PR broke logic of legacy token exchange. This PR simplifies JWT tokens lifecycle checks and fixed migration
Summary by CodeRabbit
Refactor
Bug Fixes
✏️ Tip: You can customize this high-level summary in your review settings.