Snowplow on NextJS getServerSideProps

Hello everyone,

Is it possible to call trackStructEvent from @snowplow/browser-tracker inside a getServerSideProps function in nextjs? If not, how can I track those events?

I don’t see why not - I’d avoid doing anything in the function that isn’t asynchronous so you aren’t blocking / delaying rendering but from a Snowplow perspective this should be fine.,

Hmm, interesting. I do not have access to snowplow directly, but the team in charge have told me that they are not able to see the events I’m triggering in the server-side (they do see my client side events with the same function). I’m also myself not able to see the using the snowplow chrome extension.

No, because the getServerSideProps function runs server side, you’ll need to setup the Node tracker to fire events from that function; the browser-tracker will only work in the client-side code.

To properly “stitch” the server-side events to the client side events you’re firing on the actual page, you’ll need to use the context.req parameter to set the client properties; most of the important stuff (domain_userid, domain_sessionid, domain_sessionidx) should be in the _sp_id.* cookie, context.req.headers (user agent, lang, IP if you have loadbalancers/proxies upstream) or context.req.socket.address().address if clients connect to your server directly for some reason. Network User ID may be possible too (dedicated cookie, usually called sp) if you’re using a first-party collector domain.

I think there’s meant to be a util function to make pulling this info from the cookie easier on the roadmap, but until then you’ll have to split the cookie value into fields yourself. The fields are just dot-separated (except index-0, cookieDisabled isn’t actually stored in the cookie, so count from index-1 as index-0).

Depending on your build system you might need dynamic import trickery for the node tracker to make sure it doesn’t go into your client-side bundle, but that’s hard to advise on.

(Alternatively just include the information you want to track in the props itself and track the event from the browser-tracker when you render the actual page).

You can’t usetrackStructEvent from@snowplow/browser-tracker directly in getServerSideProps in Next.js. It runs server-side. Instead, trigger`trackStructEvent on the client side using a useEffect hook in your component after fetching data server-side. This ensures proper event tracking in the browser.