How to distinguish preload events in Rails controller

Hi, I have implemented PostHog Rails gem in all of my controllers in almost every method. The problem is that when I hover at the link, it triggers prefetch event, which calls my Rails controller and that triggers PostHog event. Is there any way how to distinguish these prefetch calls in Rails controller without deactivating the preload? Thanks!

Here’s an example of what I mean:

def index
  @people = @current_user.people

  # I want to call `capture` only when the user really clicks on the link
  posthog.capture(distinct_id: @current_user.id,
                   event: '$pageview',
                   properties: { '$current_url': people_url})
end

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

Hi @greg, thanks a lot for your answer! The most important part for me is the fact, that the browser then doesn’t send a new request. I missed that bit when trying to debug it, thanks!

The other solution is basically using their own JavaScript library and sending those events from frontend directly. That was something I wanted to originally avoid, but now looks like an alternative to what you proposed with cookie solution.

The outcome is that it’s not possible to detect preload event and it’s rather better to keep it simple and just use the library (or roll with backend solution while knowing that some of these “clicks” are not clicks).

1 Like