https://github.com/tomilola-ng/nextjs-ga
Sample Component to Add Google Analytics to your NextJS Applications
https://github.com/tomilola-ng/nextjs-ga
analytics ga4 google-analytics nextjs nextjs15 search user-tracking
Last synced: about 2 months ago
JSON representation
Sample Component to Add Google Analytics to your NextJS Applications
- Host: GitHub
- URL: https://github.com/tomilola-ng/nextjs-ga
- Owner: Tomilola-ng
- License: mit
- Created: 2025-01-22T06:54:03.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-01-22T07:12:15.000Z (over 1 year ago)
- Last Synced: 2025-01-22T08:22:45.308Z (over 1 year ago)
- Topics: analytics, ga4, google-analytics, nextjs, nextjs15, search, user-tracking
- Language: TypeScript
- Homepage:
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# π Next.js Google Analytics Component
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!




---
## π Why Use This Component?
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.
---
## π οΈ How to Use
### Step 1: Copy the Component
Create a new file in your `components` folder (e.g., `components/google-analytics.tsx`) and paste the following code:
```tsx
// 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 (
<>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gid}', {
page_path: window.location.pathname,
});
`}
>
);
}
```
---
### Step 2: Add the Component to Your App
Import and use the `Analytics` component in your `_app.tsx` (or `layout.tsx`) file to ensure it loads on every page:
```tsx
// pages/_app.tsx
import Analytics from "@/components/google-analytics";
export default function MyApp({ Component, pageProps }) {
return (
<>
>
);
}
```
OR
```tsx
// app/layout.tsx
import Analytics from "@/components/google-analytics";
export default function MyApp({ Component, pageProps }) {
return (
<>
... // Previous Code
... // Other Code
>
);
}
```
Replace `"G-2087S873KK"` with your actual **Google Analytics Tracking ID**.
---
### Step 3: Deploy and Verify
Deploy your Next.js app and visit your website. Open the **Google Analytics Real-Time Dashboard** to verify that your website is sending data.
---
## β¨ Features
### 1. **Reusable Component**
Pass your Google Analytics Tracking ID (`gid`) as a prop to make the component reusable across multiple projects.
### 2. **Validation**
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.
### 3. **Optimized Performance**
The `Script` component from Next.js ensures the Google Analytics script is loaded efficiently without blocking your page render.
### 4. **TypeScript Support**
The component is written in TypeScript, providing better tooling support and type safety.
---
## π Example Usage
### Basic Usage
```tsx
```
### Dynamic Tracking ID
If your tracking ID is stored in an environment variable, you can pass it dynamically:
```tsx
```
---
## π€ Contributing
Contributions are welcome! If you have ideas for improvements or find any issues, feel free to:
- Open an issue on the [GitHub repository](https://github.com/Tomilola-ng/nextjs-ga).
- Submit a pull request with your changes.
Letβs make this component even better together!
---
## π Follow Me
If you found this component helpful, consider following me on:
- **X (Twitter)**: [@Tomilola_ng](https://twitter.com/Tomilola_ng)
- **GitHub**: [Tomilola-ng](https://github.com/Tomilola-ng)
Your support means a lot!
---
## π License
This project is licensed under the **MIT License**. Feel free to use, modify, and distribute it as you see fit.
---
## π References
- [Next.js Documentation](https://nextjs.org/docs)
- [Google Analytics Documentation](https://developers.google.com/analytics/devguides/collection/gtagjs)
---
β¨ **Star this repository if you found it helpful!** β¨