Created
October 16, 2023 10:29
-
-
Save JoueBien/82b7215d225136bcea812dc597bd30e7 to your computer and use it in GitHub Desktop.
Next JS 13 GTM using @analytics/google-tag-manager
This file contains 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 { | |
PropsWithChildren, | |
FC, | |
createContext, | |
useState, | |
useEffect, | |
} from "react"; | |
import Analytics, { AnalyticsInstance } from "analytics"; | |
import googleTagManager from "@analytics/google-tag-manager"; | |
import { useRouter } from "next/router"; | |
export const GlobalNextAnalyticsContext = createContext<{ | |
analytics?: AnalyticsInstance; | |
}>({}); | |
export const GlobalNextAnalyticsProvider: FC< | |
PropsWithChildren & { | |
appName: string; | |
gtmId: string; | |
} | |
> = ({ children, appName, gtmId }) => { | |
// Global State | |
const { asPath } = useRouter(); | |
const [analytics, setAnalytics] = useState<AnalyticsInstance | undefined>( | |
undefined | |
); | |
// On Mount set up analytics | |
useEffect(() => { | |
setAnalytics( | |
Analytics({ | |
// Call this whatever you like. | |
app: appName, | |
plugins: [ | |
// Only register GMT in production | |
...(process.env.NODE_ENV === "production" | |
? [ | |
googleTagManager({ | |
containerId: gtmId, // GTM_CONTAINER_ID, | |
enabled: true, | |
}), | |
] | |
: []), | |
], | |
}) | |
); | |
}, []); | |
// On page change fire page change | |
useEffect(() => { | |
if (analytics) { | |
analytics?.page(); | |
} | |
}, [analytics, asPath]); | |
return ( | |
<GlobalNextAnalyticsContext.Provider value={{ analytics }}> | |
{children} | |
</GlobalNextAnalyticsContext.Provider> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment