How could I add google analytics to Nextra ?
Adding Google Analytics to a Nextra site involves a few steps. Nextra is a Next.js-based documentation site generator, so you'll need to integrate Google Analytics into your Next.js project. Here's a step-by-step guide to help you do that:
Create a Google Analytics Account:
UA-XXXXXXXXX-X
for Universal Analytics or G-XXXXXXXXXX
for Google Analytics 4).Install the next/script
Component:
next/script
component that you can use to add third-party scripts to your application.Add the Google Analytics Script:
_app.js
or _app.tsx
file in your Next.js project. This file is used to initialize pages and is a good place to add global scripts.Here’s an example of how you can add the Google Analytics script to your _app.js
or _app.tsx
file:
// _app.js or _app.tsx
import { useEffect } from 'react';
import Script from 'next/script';
import { useRouter } from 'next/router';
const GA_TRACKING_ID = 'YOUR_GOOGLE_ANALYTICS_TRACKING_ID';
const MyApp = ({ Component, pageProps }) => {
const router = useRouter();
useEffect(() => {
const handleRouteChange = (url) => {
window.gtag('config', GA_TRACKING_ID, {
page_path: url,
});
};
router.events.on('routeChangeComplete', handleRouteChange);
return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${GA_TRACKING_ID}`}
/>
<Script
id="google-analytics"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
<Component {...pageProps} />
</>
);
};
export default MyApp;
Replace YOUR_GOOGLE_ANALYTICS_TRACKING_ID
:
YOUR_GOOGLE_ANALYTICS_TRACKING_ID
with your actual Google Analytics tracking ID.Deploy Your Site:
Verify Tracking:
By following these steps, you should have Google Analytics successfully integrated into your Nextra site.