Anyone there? Having some trouble with your next....
# support
c
Anyone there? Having some trouble with your next.js implementations. All of them collect too few or too many page views
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.
c
useRudderAnalytics.ts:
Copy code
import { useEffect, useState } from 'react';
import type { RudderAnalytics } from '@rudderstack/analytics-js';

const useRudderStackAnalytics = (): RudderAnalytics | undefined => {
  const [analytics, setAnalytics] = useState<RudderAnalytics>();

  useEffect(() => {
    if (!analytics) {
      const initialize = async () => {
        const { RudderAnalytics } = await import('@rudderstack/analytics-js');
        const analyticsInstance = new RudderAnalytics();

        analyticsInstance.load('', '');

        analyticsInstance.ready(() => {
          console.log('We are all set!!!');
        });

        window.rudderanalytics = analyticsInstance;
        setAnalytics(analyticsInstance);
      };

      initialize().catch(e => console.log(e));
    }
  }, [analytics]);

  return analytics;
};

export default useRudderStackAnalytics;
_app.tsx:
Copy code
import React from 'react';
import { ThemeProvider } from '@mui/material/styles';
import { AppProps } from 'next/app';
import { CssBaseline } from '@mui/material';
import dynamic from 'next/dynamic';
import Script from 'next/script';
import theme from '../theme/theme';
import Layout from '../components/general/Layout';
import { useRouter } from 'next/router'
import useRudderStackAnalytics from '../useRudderAnalytics';

import '../styles/globals.css';
import 'swiper/css/bundle';
import '../components/general/video/VideoPlayer.css';

function SsrApp(props: AppProps): JSX.Element {
  const { Component, pageProps } = props;
  const router = useRouter();
  const analytics = useRudderStackAnalytics();

  React.useEffect(() => {
    // Remove the server-side injected CSS.
    const jssStyles = document.querySelector('#jss-server-side');
    // console.log(jssStyles);
    if (jssStyles) {
      jssStyles.parentElement?.removeChild(jssStyles);
    }
    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]);
  return (
    <React.Fragment>
      <Script id="google-tag-manager" strategy="afterInteractive">
        {`
        (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
        new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
        j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
        'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
        })(window,document,'script','dataLayer','GTM-${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}');
      `}
      </Script>
      <ThemeProvider theme={theme}>
        <CssBaseline />
        <Layout>
          <Component {...pageProps} />
        </Layout>
      </ThemeProvider>
    </React.Fragment>
  );
}

const NoSsrApp = dynamic(() => Promise.resolve(SsrApp), {
  ssr: false,
});

export const isLocal = process.env.NODE_ENV !== 'production';
export const isDevelopment = process.env.NEXT_PUBLIC_PREVIEW === '1';
export const isProduction = process.env.NODE_ENV === 'production' && process.env.NEXT_PUBLIC_PREVIEW !== '1';

const App = isLocal ? NoSsrApp : SsrApp;

export default App;
_document.tsx:
Copy code
/* eslint-disable @next/next/no-sync-scripts */
import React from 'react';
import Document, { Html, Main, DocumentContext, Head, NextScript } from 'next/document';
import { ServerStyleSheets } from '@mui/styles';
import Script from 'next/script';



export default class MyDocument extends Document {
  render(): JSX.Element {
    return (
      <Html lang="en">
        <Head>
          {/* <link rel="preload" href="/fonts/inter/Inter-Regular.ttf" as="font" type="font/ttf" crossOrigin="anonymous" /> */}
          {/* <link rel="preload" href="/fonts/inter/Inter-Medium.ttf" as="font" type="font/ttf" crossOrigin="anonymous" /> */}
          {/* <link rel="preload" href="/fonts/inter/Inter-Bold.ttf" as="font" type="font/ttf" crossOrigin="anonymous" /> */}
          {/* <link rel="preload" href="/fonts/inter/Inter-SemiBold.ttf" as="font" type="font/ttf" crossOrigin="anonymous" /> */}
          <Script id='bufferEvents' strategy='beforeInteractive'>
          {`
            window.rudderanalytics = [];
            var methods = [
              'load',
              'page',
              'track',
              'identify',
              'alias',
              'group',
              'ready',
              'reset',
              'getAnonymousId',
              'setAnonymousId',
              'getUserId',
              'getUserTraits',
              'getGroupId',
              'getGroupTraits',
              'startSession',
              'endSession',
              'getSessionId',
            ];
            for (var i = 0; i < methods.length; i++) {
              var method = methods[i];
              window.rudderanalytics[method] = (function (methodName) {
                return function () {
                  window.rudderanalytics.push([methodName].concat(Array.prototype.slice.call(arguments)));
                };
              })(method);
            }
        `}
        </Script>
        </Head>
        <body>
          {/* Google Tag Manager (noscript) */}
          <noscript>
            <iframe
              src={`https://www.googletagmanager.com/ns.html?id=GTM-${process.env.NEXT_PUBLIC_GOOGLE_TAG_MANAGER_ID}&gtm_auth=_9QtPXywUOZqvFPhHOU1lw&gtm_preview=env-4&gtm_cookies_win=x`}
              height="0"
              width="0"
              style={{ display: 'none', visibility: 'hidden' }}
            />
          </noscript>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

// `getInitialProps` belongs to `_document` (instead of `_app`),
// it's compatible with server-side generation (SSG).
MyDocument.getInitialProps = async (ctx: DocumentContext) => {
  // Render app and page and get the context of the page with collected side effects.
  const sheets = new ServerStyleSheets();
  const originalRenderPage = ctx.renderPage;

  ctx.renderPage = () =>
    originalRenderPage({
      enhanceApp: App => props => sheets.collect(<App {...props} />),
    });

  const initialProps = await Document.getInitialProps(ctx);

  return {
    ...initialProps,
    // Styles fragment is rendered after the app and page rendering finish.
    styles: [...React.Children.toArray(initialProps.styles), sheets.getStyleElement()],
  };
};
Looks to be correct, but every page view triggers multiple events
So… in looking at the solution more deeply, what happens is all in this block:
Copy code
const completeHandler = () => {
      trackPageChange();
    };

    router.events.on('routeChangeComplete', completeHandler);
    trackPageChange()

    return () => {
      router.events.off('routeChangeComplete', completeHandler);
On the initial visit to the website, trackPageChange is triggered. On subsequent page visits, trackPageChange is triggered AND the router.event.on(‘routeChangeComplete’… triggers
Looking for a good solution
m
Hi Jim, what version of NextJS are you using? While the team has built some NextJS sample apps, they have not tested on NextJS 14. Here are the sample app built https://github.com/rudderlabs/rudder-sdk-js/tree/develop/examples/nextjs