Skip to content

Commit 84a58c7

Browse files
committed
add Google Analytics #53
1 parent c2d1e29 commit 84a58c7

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

Diff for: pages/_document.js

+31
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,26 @@
1+
/* eslint-disable react/no-danger */
2+
13
import React from 'react';
4+
import Router from 'next/router';
25
import JssProvider from 'react-jss/lib/JssProvider';
36
import Document, { Head, Main, NextScript } from 'next/document';
47

58
import getContext from '../lib/context';
69

10+
require('dotenv').config();
11+
12+
const gaTrackingId = 'process.env.GA_TRACKING_ID';
13+
14+
Router.onRouteChangeComplete = () => {
15+
if (window.gtag) {
16+
window.gtag('config', window.gaTrackingId, {
17+
page_location: window.location.href,
18+
page_path: window.location.pathname,
19+
page_title: window.document.title,
20+
});
21+
}
22+
};
23+
724
class MyDocument extends Document {
825
render() {
926
return (
@@ -61,6 +78,20 @@ class MyDocument extends Document {
6178
}
6279
`}
6380
</style>
81+
<script async src={`https://www.googletagmanager.com/gtag/js?id=${gaTrackingId}`} />
82+
<script
83+
dangerouslySetInnerHTML={{
84+
__html: `
85+
window.gaTrackingId = '${gaTrackingId}';
86+
window.dataLayer = window.dataLayer || [];
87+
function gtag(){
88+
dataLayer.push(arguments);
89+
}
90+
gtag('js', new Date());
91+
gtag('config', '${gaTrackingId}');
92+
`,
93+
}}
94+
/>
6495
</Head>
6596
<body
6697
style={{

0 commit comments

Comments
 (0)