Issue with Next JS router.push not functioning unless the page is refreshed

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();

Answer №1

Prior to initiating the router.push() function, it is crucial to ensure that the router instance has finished loading. The condition router.isReady signifies that the router is fully prepared for operation.

To prevent premature redirection, implement a check to verify the readiness of the router:

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]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Unlocking API secrets in Next.js through AWS Amplify

I'm struggling to figure out how to properly set and access API secrets in a Next.js app within an AWS Amplify project. Here's the situation: I have a confidential API key that is used to retrieve data from an API. Obviously, this key needs to b ...

Javascript encountering issues with recognizing 'self.function' within an onclick event

Recently, I have been working on enhancing a Javascript file that is part of a Twitter plugin. One of the key additions I made was implementing a filter function for this plugin. Here is a snippet of the script showcasing the relevant parts: ;(function ( ...

Javascript for Cordova utilizing WebSocket and incorporating client side certificates

I am looking to establish a secure SSL/TLS connection between my client and server, with only a specific authorized client allowed to connect. To achieve this, I have generated a client certificate using OpenSSL on the server for mutual authorization. The ...

Creating a customized greeting message using discord.js

I've been working on creating a Discord bot using discord.js, and I'm trying to figure out how to make the bot send a welcome message when a new member joins the server and opens a chat with the bot. The message should be something like "Hi there ...

Why is my IEDriverServer typing so slow? Seeking JavaScript solutions

While working with Selenium and IEDriverServer, I have encountered an issue where the keys are being sent to the input at a very slow pace. After conducting some research, many websites recommend ensuring that the Browser and IEDriverServer are of the sam ...

Adjusting the height of a container dynamically in React while flex items wrap using CSS

In my React project, I have a container called "answers-container" with multiple buttons inside it, laid out using flexbox with flex-wrap: wrap to allow them to wrap onto the next line when the container width is exceeded. However, I'm facing an issu ...

Counter cannot be accessed once it has been updated

When I click a button, an interval should start. The issue is that I'm unable to access the value of counter. The goal is for the interval to stop when the counter reaches 5. Here's an example: let interval = null; const stateReducer = (state, ...

What could be causing the excessive number of entries in my mapping results?

I am in need of mapping an array consisting of dates. Each date within this array is associated with a group of dates (formatted as an array). For instance: The format array looks like this: let format = [3, 3, 1, 5, 4, 4, 3, 5, 13, 10, 3, 5, 5, 2, 2, 10] ...

Leverage context to facilitate communication between components operating at various levels of the system

I am currently working on the settings pages of my applications. Each page features a common SettingsLayout (parent component) that is displayed across all settings pages. One unique aspect of this layout is the presence of an ActionsBar, where the submit/ ...

How to verify if both MySQL queries in Node.js have fetched results and then display the page content

Seeking assistance with two queries: one to verify user following post author and another to check if the user has liked the post. I attempted to use the logic: if ((likes) && (resault)), but it's not yielding the desired outcome. After inve ...

"Encountering a problem with the NextUI and Tailwind configuration file

Challenge encountered while setting up nextui with tailwind.config.js tailwind.config.js import {nextui} from "@nextui-org/react"; /** @type {import('tailwindcss').Config} */ module.exports = { content: [ './src/pages/**/*. ...

What steps can be taken to ensure authenticated requests are made to Google Cloud Storage from a NextJS app?

Utilizing a Cloud Storage instance to store images on my NextJS web app has been presenting some challenges. The way I reference the images is as follows: ... some code image="https://storage.cloud.google.com/{my-project}/myimage.jpg" ... some m ...

Unlocking the Power of Combining JMVC and Server-side MVC Models

It's been a few days since I posted this question here and still no response. I also tried posting it on forum.javascriptMVC.com and finally got an answer, but I'm looking for more insights. Here's my question: After reading the documentat ...

Guide to interpreting an Angular expression using traditional JavaScript conventions

I have encountered an issue with the Angular app that I am currently working on. It needs to retrieve the Google Analytics ID from Angular in order to pass it to ga('create', 'UA-XXXXX-Y') using standard JavaScript in my index.html. &l ...

What methods can I employ within an AngularJS controller to retrieve data from Google App Engine instead of solely relying on a JSON file?

As a newcomer to web development, I have been experimenting with retrieving data from a Google App Engine datastore and selectively displaying it on a webpage using AngularJS. While I have successfully integrated Angular with a JSON file and posted the con ...

Error: The object 'exports' is not defined in geotiff.js at line 3

Looking to integrate the geotiff library with Angular 6.1.0 and TypeScript 2.9.2. Installed it using npm i geotiff Encountering the following error in the browser console: Uncaught ReferenceError: exports is not defined at geotiff.js:3 After r ...

React's memo and/or useCallback functions are not functioning as anticipated

Within my Home Component, there is a state called records, which I utilize to execute a records.map() and display individual RecordItem components within a table. function Home() { const [records, setRecords] = useState<Array<RecordType>>(l ...

Attempting to scroll through a webpage and extract data using Python and Selenium in a continuous manner

Recently, I posed a question (you can find it here: Python Web Scraping (Beautiful Soup, Selenium and PhantomJS): Only scraping part of full page) that shed light on an issue I encountered while attempting to scrape all the data from a webpage that updates ...

Error: The current component does not have a template or render function specified. Check the <App>

I am a beginner in Vue js and I am facing an issue while running my application. It is showing an empty page with the error message: Component is missing template or render function. at <App>. Additionally, there is also a warning from Vue Router sa ...

Formik: encountering target as undefined while passing Material UI Date Picker as prop to React Component

I'm currently working on developing a component that can be reused. The idea is to pass form fields as props, but I ran into an issue when clicking on the datepicker field. The error message that pops up is: TypeError: target is undefined Any sugge ...