skip to Main Content

clarification – I do not want to catch any router change event inside NextJS. I want to catch them outside NextJS.

I have an application written in NextJS, I have some code that is running outside the NextJS context. I want this code to catch when navigation changes happen. Links are built using NextJS link component using NextJS Router.

The code is sitting in an external JavaScript file that is loaded in _document.tsx

<script src="assets/scripts/testerTools.js" />

it loads correctly

when navigation changes I want to run a function, let’s assume something simple like

const runfunction = () => {
  console.log("it ran");
}

I have tried the following

window.addEventListener('replaceState', () => {runfunction()});
window.addEventListener('pushState', () => {runfunction()});
window.addEventListener('popState', () => {runfunction()});
navigator.addEventListener('navigate', () => {runfunction()});

None of these work when I follow a NextJS link and the address bar url changes.

Is there some event listener I can attach to and run my function that will be able to listen to these changes.

I am using Firefox currently, although hopefully that wouldn’t be affecting the code in this case.

2

Answers


  1. The events you are trying to listen to are all browser events, and they are not triggered when navigating between pages in Next.js. Instead, you need to listen to the routeChangeStart event from the Next.js router.

    To do this, you can use the useRouter hook from the next/router package. This hook will return an object with a events property that you can use to subscribe to events.

    The following code shows how to listen to the routeChangeStart event and run your function when it is triggered:

    import { useRouter } from "next/router";
    
    const runfunction = () => {
      console.log("it ran");
    };
    
    const App = () => {
      const router = useRouter();
    
      router.events.on("routeChangeStart", runfunction);
    
      return <div>...</div>;
    };
    

    This code will listen to the routeChangeStart event and run the runfunction() function whenever the route changes.

    Note that you need to call the router.events.off() method to unsubscribe from the event when you are no longer interested in listening to it.

    Here is a complete example of how to listen to the routeChangeStart event in an external JavaScript file:

    // testerTools.js
    
    const runfunction = () => {
      console.log("it ran");
    };
    
    const subscribeToRouteChange = () => {
      const router = useRouter();
    
      router.events.on("routeChangeStart", runfunction);
    };
    
    export { subscribeToRouteChange };
    

    To use this code, you would need to import it into your Next.js application and then call the subscribeToRouteChange() function.

    Login or Signup to reply.
  2. It seems like you’re looking for a way to catch Next.js router changes outside of the Next.js framework. If you want to catch router changes that result in changes to the browser’s address bar location (href) without relying on the Next.js router object, you can use the window.onpopstate event handler in JavaScript. This event is triggered when the user navigates through their browsing history, such as clicking the back or forward buttons or modifying the URL manually.

    Here’s how you can use window.onpopstate to catch router changes outside of Next.js:

    // Add an event listener for popstate
    window.onpopstate = (event) => {
      // The event object contains information about the popstate event
      // You can access the new URL using event.state or document.location.href
      const newURL = event.state || document.location.href;
      
      console.log('Router change detected:', newURL);
    
      // You can run your custom function here
      runFunction();
    };
    
    // Define your custom function
    const runFunction = () => {
      console.log('Custom function ran');
      // Your custom logic here
    };
    

    By setting up this event listener, you can capture changes to the browser’s history, including those triggered by Next.js router changes, back and forward button clicks, or manual URL modifications.

    This approach allows you to handle router changes independently of Next.js’s internal router and is more suitable if you want to capture all router changes happening throughout your application, not just those initiated within Next.js components.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search