Angular 4 Universal - Google Analytics / Client Side Only Code

1.2k Views Asked by At

So I'm trying to migrate our site from a static SPA to Angular Universal Rendered Server Side and I'm having an issue with Google Analytics.

In my SPA I define GA in the index.html via the html script but with Server Side Rendering this obviously doesn't make sense.

I tried to:

if(ga) {
   ga.create(...);
}

to get it to run only when ga is initialized (which it should be on the client but not on the server), but I get an undefined object error (ReferenceError: ga is not defined - on the if (ga) line), where not defined should be a falsy value.

So I tried to search how to run code client side only and I found isBrowser, but that's from angular2-universal, and I can't find anything like that in platform-server or platform-browser...

Thanks!

1

There are 1 best solutions below

0
On BEST ANSWER

So checking that the typeof window isn't undefined did it. I'll probably abstract this out to a service but this got me past the first hump for a POC.

if ( typeof window != 'undefined' )