gatsby-plugin-segment-js icon indicating copy to clipboard operation
gatsby-plugin-segment-js copied to clipboard

Cannot read property 'track' of undefined

Open peduarte opened this issue 5 years ago • 8 comments

Hello,

I've followed the instructions on the Readme.

  • Added plugin to gatsby-config
{
	resolve: 'gatsby-plugin-segment-js',
	options: {
		prodKey: 'KEY_HERE',
	},
}
  • Then, tracking an event:
window.analytics.track('test');

On development mode, I get Cannot read property 'track' of undefined.

Am I doing something wrong?

I know I can check if window.analytics exists, but the docs imply that this plugin was handling that?

peduarte avatar Apr 12 '19 08:04 peduarte

this is weird. do you have an ad blocker? which browser are you using. how does this work on production, or you only see the issue on dev? when you check for window.analytics in your chrome console, what happens?

please let me know the above, or if the issue is solved, please comment what the fix was. thanks!

benjaminhoffman avatar May 15 '19 04:05 benjaminhoffman

I had the same issue, and window.analytics returned undefined for me in the Chrome console. However, this was only on localhost, and it works fine on production.

daveyheuser avatar Jul 20 '19 15:07 daveyheuser

what about when you do yarn build ... i assume it works then?

and you've checked incognito browser, with no ad blockers, right?

benjaminhoffman avatar Jul 21 '19 15:07 benjaminhoffman

I also had this issue, window.analytics returned undefined, I've tried yarn build but no luck

peterphan1996 avatar Jul 24 '19 02:07 peterphan1996

just in case someone comes across this, it means you probably don't have a DEV key defined. the prod key will only run in production, local host is dev environment.

geoffgolder-ah avatar Nov 14 '19 19:11 geoffgolder-ah

I hit the same issue, until I wrapped my window.analytics.track in a if (window.analytics) conditional.

It looks to me like the analytics.js script isn't being loaded into the page header. This is true even on production build. When looking at the chrome console (adblocker disabled), I have no window.analytics options available.

alexfornuto avatar Nov 14 '19 23:11 alexfornuto

I had this problem because I copied the code snippet from the docs which contains a junk code snippet:

customSnippet: '!function(){var analytics=window.analytics||[];...;analytics.load("${writeKey}");analytics.page();}}();'

I had to remove that. 😦

149203 avatar Nov 03 '21 20:11 149203

Without a valid env variable, analytics doesn't load; Set NODE_ENV to production or development

export NODE_ENV=production

or

export NODE_ENV=development

Senthil-Sivanath avatar Dec 28 '22 13:12 Senthil-Sivanath