Post-signIn Manual Redirect Fails Due to Middleware Token Delay in Next.js 15 with NextAuth v4 #13122
Unanswered
devdogfish
asked this question in
Help
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I'm working on a Next.js 15 App Router project using NextAuth v4 (not the rebranded auth.js version). I’ve implemented credentials-based authentication with a custom handleSubmit function that:
Calls and awaits signIn() with redirect: false (to preserve form values).
Then calls router.replace('/') to redirect the user to the homepage upon successful login.
The problem is that the redirect often fails on the first attempt, and the user has to click multiple times to be successfully redirected.
After debugging, it seems the issue stems from my middleware, which fetches the JWT token (by awaiting the
getNextAuthToken
function with request and nextAuth secret) and subsequently checks the token's validity to determine authentication status. However, the token is not available immediately after signIn() resolves, so the middleware redirects the user back to the login page.As a temporary workaround, I've added a timeout delay before calling router.replace() to give the session time to update, and that makes it work. But this feels unreliable and not ideal.
Question
Is there a more robust and reliable way to handle post-signIn redirection without relying on a hardcoded delay? Ideally, I want to ensure that the session or token is available before redirecting, so the middleware correctly detects the authenticated user on first try.
Tech Stack
Thanks!
Beta Was this translation helpful? Give feedback.
All reactions