analytics-debugger / ga4mp

GA4MP
MIT License
40 stars 11 forks source link

Failing to send tracking events in server-side context #14

Closed quadmachine closed 1 year ago

quadmachine commented 1 year ago

Hi, I'm trying to send a tracking event using your library, it's running in a Nuxt app, within SSR context, so basically Node, and window and other browser specific stuff is not available. Sending fails with error:

 ERROR  Could not send tracking event window is not defined                                                              14:22:13

  at clientHints (node_modules/@analytics-debugger/ga4mp/dist/ga4mp.umd.js:251:5)
  at Object.trackEvent (node_modules/@analytics-debugger/ga4mp/dist/ga4mp.umd.js:603:7)
  at sendToTackingServer (modules/serverSideTracking/helper/serverSideTrackingHelper.ts:216:14)
  at _default (modules/serverSideTracking/hooks/trackSrrPageLoad.ts:134:53)
  at node_modules/hable/dist/hable.js:1:990
  at node_modules/hable/dist/hable.js:1:208
  at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
  at async Nuxt.callHook (node_modules/hable/dist/hable.js:1:959)
  at async nuxtMiddleware (node_modules/@nuxt/server/dist/server.js:147:5)

This is my code:

const ga4mp = require('@analytics-debugger/ga4mp/dist/ga4mp.umd.js')

ga4track = ga4mp(['G-XXXXXXXXXX'], {
  user_id: undefined,
  client_id: seid,
  non_personalized_ads: true,
  debug: true,
  endpoint: process.env.SERVER_SIDE_TRACKING_COLLECTOR,
})
ga4track.setEventsParameter(
  'api_secret',
  process.env.SERVER_SIDE_TRACKING_API_KEY
)

ga4track.trackEvent('page_view')

Maybe I'm missing some configuration option, or perhaps it's a bug? Not sure, any help is appreciated.

thyngster commented 1 year ago

Hi @quadmachine could you provide a simple repo to replicate this?

quadmachine commented 1 year ago

Sure, I've created a repo here, this is a basic Nuxt starter, only relevant stuff would be in the trackSrrPageLoad.ts here https://stackblitz.com/edit/nuxt-starter-2nzhse?file=README.md,modules%2FserverSideTracking%2Fhooks%2FtrackSrrPageLoad.ts everything else is Nuxt boilerplate.

Just run yarn dev to start the app, it will try to track the initial page load once it build but will throw with the error ReferenceError: window is not defined

Thanks for any help <3

quadmachine commented 1 year ago

@thyngster I've perhaps fixed the issue, in clientHints function check on line 211 doesn't break if I change from

if (window && !('navigator' in window)) {

to

if (typeof window === 'undefined') {

Perhaps I can make a MR for this?

thyngster commented 1 year ago

I'm publishing a fix today

thyngster commented 1 year ago

@quadmachine A fix is in place in version 0.0.5

quadmachine commented 1 year ago

@thyngster Can confirm the fix is working, tnx!