WebPublisher/React
[nextjs] Google Analytics
amanda
2024. 8. 29. 14:39
GA setting
@next/third-parties
설치
src/app/[lng]/layout.tsx
import type { Metadata, Viewport } from 'next';
import { dir } from 'i18next';
import { locales } from '@/i18n';
import { NextIntlClientProvider } from 'next-intl';
import { getMessages, unstable_setRequestLocale } from 'next-intl/server';
import { GoogleAnalytics, GoogleTagManager } from '@next/third-parties/google';
import '@/assets/css/globals.css';
export const metadata: Metadata = {
title: 'title',
description: 'description',
authors: [{ name: 'name' }],
keywords: [
'keywords',
],
robots: 'index,follow',
icons: {
icon: '/favicon.ico',
},
appleWebApp: {
title: 'title',
capable: true,
statusBarStyle: 'black-translucent',
},
};
export const viewport: Viewport = {
width: 'device-width',
initialScale: 1,
maximumScale: 1,
minimumScale: 1,
userScalable: false,
viewportFit: 'cover',
};
interface Props {
children: React.ReactNode;
params: { lng: string };
}
export function generateStaticParams() {
return locales.map((locale) => ({ locale }));
}
export default async function RootLayout(props: Readonly<Props>) {
const { children, params } = props;
const { lng } = params;
unstable_setRequestLocale(lng);
const messages = await getMessages();
return (
<html lang={lng} dir={dir(lng)}>
<GoogleAnalytics gaId="G-**********" />
<GoogleTagManager gtmId="GTM-********" />
<body>
<NextIntlClientProvider messages={messages}>
<div className="wrapper">{children}</div>
</NextIntlClientProvider>
</body>
</html>
);
}
src/helper/googleAnalytics.tsx
'use client';
import React, { useEffect } from 'react';
import Script from 'next/script';
const GoogleAnalytics = (props?: any) => {
const googleAnalyticsID = 'G-**********'; // process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS;
return (
<>
<Script
strategy="lazyOnload"
src={`https://www.googletagmanager.com/gtag/js?id=${googleAnalyticsID}`}
/>
<Script id="" strategy='lazyOnload'>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){
window && window.dataLayer && window.dataLayer.push(arguments);
}
gtag('js', new Date());
gtag('config', '${googleAnalyticsID}', {
page_path: window.location.pathname,
});
`}
</Script>
</>
);
}
export default GoogleAnalytics;