I’m using Next.js 14.2 with the page directory. When I create a build and run npm start
, it opens a landing page with a login button using the <Link>
component. I also set prefetch={false}
in the login button. When I redirect to the login screen and enter all the correct values, it shows “login successful,” but it does not redirect to the dashboard. I’m sharing the redirect code below.
import { useRouter } from 'next/router';
const router = useRouter();
useEffect(() => {
if (loggedin && localStorage?.getItem('token')) {
console.log("isReady", router.isReady);
router.push(ROUTE_NAMES.DASHBOARD);
}
}, [loggedin]);
When I check the console, isReady
is returning true
. Let me know where I’m wrong.
The router.push()
function is being called before the router instance is ready. router.isReady
is true
only when the router is completely ready.
Add a condition check if the router is ready before performing the redirect:
import { useEffect } from 'react';
import { useRouter } from 'next/router';
useEffect(() => {
if (loggedin && localStorage?.getItem('token')) {
if (router.isReady) {
router.push(ROUTE_NAMES.DASHBOARD);
}
}
}, [loggedin, router.isReady]);