在Next Script中嵌入Google Analytics

Maple

Problem

笔者基于已有的库部署了ChatGPT-Next-Web,希望添加Google Analytics用来查看用户使用情况。

Solution

参考官网的说明Next Script for Google Analytics | Next.js (nextjs.org)

If you are using the gtag.js script to add analytics, use the next/script component with the right loading strategy to defer loading of the script until necessary.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import Script from 'next/script'

function Home() {
return (
<div className="container">
<Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" />
<Script id="google-analytics">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</div>
)
}

export default Home

Take ChatGPT-Next-Web as an example, you need to edit GPT-Web/app/layout.tsx.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import Script from 'next/script'

export default function RootLayout({
children,
}: {
children: React.ReactNode;
}) {
return (
<html lang="en">
<head>
<meta name="config" content={JSON.stringify(getClientConfig())} />
<link rel="manifest" href="/site.webmanifest"></link>
<script src="/serviceWorkerRegister.js" defer></script>
<Script src="https://www.googletagmanager.com/gtag/js?id=GA_MEASUREMENT_ID" />
<Script id="google-analytics">
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());

gtag('config', 'GA_MEASUREMENT_ID');
`}
</Script>
</head>
<body>{children}</body>
</html>
);
}
  • Title: 在Next Script中嵌入Google Analytics
  • Author: Maple
  • Created at : 2023-11-15 16:05:15
  • Updated at : 2023-11-15 18:04:45
  • Link: https://www.maple367.eu.org/Tools/Website/在next-script中嵌入google-analytics/
  • License: This work is licensed under CC BY-NC-SA 4.0.
Comments
On this page
在Next Script中嵌入Google Analytics