Created
January 23, 2023 10:42
-
-
Save ugnmura/8c3f7ef528a68847ef04cd60b01b92cc to your computer and use it in GitHub Desktop.
Google Analytics Integration with Next.js worker scripts
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
import React from "react"; | |
import Head from "next/head"; | |
import Script from "next/script"; | |
import { Partytown } from "@builder.io/partytown/react"; | |
export interface GoogleAnalyticsProps { | |
measurementId: string; | |
} | |
export const GoogleAnalytics: React.FC<GoogleAnalyticsProps> = ({ | |
measurementId, | |
}) => { | |
return ( | |
<> | |
<Head> | |
<Partytown forward={["dataLayer.push"]} /> | |
</Head> | |
<Script | |
id="data-partytown-config" | |
data-partytown-config | |
dangerouslySetInnerHTML={{ | |
__html: ` | |
partytown = { | |
lib: "/_next/static/~partytown/", | |
forward: ["gtag"] | |
}; | |
`, | |
}} | |
/> | |
<Script | |
id="gtag-init" | |
type="text/partytown" | |
dangerouslySetInnerHTML={{ | |
__html: ` | |
window.dataLayer = window.dataLayer || []; | |
window.gtag = function gtag(){window.dataLayer.push(arguments);} | |
gtag('js', new Date()); | |
gtag('config', '${measurementId}', { | |
page_path: window.location.pathname, | |
}); | |
`, | |
}} | |
/> | |
<Script | |
strategy="worker" | |
src={`https://www.googletagmanager.com/gtag/js?id=${measurementId}`} | |
/> | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment