Ad

How To Use Google Analytics Function In Angular 5 (SSR With Universal)?

- 1 answer

I'm trying to implement google analytics functionality to my Angular 5 site.

But the instruction from this discussion:

Angular 4+ using Google Analytics

doesn't make sense because in my case the whole code executes on server-side and ga function just can't work properly (because it uses DOM elements).

Can you tell me, what is the best practise to use Google analytics in SSR Angular site?

Thank you in advance!

Ad

Answer

I found the solution! Just make two versions of site and use Nginx to route bots to SSR version. Nginx config:

server {
listen 80;
server_name site.ru www.site.ru;

root   /var/www/site.ru/dist/browser;
index  index.html;

location / {
   try_files $uri @prerender;
}

location @prerender {
#proxy_set_header X-Prerender-Token YOUR_TOKEN;

set $prerender 0;
if ($http_user_agent ~* ("Googlebot\/2.1|YandexBot|googlebot|yahoo|bingbot|baiduspider|yandex|yeti|yodaobot|gigabot|ia_archiver|facebookexternalhit|twitterbot|developers\.google\.com|spider|crawl|slurp|bot")) {
    set $prerender 1;
}
if ($args ~ "_escaped_fragment_") {
    set $prerender 1;
}

#if ($http_user_agent ~ "Prerender") {
#    set $prerender 0;
#}
#if ($uri ~ "\.(js|css|xml|less|png|jpg|jpeg|gif|pdf|doc|txt|ico|rss|zip|mp3|rar|exe|wmv|doc|avi|ppt|mpg|mpeg|tif|wav|mov|psd|ai|xls|mp4|m4a|swf|dat|dmg|iso|flv|m4v|torrent|ttf|woff)") {
#    set $prerender 0;
#}

#resolve using Google's DNS server to force DNS resolution and prevent caching of IPs
resolver 8.8.8.8;

if ($prerender = 1) {
proxy_pass http://XX.XXX.XXX.XXX:4002;

}
if ($prerender = 0) {
    rewrite .* /index.html break;
}
}
}
Ad
source: stackoverflow.com
Ad