Welcome to nextjs-ga, a simple and reusable React component to seamlessly integrate Google Analytics into your Next.js applications.
No need to install an npm package—just copy and paste the component into your project, and you're good to go!
Tracking user behavior and website performance is crucial for optimizing your Next.js app. With this component, you can:
- Easily Add Google Analytics: No complex setup or npm installations required.
- Reusable and Customizable: Pass your Google Analytics Tracking ID (
gid
) as a prop. - Lightweight and Efficient: Uses Next.js's
Script
component for optimal performance. - Validation Included: Ensures your
gid
is in the correct format.
Create a new file in your components
folder (e.g., components/google-analytics.tsx
) and paste the following code:
// components/google-analytics.tsx
"use client";
import Script from "next/script";
import { useEffect } from "react";
interface AnalyticsProps {
gid: string;
}
export default function Analytics({ gid }: AnalyticsProps) {
useEffect(() => {
// Validate the Google Analytics Tracking ID
const isValidGid = /^G-[A-Z0-9]+$/.test(gid);
if (!isValidGid) {
console.error(
"Invalid Google Analytics Tracking ID. Expected format: G-[A-Z0-9]+"
);
return;
}
}, [gid]);
return (
<>
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=${gid}`}
/>
<Script id="google-analytics" strategy="lazyOnload">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gid}', {
page_path: window.location.pathname,
});
`}
</Script>
</>
);
}
Import and use the Analytics
component in your _app.tsx
(or layout.tsx
) file to ensure it loads on every page:
// pages/_app.tsx
import Analytics from "@/components/google-analytics";
export default function MyApp({ Component, pageProps }) {
return (
<>
<Analytics gid="G-2087S873KK" />
<Component {...pageProps} />
</>
);
}
OR
// app/layout.tsx
import Analytics from "@/components/google-analytics";
export default function MyApp({ Component, pageProps }) {
return (
<>
... // Previous Code
<Analytics gid="G-2087S873KK" />
... // Other Code
</>
);
}
Replace "G-2087S873KK"
with your actual Google Analytics Tracking ID.
Deploy your Next.js app and visit your website. Open the Google Analytics Real-Time Dashboard to verify that your website is sending data.
Pass your Google Analytics Tracking ID (gid
) as a prop to make the component reusable across multiple projects.
The component includes a validation check to ensure your gid
is in the correct format (G-[A-Z0-9]+
). If the ID is invalid, an error will be logged to the console.
The Script
component from Next.js ensures the Google Analytics script is loaded efficiently without blocking your page render.
The component is written in TypeScript, providing better tooling support and type safety.
<Analytics gid="G-2087S873KK" />
If your tracking ID is stored in an environment variable, you can pass it dynamically:
<Analytics gid={process.env.NEXT_PUBLIC_GA_TRACKING_ID} />
Contributions are welcome! If you have ideas for improvements or find any issues, feel free to:
- Open an issue on the GitHub repository.
- Submit a pull request with your changes.
Let’s make this component even better together!
If you found this component helpful, consider following me on:
- X (Twitter): @Tomilola_ng
- GitHub: Tomilola-ng
Your support means a lot!
This project is licensed under the MIT License. Feel free to use, modify, and distribute it as you see fit.
✨ Star this repository if you found it helpful! ✨