I am using Next.js router.replace
once the user enters the home page. It’s working great, but the issue is that the back button is still enabled. If I click the back button, it goes to Chrome’s default page. How can I get rid of this?
router.replace({
pathname: '/home',
});
4
What you can do is use router.push
as Ragul CS suggested – but I’d add checks and redirects.
If the user is on the login page, we can automatically redirect them to the home page if they’re logged in and vice versa, something like this in src/middleware.ts
:
export async function middleware(request: NextRequest, _: NextResponse) {
if(request.nextUrl.pathname === 'login') {
// if user is signed in - redirect to /home
}
if(request.nextUrl.pathname === 'home') {
//if user is not signed in - redirect to /login
}
}
This way you don’t have to change the way the back button works.