Last active
December 4, 2022 00:05
-
-
Save shinshin86/09cb469c7332b4dfaa3e39611a2f5202 to your computer and use it in GitHub Desktop.
Google analytics setup example at Next.js with TypeScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// pages/_document.tsx | |
// And setup to next.config.js ↓↓↓ | |
/* | |
module.exports = { | |
publicRuntimeConfig: { | |
TRACKING_ID: process.env.TRACKING_ID || '', | |
}, | |
serverRuntimeConfig: { | |
TRACKING_ID: process.env.TRACKING_ID || '', | |
}, | |
}; | |
*/ | |
// Reference: https://nextjs.org/docs/api-reference/next.config.js/runtime-configuration | |
import Document, { Html, Head, Main, NextScript } from 'next/document'; | |
import getConfig from 'next/config'; | |
const { publicRuntimeConfig, serverRuntimeConfig } = getConfig(); | |
const trackingId: string = publicRuntimeConfig.TRACKING_ID || serverRuntimeConfig.TRACKING_ID; | |
export default class MyDocument extends Document { | |
render() { | |
return ( | |
<Html> | |
<Head> | |
{trackingId && ( | |
<> | |
<script | |
async | |
src={`https://www.googletagmanager.com/gtag/js?id=${trackingId}`} | |
/> | |
<script | |
dangerouslySetInnerHTML={{ | |
__html: ` | |
window.dataLayer = window.dataLayer || []; | |
function gtag(){dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', '${trackingId}', { | |
page_path: window.location.pathname, | |
}); | |
`, | |
}} | |
/> | |
</> | |
)} | |
</Head> | |
<body> | |
<Main /> | |
<NextScript /> | |
</body> | |
</Html> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment