Skip to content

Commit

Permalink
feat: track google analytics clientIds (#3264)
Browse files Browse the repository at this point in the history
* store client id in localstorage

* remove newline

* use React.ga

* fix import
  • Loading branch information
tinaszheng authored Feb 9, 2022
1 parent b5a72cd commit 440ac0c
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/components/analytics/GoogleAnalyticsReporter.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import ReactGA from 'react-ga'
import { RouteComponentProps } from 'react-router-dom'
import { getCLS, getFCP, getFID, getLCP, Metric } from 'web-vitals'

import { GOOGLE_ANALYTICS_CLIENT_ID_STORAGE_KEY } from './index'

function reportWebVitals({ name, delta, id }: Metric) {
ReactGA.timing({
category: 'Web Vitals',
Expand Down Expand Up @@ -31,5 +33,15 @@ export default function GoogleAnalyticsReporter({ location: { pathname, search }
useEffect(() => {
ReactGA.pageview(`${pathname}${search}`)
}, [pathname, search])

useEffect(() => {
// typed as 'any' in react-ga -.-
ReactGA.ga((tracker: any) => {
if (!tracker) return

const clientId = tracker.get('clientId')
window.localStorage.setItem(GOOGLE_ANALYTICS_CLIENT_ID_STORAGE_KEY, clientId)
})
}, [])
return null
}
5 changes: 5 additions & 0 deletions src/components/analytics/index.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import ReactGA from 'react-ga'
import { isMobile } from 'utils/userAgent'

export const GOOGLE_ANALYTICS_CLIENT_ID_STORAGE_KEY = 'ga_client_id'
const GOOGLE_ANALYTICS_ID: string | undefined = process.env.REACT_APP_GOOGLE_ANALYTICS_ID

const storedClientId = window.localStorage.getItem(GOOGLE_ANALYTICS_CLIENT_ID_STORAGE_KEY)

if (typeof GOOGLE_ANALYTICS_ID === 'string') {
ReactGA.initialize(GOOGLE_ANALYTICS_ID, {
gaOptions: {
storage: 'none',
storeGac: false,
clientId: storedClientId ?? undefined,
},
})
ReactGA.set({
Expand Down

0 comments on commit 440ac0c

Please sign in to comment.