Browse Source

Fix pageview collection for UA

main
Dan Abramov 3 years ago
parent
commit
8ca0215cff
  1. 33
      beta/src/pages/_app.tsx

33
beta/src/pages/_app.tsx

@ -4,6 +4,7 @@
import * as React from 'react';
import {AppProps} from 'next/app';
import {useRouter} from 'next/router';
import '@docsearch/css';
import '../styles/fonts.css';
import '../styles/algolia.css';
@ -14,7 +15,29 @@ import Script from 'next/script';
const EmptyAppShell: React.FC = ({children}) => <>{children}</>;
if (typeof window !== 'undefined') {
window.dataLayer = window.dataLayer || [];
window.gtag = function () {
dataLayer.push(arguments);
};
gtag('js', new Date());
}
export default function MyApp({Component, pageProps}: AppProps) {
const router = useRouter();
React.useEffect(() => {
const handleRouteChange = (url) => {
// @ts-ignore
gtag('config', process.env.NEXT_PUBLIC_GA_TRACKING_ID, {
page_path: url,
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
let AppShell = (Component as any).appShell || EmptyAppShell;
// In order to make sidebar scrolling between pages work as expected
// we need to access the underlying MDX component.
@ -31,16 +54,6 @@ export default function MyApp({Component, pageProps}: AppProps) {
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GA_TRACKING_ID}`}
/>
)}
<Script id="google-analytics" strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`}
</Script>
</AppShell>
);
}

Loading…
Cancel
Save