How to distinguish preload events in Rails controller

Full disclosure: I never used Posthog, and did not try the idea I’m proposing. It’s just a rough sketch.

I think just detecting if it was a prefetch would not help you. Because the actual click will not trigger another request. Whatever the prefetch got as a response would be used instead.

The simplest thing I can imagine would work:

Put the data that posthog captures in some kind of queue with UUID:

p = PostHogCache.create(payload: {distinct_id: @current.user.id, ...}

and set this UUID in a cookie,

cookies.signed[:post_hog_id] = {value: p.id, expires: 20.seconds.from_now } #*

and have a script attached to document.onload (or one of turbo own events Turbo Reference) that would send some kind of request POST /posthog/visit/UUID

(*) I think the way cookies work is that your browser will overwrite the value if many requests are made. The risk here is that two subsequent prefetch requests arrive out of order. Depending on how critical occasional inconsistency is for you, you might need to find a more robust solution.

1 Like