Skip to content

Commit

Permalink
feat: add google analytics (#30)
Browse files Browse the repository at this point in the history
  • Loading branch information
KevinWu098 authored Dec 28, 2023
1 parent cbea27c commit 14f45e6
Show file tree
Hide file tree
Showing 4 changed files with 61 additions and 0 deletions.
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,
});
};

0 comments on commit 14f45e6

Please sign in to comment.