Fixing "Uncaught ReferenceError: ga is not defined"

19 Sep ยท by Tim Kamanin ยท 2 min read

Are you staring at a pesky "Uncaught ReferenceError: ga is not defined" console error message right now?

Yeah, I feel your pain, I've just lost two hours of my life figuring it out. Let me save this time for you.

This message means ga is not available for the code that tries to use it. And ga stands for "Google Analytics". ga is a global object used by the legacy analytics.js snippet.

Let's troubleshoot

1) Open a debug console and type: window.ga. Did you get undefined? If yes, that go to the next step. If not, then your problem is in code order. Make sure https://www.google-analytics.com/analytics.js gets included before you call ga() function. This one is easy, and that wasn't my case. Let's move on.

2) Okay, so window.ga says "undefined" to you. If you're sure that Google analytics is enabled on your website (via wordpress/drupal or whatever else plugin, just like in my case), the only reason why it's still not working is because your website includes Google analytics in a modern, "Global Site Tag" way. View a source of your page and try to locate a https://www.googletagmanager.com/gtag/js string. Got it? Yeah, right. It means you can't use ga() in your code and you need either:

a) Rollback to the legacy analytics.js code, or b) convert existing code, so it's compatible with gtag.js. Read here for more info on migrating from analytics.js to gtag.js.

My case

My issue was related to Google Optimize. Every doc and tutorial was telling me to use ga('require', 'GTM-XXXXXX'); to enable Google Optimize container. But since I had Google Analytics included as gtag.js I needed to use:

gtag('config', 'UA-GA_TRACKING-CODE', { 'optimize_id': 'GTM-XXXXXX'})

Did it help? You're welcome! Follow me on Twitter @timonweb and let me know if this post was helpful.

Want to get more ๐Ÿ”ฅ tips like this one?

Subscribe to get notified about new dev tutorials