Post-signIn Manual Redirect Fails Due to Middleware Token Delay in Next.js 15 with NextAuth v4 #82022
Replies: 1 comment
-
Hi @devdogfish, Thanks for the detailed explanation! This delay issue with token availability right after signIn() in NextAuth + Next.js middleware is a known challenge. What’s going on? Your middleware runs on the next request and checks the token, but it may still see the old/no token state, causing a redirect back to login. The manual redirect with router.replace() happens before the token is fully set and middleware updated, hence the failed redirect on the first try. Better approaches than a fixed timeout:
This ensures you redirect only once the session is truly active. Disable middleware redirect temporarily after sign-in Redirect from server action or route handler Improve middleware token caching/refresh logic In summary, instead of a hardcoded delay, rely on the client session status to trigger navigation once auth state is stable. Happy to help refactor your code if you want! |
Beta Was this translation helpful? Give feedback.
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