benjaminhoffman / gatsby-plugin-segment-js

Gatsby plugin for segment.com's analytic.js snippet
https://www.npmjs.com/package/gatsby-plugin-segment-js
MIT License
40 stars 28 forks source link

Double page tracking via gatsby-ssr.js and gatsby-browser .js #50

Closed esaborit4code closed 1 year ago

esaborit4code commented 2 years ago

Enabling trackPage option makes these lines to get run one after all, which ends in duplicate page tracking:

First this from gatsby-ssr.js: https://github.com/benjaminhoffman/gatsby-plugin-segment-js/blob/897db9ba7f2b0bab91aab3c87bac1682fcf36396/src/gatsby-ssr.js#L39-L41

or this if delayLoad is enabled: https://github.com/benjaminhoffman/gatsby-plugin-segment-js/blob/897db9ba7f2b0bab91aab3c87bac1682fcf36396/src/gatsby-ssr.js#L55

and, then, this other from gatsby-browser.js: https://github.com/benjaminhoffman/gatsby-plugin-segment-js/blob/897db9ba7f2b0bab91aab3c87bac1682fcf36396/src/gatsby-browser.js#L15

In addition, gatsby-ssr and gatsby-broswer calls to page differ. SSR verison does not pass anything and browser passes the document.title as param.

shixish commented 2 years ago

We're seeing this too. I'm just not using trackPage configuration option and instead I'm using this in gatsby-browser.js:

exports.onRouteUpdate = () => {
  //Fire off the Segment tracking call
  window.analytics && window.analytics.page();
};

This way it doesn't fire the extra analytics.page calls from gatsby-ssr.js, and we just fire them manually.

newhouse commented 2 years ago

Sounds like this is real. I'll have a look. Is it just straightforward to repro?

timmartin commented 2 years ago

This is hitting me as well. I can reproduce it quite easily, but I don't have it in a public project. If it would be useful, I could put together a public repo that illustrates it. I think it's just a matter of adding the plugin with trackPage = true, though.

izzymiller commented 1 year ago

Would a good fix be to set a flag in the config as to whether you are actually making use of server side rendering, and to not fire the call in gatsby-ssr.js if not?

I think a lot of people using Styled Components (myself included) have a gatsby-ssr.js despite not using server side rendering intentionally for some reason that I only vaguely remember— but builds fail if i remove it.

newhouse commented 1 year ago

This is fixed in 4.0.0, and there is now a includeTitleInPageCall option where you can choose if you want to send the page title with the call. That's the only thing close to a "breaking change" in 4.0, despite it being a "major" version bump.