I am currently using GA4 + Growthbook + NextJS, ho...
# ask-questions
a
I am currently using GA4 + Growthbook + NextJS, however I am using Growthbook server side so I can use the middleware to A/B test pages and redirect users to the page they need to view. I need to send the "experiment_viewed" event to Google Analytics for it to show in Growthbook what would be the best way to do this? Currently have this code snippet in the trackingCallback but it is not submitting events to GA4
Copy code
const gb = new GrowthBook({
    apiHost: process.env.NEXT_PUBLIC_GROWTHBOOK_API_HOST,
    clientKey: process.env.NEXT_PUBLIC_GROWTHBOOK_CLIENT_KEY,
    enableDevMode: true,
    trackingCallback: async (experiment, result) => {
      console.log('Tracking event:', experiment.key, result.variationId || result.key)

      // Server-side GA4 tracking for experiments
      try {
        // Construct GA payload with proper parameter structure for GA4
        const payload = {
          client_id: clientId,
          user_id: userId, // Including user ID for cross-device tracking
          user_properties: {
            gb_user_id: { value: userId },
          },
          events: [
            {
              name: 'experiment_view', // GA4 typically uses snake_case
              params: {
                experiment_id: experiment.key,
                variation_id: result.variationId || result.key,
                experiment_name: experiment.name || experiment.key,
              },
            },
          ],
        }

        // GA4 Measurement Protocol endpoint
        const endpoint = `<https://www.google-analytics.com/mp/collect?measurement_id=${process.env.GA_MEASUREMENT_ID}&api_secret=${process.env.GA_API_SECRET}>`

        // Send event to Google Analytics with better error reporting
        const response = await fetch(endpoint, {
          method: 'POST',
          body: JSON.stringify(payload),
          headers: {
            'Content-Type': 'application/json',
          },
        })

        if (!response.ok) {
          const errorText = await response.text()
          console.error('GA4 API error:', response.status, errorText)
        } else {
          console.log('GA4 event sent successfully')
        }
      } catch (error) {
        console.error('Error sending GA event:', error)
      }
    },
  })
It is logging "GA4 Event is sent successfully, but it is not showing up
f
How long has it been?
a
A few days
f
huh
a
Also been looking on the RealTime view in Google Analytics still nothing unfortunately
f
looks like the code is executing correctly - but perhaps that endpoint is failing?
the fetch?
a
When logging the response I get a 204 status code
f
huh
no experiment_view events? we usually call it experiment_view*ed*
doesn't matter, just want to make sure you're checking for the right event
a
No nothing there, also queried in BigQuery for it, but I didn't find it
f
can you just use curl or postman or something to send an event and see if you can see it in GA4?
I wonder if there is something not right with that call
a
The response I am getting:
Copy code
{
  "validationMessages": []
}
When using CURL:
Copy code
curl -X POST "<https://www.google-analytics.com/debug/mp/collect?measurement_id=G-XXX&api_secret=XXXXXXXX>" \
-H "Content-Type: application/json" \
-d '{
  "client_id": "123456.7890123456",
  "events": [{
    "name": "experiment_viewed",
    "params": {
      "experiment_id": "test-experiment",
      "variation_id": "A"
    }
  }]
}'
Without the '/debug' I get no response and no error or anything
Copy code
curl -X POST "<https://www.google-analytics.com/mp/collect?measurement_id=G-XXX&api_secret=XXXXXXXX>" \
-H "Content-Type: application/json" \
-d '{
  "client_id": "123456.7890123456",
  "events": [{
    "name": "experiment_viewed",
    "params": {
      "experiment_id": "test-experiment",
      "variation_id": "A"
    }
  }]
}'
@fresh-football-47124 got any insights on what I could do?
f
does that event show up in GA4?