Encountering an issue with client-side navigation and middleware in the router. It seems that the router is storing the initial redirect path and subsequent navigations bypass the middleware.
This behavior ceases upon browser refresh and does not occur in a development environment.
I aim to have the router consistently pass through the middleware for redirection evaluation each time.
To recreate this issue:
- Repeatedly go to
/
from the browser search bar. There's a 50% chance of being redirected to/dashboard
or/profile
due tomiddleware.ts
- Access
/login
and click on Login button. This triggers arouter.push('/')
which redirects to either/dashboard
or/profile
. - Click Logout button, initiating a
router.push('/login')
. - Subsequent Logins will always direct to the same route.
My middleware function in middleware.ts:
export function middleware(request: NextRequest) {
if (request.nextUrl.pathname === '/') {
if (Math.random() > 0.5) {
return NextResponse.redirect(new URL('/dashboard', request.url))
} else {
return NextResponse.redirect(new URL('/profile', request.url))
}
}
}
My login.tsx file:
import { NextPage } from 'next'
import { useRouter } from 'next/router'
const LoginPage: NextPage<{}> = () => {
const router = useRouter()
const login = () => {
router.push('/')
}
return (
<div>
<h1>Login</h1>
<button onClick={login}>Login</button>
</div>
)
}
export default LoginPage
Dashboard/Profile Page code:
import { NextPage } from 'next'
import { useRouter } from 'next/router'
const DashboardPage: NextPage<{}> = () => {
const router = useRouter()
const logout = () => {
router.push('/login')
}
return (
<div>
<h1>DashboardPage</h1>
<button onClick={logout}>Logout</button>
</div>
)
}
export default DashboardPage
Vercel site demo:
Full code available at: https://github.com/LautaroRiveiro/nextjs-router-clientside-test