Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add google analytics #30

Merged
merged 1 commit into from
Dec 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ yarn-error.log*

# local env files
.env*.local
.env

# vercel
.vercel
Expand Down
2 changes: 2 additions & 0 deletions app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Inter } from "next/font/google";
import "./globals.css";
import Header from "@/components/header";
import Footer from "@/components/footer";
import GoogleAnalytics from "@/components/GoogleAnalytics";

const inter = Inter({ subsets: ["latin"] });

Expand All @@ -22,6 +23,7 @@ export default function RootLayout({
<body className={inter.className}>
<div className="flex flex-col place-content-center bg-background text-text">
<Header />
<GoogleAnalytics />
{children}
<Footer />
</div>
Expand Down
31 changes: 31 additions & 0 deletions components/GoogleAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
"use client";

import Script from "next/script";
import * as gtag from "@/lib/gtag";

const GoogleAnalytics = () => {
return (
<>
<Script
strategy="afterInteractive"
src={`https://www.googletagmanager.com/gtag/js?id=${gtag.GA_TRACKING_ID}`}
/>
<Script
id="gtag-init"
strategy="afterInteractive"
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${gtag.GA_TRACKING_ID}', {
page_path: window.location.pathname,
});
`,
}}
/>
</>
);
};

export default GoogleAnalytics;
27 changes: 27 additions & 0 deletions lib/gtag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
// https://stackoverflow.com/questions/77063977/implementing-google-analytics-in-nextjs-13-app-directory

export const GA_TRACKING_ID: string | undefined = process.env.GA_TRACKING_ID;

export const pageview = (url: string) => {
(window as any).gtag("config", GA_TRACKING_ID, {
page_path: url,
});
};

export const event = ({
action,
category,
label,
value,
}: {
action: string;
category: string;
label: string;
value: number;
}) => {
(window as any).gtag("event", action, {
event_category: category,
event_label: label,
value: value,
});
};