-
Notifications
You must be signed in to change notification settings - Fork 1
fix(auth): resolve onboarding redirect loop without disabling cookieCache #7
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
Open
jacksonkasi1
wants to merge
1
commit into
organization-v2
Choose a base branch
from
feature/fix-onboarding-cache-loop
base: organization-v2
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| /** | ||
| * Refresh the Better Auth session cookie cache after a mutation. | ||
| * | ||
| * Better Auth caches the session payload (session + user fields) in a signed | ||
| * cookie (`session.cookieCache`) so subsequent `/get-session` requests can be | ||
| * answered without hitting the database. When we mutate session-bearing rows | ||
| * directly (e.g. `sessionTable.activeOrganizationId`, `userTable.shouldOnboard`, | ||
| * `userTable.currentOnboardingStep`), the cookie cache becomes stale and | ||
| * downstream guards (RequireOnboarding) will read the OLD values until the | ||
| * cache expires, causing redirect loops. | ||
| * | ||
| * This helper re-reads the live session + user from the database via | ||
| * `ctx.context.internalAdapter.findSession` and re-issues the signed session | ||
| * cookie via Better Auth's `setSessionCookie` helper, which internally calls | ||
| * `setCookieCache`. After this runs, the very next request will see the fresh | ||
| * session values. | ||
| * | ||
| * Reference: better-auth v1.4.x `src/cookies/index.ts` (setSessionCookie / | ||
| * setCookieCache) and `src/api/routes/update-user.ts` which uses the same | ||
| * pattern after `internalAdapter.updateUser`. | ||
| */ | ||
|
|
||
| // ** import lib | ||
| import { setSessionCookie } from "better-auth/cookies"; | ||
|
|
||
| // ** import logs | ||
| import { logger } from "@repo/logs"; | ||
|
|
||
| // ** import types | ||
| import type { GenericEndpointContext } from "better-auth"; | ||
|
|
||
| /** | ||
| * Re-read the session for the current request from the database and refresh | ||
| * the signed session cookie (including the cookie cache). | ||
| * | ||
| * Safe to call from any authenticated endpoint handler (`use: [sessionMiddleware]`). | ||
| * No-op if no session is attached to the request context. | ||
| */ | ||
| export async function refreshSessionCookie( | ||
| ctx: GenericEndpointContext, | ||
| ): Promise<void> { | ||
| try { | ||
| const currentSession = ctx.context.session as | ||
| | { session?: { token?: string } } | ||
| | null | ||
| | undefined; | ||
| const sessionToken = currentSession?.session?.token; | ||
|
|
||
| if (!sessionToken) { | ||
| // No session on this request - nothing to refresh. | ||
| return; | ||
| } | ||
|
|
||
| const fresh = await ctx.context.internalAdapter.findSession(sessionToken); | ||
|
|
||
| if (!fresh) { | ||
| // Session was deleted concurrently - leave cookie alone, /get-session | ||
| // will clean it up on the next request. | ||
| return; | ||
| } | ||
|
|
||
| await setSessionCookie(ctx, { | ||
| session: fresh.session, | ||
| user: fresh.user, | ||
| }); | ||
| } catch (error) { | ||
| // Never let cookie refresh failures break the mutation - log and continue. | ||
| // Worst case: cookie cache is stale for `cookieCache.maxAge` seconds. | ||
| logger.error( | ||
| `Failed to refresh session cookie cache: ${ | ||
| error instanceof Error ? error.message : String(error) | ||
| }`, | ||
| ); | ||
| } | ||
| } | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
suggestion: Log the full error object instead of only the message to preserve stack traces and structured data.
Interpolating only
error.message/String(error)discards the stack and any structured fields. If your logger supports it, prefer passing the error object itself, e.g.logger.error("Failed to refresh session cookie cache", { error })orlogger.error(error, "Failed to refresh session cookie cache"), so you retain full diagnostics when issues occur.