Skip to content

Commit

Permalink
Merge pull request #116 from hufs-sports-live/fix/ga
Browse files Browse the repository at this point in the history
[FIX]: 서버 컴포넌트에서 useEffect가 안돌아가는 문제 해결
  • Loading branch information
seongminn authored Nov 29, 2023
2 parents 94ebec1 + 1807391 commit e52cf67
Show file tree
Hide file tree
Showing 7 changed files with 92 additions and 47 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
"@commitlint/cli": "^18.2.0",
"@commitlint/config-conventional": "^18.1.0",
"@tanstack/eslint-plugin-query": "^5.6.0",
"@types/gtag.js": "^0.0.18",
"@types/node": "^20",
"@types/react": "^18",
"@types/react-dom": "^18",
Expand Down
37 changes: 37 additions & 0 deletions src/app/GoogleAnalytics.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
'use client';

import Script from 'next/script';

import * as gtag from '@/utils/gtag';

export default function GoogleAnalytics() {
gtag.useGtag();

return (
<>
{process.env.NODE_ENV !== 'development' && (
<>
{/* Global Site Tag (gtag.js) - Google Analytics */}
<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,
});
`,
}}
/>
</>
)}
</>
);
}
38 changes: 2 additions & 36 deletions src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,11 @@ import './globals.css';
import { Analytics } from '@vercel/analytics/react';
import type { Metadata } from 'next';
import { Noto_Sans_KR } from 'next/font/google';
import { useRouter } from 'next/router';
import { useEffect } from 'react';

import Footer from '@/components/layout/Footer';
import Header from '@/components/layout/Header';
import * as ga from '@/types/ga/gtag';

import GoogleAnalytics from './GoogleAnalytics';
import ReactQueryProvider from './ReactQueryProvider';

const inter = Noto_Sans_KR({
Expand All @@ -30,41 +28,9 @@ export default function RootLayout({
}: {
children: React.ReactNode;
}) {
const router = useRouter();

useEffect(() => {
const handleRouteChange = (url: URL) => {
ga.pageView(url);
};

router.events.on('routeChangeComplete', handleRouteChange);

return () => {
router.events.off('routeChangeComplete', handleRouteChange);
};
}, [router.events]);

return (
<html lang="en">
<head>
<script
async
src={`https://www.googletagmanager.com/gtag/js?id=${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_TAG}`}
/>
<script
dangerouslySetInnerHTML={{
__html: `
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', '${process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_TAG}', {
page_path: window.location.pathname,
});
`,
}}
/>
</head>
<GoogleAnalytics />
<body className={`${inter.className} m-auto max-w-md`}>
<ReactQueryProvider>
<Header />
Expand Down
11 changes: 0 additions & 11 deletions src/types/ga/gtag.ts

This file was deleted.

3 changes: 3 additions & 0 deletions src/types/type.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
/// <reference types="gtag.js" />

declare module 'gtag.js';
44 changes: 44 additions & 0 deletions src/utils/gtag.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import { usePathname } from 'next/navigation';
import { useEffect, useRef } from 'react';

export const GA_TRACKING_ID = process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_TAG;

// https://developers.google.com/analytics/devguides/collection/gtagjs/pages
export const pageview = (url: URL) => {
window.gtag('config', GA_TRACKING_ID as string, {
page_path: url,
});
};

// https://developers.google.com/analytics/devguides/collection/gtagjs/events
export const event = (
action: Gtag.EventNames,
{ event_category, event_label, value }: Gtag.EventParams,
) => {
window.gtag('event', action, {
event_category,
event_label,
value,
});
};

export const useGtag = () => {
const pathname = usePathname(); // Get current route

// Save pathname on component mount into a REF
const savedPathNameRef = useRef(pathname);

useEffect(() => {
if (process.env.NODE_ENV === 'development') return;

const handleRouteChange = (url: URL) => {
pageview(url);
};

if (savedPathNameRef.current !== pathname) {
handleRouteChange(new URL(pathname, window.location.origin));
// Update REF
savedPathNameRef.current = pathname;
}
}, [pathname]);
};
5 changes: 5 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -751,6 +751,11 @@
resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.2.tgz#ff02bc3dc8317cd668dfec247b750ba1f1d62453"
integrity sha512-VeiPZ9MMwXjO32/Xu7+OwflfmeoRwkE/qzndw42gGtgJwZopBnzy2gD//NN1+go1mADzkDcqf/KnFRSjTJ8xJA==

"@types/gtag.js@^0.0.18":
version "0.0.18"
resolved "https://registry.yarnpkg.com/@types/gtag.js/-/gtag.js-0.0.18.tgz#d6bc7cb1acc64ff4f4e4be918d401c53fe9ccf20"
integrity sha512-GJxnIvuXuVhKaHfsOdzGipoOoXq72y3mdcncc9h6i6E7nlz89zBEj2wrLM7bqO5Xk9Lm2B94MwdQsSwRlaPSWw==

"@types/json-schema@^7.0.12":
version "7.0.14"
resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.14.tgz#74a97a5573980802f32c8e47b663530ab3b6b7d1"
Expand Down

0 comments on commit e52cf67

Please sign in to comment.