Next.js Discord

Discord Forum

router.push() not working in production --middleware doesn't see auth cookies

Unanswered
Barbary Lion posted this in #help-forum
Open in Discord
Barbary LionOP
I'm using cookie-based authentication in my Next.js app. When a user logs in, I set an HTTP-only cookie in their browser.

The issue I'm facing is that after setting or modifying cookies (e.g., on login, logout, or any similar action), router.push() doesn't seem to work as expected. Specifically, after a successful login, I try to redirect the user to a protected route (e.g., /dashboard) using router.push('/dashboard'), but it doesn't navigate. I suspect the middleware is the reason.

It seems like the middleware runs before the new cookies are available, so it still treats the user as unauthenticated and blocks access to the protected route. However, if I use window.location.href = '/dashboard', the redirect works correctly and the middleware recognizes the newly set cookies.

Is this a known issue with middleware and router.push() after setting HTTP-only cookies? Is there a better way to handle this redirect so that the middleware correctly detects the updated authentication state?

10 Replies

where are you setting the cookies, like in a server action
Barbary LionOP
no i have seperate backend built by laravel
@Anay-208 | Ping in replies where are you setting the cookies, like in a server action
Barbary LionOP
so i just fetch from the client side to the backend and the cookies are setted in the browser
the same issue is in this discussion and i just want to know if it still unsolved https://github.com/vercel/next.js/discussions/51782
If you use server action to set cookies, it wouldn't have been necessary
Barbary LionOP
i already tried router.refresh() before router.push and it didn't works for me
@Anay-208 | Ping in replies It is solved in the discussion, and the solution would be ts router.refresh()
Barbary LionOP
the only dirty solution i found is the window.location method
Can you try adding a console log to dashboard/page.tsx to see if you recieve request when using router.push