Skip to content

Commit

Permalink
feat(#350): add nonce prop (#392)
Browse files Browse the repository at this point in the history
  • Loading branch information
MauricioRobayo authored Feb 22, 2023
1 parent 80b0cd3 commit b0b5766
Showing 1 changed file with 8 additions and 3 deletions.
11 changes: 8 additions & 3 deletions src/components/GoogleAnalytics.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ type GoogleAnalyticsProps = {
strategy?: ScriptProps["strategy"];
debugMode?: boolean;
defaultConsent?: "granted" | "denied";
nonce?: string;
};

type WithPageView = GoogleAnalyticsProps & {
Expand All @@ -27,6 +28,7 @@ export function GoogleAnalytics({
strategy = "afterInteractive",
defaultConsent = "granted",
trackPageViews,
nonce,
}: WithPageView | WithIgnoreHashChange): JSX.Element | null {
const _gaMeasurementId =
process.env.NEXT_PUBLIC_GA_MEASUREMENT_ID ?? gaMeasurementId;
Expand All @@ -47,15 +49,18 @@ export function GoogleAnalytics({
return (
<>
<Script src={`${gtagUrl}?id=${_gaMeasurementId}`} strategy={strategy} />
<Script id="nextjs-google-analytics">
<Script id="nextjs-google-analytics" nonce={nonce}>
{`
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
${defaultConsent === "denied" && `gtag('consent', 'default', {
${
defaultConsent === "denied" &&
`gtag('consent', 'default', {
'ad_storage': 'denied',
'analytics_storage': 'denied'
});`}
});`
}
gtag('config', '${_gaMeasurementId}', {
page_path: window.location.pathname,
${debugMode ? `debug_mode: ${debugMode},` : ""}
Expand Down

0 comments on commit b0b5766

Please sign in to comment.