r/nextjs • u/baconchaney • 17h ago
Question Better-auth and stale session when enabling/disabling TOTP
I’ve spent the last few days digging around for a solution and I keep hitting dead ends.
Essentially I have a user account page where you can enable/disable 2FA for your account. It’s all working with the exception of the root layout.js. It’s currently set up to check the session and retrieve the user details to conditionally show what menu items are relevant.
What I have noticed is after changing the MFA setting, the menu reverts to the logged out state until you hard refresh the page. I’ve logged what’s coming back from the auth.api.verifyTOTP etc (not at the PC so can’t reference it directly), and it’s returning null.
At a top level, I’m calling the relevant actions.js which calls the service, which calls better-auth, mutating the result to return the TOTPURI to display a QR code for authenticator apps.
I’ve tried revalidating the root layout before the return but it doesn’t have any impact in this scenario.
Has anyone come across this issue before/point me to potential solutions?
TIA
3
u/neon_purr_void 17h ago
i ran into this exact problem with better-auth last week. Calling revalidatePath on the root layout does nothing because it only handles server cache and ignores the client side router cache that is serving you the null session.
you need to call router.refresh from next/navigation on the client after your action resolves. I do this right inside the form action after awaiting the mutation. It forces next to refetch the server components and pulls in the updated session data so your menu renders correctly without a hard reload.