Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shinshin86/09cb469c7332b4dfaa3e39611a2f5202 to your computer and use it in GitHub Desktop.
Save shinshin86/09cb469c7332b4dfaa3e39611a2f5202 to your computer and use it in GitHub Desktop.
Google analytics setup example at Next.js with TypeScript
// 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