Hey all, I'm working on adding Rudderstack to our ...
# support
c
Hey all, I'm working on adding Rudderstack to our NextJS app and it looks like the docs only recommend initializing Rudderstack on the
pages/index.tsx
page if using the NPM package. This won't track users who aren't explicitly on the home page though, and dropping the init function in the
_app.tsx
file just seems to break things. Any ideas here?
m
Hey There! đź‘‹ Your message has been received by the RudderStack team. We will forward this request to your Technical Account Manager, and they will get back to you shortly. Please use the thread for any additional comments.
h
Hi @calm-salesmen-1612 Here are some NextJS sample apps to integrate the SDK. Please let us know if you still need any help. https://github.com/rudderlabs/rudder-sdk-js/tree/develop/examples/nextjs
c
Yeah I looked at these and the page router one only has one single page, so it doesn’t really answer my question. Do I have to init rudderstack on each individual page for it to work properly?
c
Hello @calm-salesmen-1612, This would be up you you in where/when you would like to initialise the SDK instance and how to orchestrate your tracking. The examples have a simple demonstration on how the SDK can be utilised as each customer has their own unique needs and requirements. Where you will use, and if you will use, the useRudderStackAnalytics hook for example is your choice. Is the question more around the lines, what is the suggested orchestration to automatically track all page changes in NextJs while using page router? If that is the case NextJs official docs recommend to use handleRouteChange https://nextjs.org/docs/pages/api-reference/functions/use-router#routerevents You can use the hook from our example and then call the page method inside the handleRouteChange as per the example of nextJs website Does this solve the issue for you?
Something like this in _app.tsx should get you started:
Copy code
const router = useRouter();
  const analytics = useRudderStackAnalytics();

  useEffect(() => {
    const trackPageChange = () => {
      analytics?.page(
        'PageView',
        {
          path: router.pathname,
          search: router.query
        }
      );
    }

    const completeHandler = () => {
      trackPageChange();
    };
    
    router.events.on('routeChangeComplete', completeHandler);
    trackPageChange()

    return () => {
      router.events.off('routeChangeComplete', completeHandler);
    };
  }, [router, analytics]);
c
where is the
useRudderStackAnalytics
you're referring to?
h
c
Got it! this is definitely more helpful, thank you