I'm currently running Next.js 14.2 in my project with the page directory structure. After building and starting the application using npm start
, a landing page is displayed with a login button that utilizes the <Link>
component. I have also disabled prefetch by setting prefetch={false}
on the login button. However, upon successful login with the correct credentials, the redirect to the dashboard does not occur. Below is the code snippet responsible for the redirect:
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]);
Upon checking the console, the isReady
value is returning as true
. Please advise on where there might be an issue.
UPDATE
I made some adjustments and introduced a condition involving the isReady
state when changing routes. However, I encountered another roadblock after implementing middleware as the page transition did not occur as expected.
if (NO_AUTH_ROUTES.includes(pathname)) {
return NextResponse.next();
} else if (isAuthenticate && AUTH_ROUTES.includes(pathname)) {
// Redirect to the dashboard since it's an authenticated route
return NextResponse.redirect(new URL(ROUTE_NAMES.DASHBOARD, request.url));
} else if (!AUTH_ROUTES.includes(pathname)) {
// Check if the pathname is not in the list of authenticated routes
// If the token or authentication status is missing, redirect to the login page
if (!isAuthenticate) {
return NextResponse.redirect(new URL(ROUTE_NAMES.LOGIN, request.url));
}
}
return NextResponse.next();