Skip to content

Commit

Permalink
Restore react-ga4
Browse files Browse the repository at this point in the history
  • Loading branch information
louis-md committed Jun 4, 2024
1 parent 78de049 commit 5816690
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
"node-fetch": "^3.3.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"react-ga4": "^2.1.0",
"release-it": "^17.3.0",
"remark-gfm": "^4.0.0",
"shelljs": "^0.8.5",
Expand Down
41 changes: 39 additions & 2 deletions pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@ import {
experimental_extendTheme as extendMuiTheme
} from '@mui/material/styles'
import type { AppProps } from 'next/app'
import { type ReactElement } from 'react'
import { useEffect, type ReactElement } from 'react'
import Head from 'next/head'
import ReactGA from 'react-ga4'
import { GoogleTagManager } from '@next/third-parties/google'

import MetaTags from '../components/MetaTags'
import { CookieBanner } from '../components/CookieBanner'
import { CookieBannerContextProvider } from '../components/CookieBanner/CookieBannerContext'
import {
CookieBannerContextProvider,
useCookieBannerContext
} from '../components/CookieBanner/CookieBannerContext'
import { createEmotionCache } from '../styles/emotion'
import '../styles/styles.css'
import '@code-hike/mdx/dist/index.css'
Expand All @@ -25,6 +29,38 @@ const clientSideEmotionCache = createEmotionCache()
// Extended theme for CssVarsProvider
const cssVarsTheme = extendMuiTheme(theme as CssVarsThemeOptions)

let isAnalyticsInitialized = false

const GoogleAnalytics: React.FC = () => {
const { isAnalyticsEnabled } = useCookieBannerContext()

// Enable/disable tracking
useEffect(() => {
if (
process.env.NEXT_PUBLIC_IS_PRODUCTION === 'true' &&
isAnalyticsEnabled
) {
ReactGA.initialize(
String(process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_TRACKING_ID),
{
gaOptions: {
cookieFlags: 'SameSite=Strict;Secure',
cookieDomain: process.env.NEXT_PUBLIC_GOOGLE_ANALYTICS_DOMAIN
}
}
)
isAnalyticsInitialized = true
return
}

if (!isAnalyticsEnabled && isAnalyticsInitialized) {
// Injected script will otherwise remain in memory until new session
location.reload()
}
}, [isAnalyticsEnabled])
return null
}

const App = ({
Component,
pageProps,
Expand All @@ -44,6 +80,7 @@ const App = ({
<CssVarsProvider theme={cssVarsTheme}>
<CookieBannerContextProvider>
<CssBaseline />
<GoogleAnalytics />
<Component {...pageProps} />
<CookieBanner />
</CookieBannerContextProvider>
Expand Down
7 changes: 7 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 5816690

Please sign in to comment.