Implementing download tracking with Google Analytics for file links

I’m running a website that offers various downloadable files including .rar, .7z and .pkg formats. I want to monitor how many times these files get downloaded through Google Analytics.

Someone mentioned I could add onclick="gtag('event', 'download', {'file_name': 'document.extension'})" to my download links, but I’m confused about what exactly should go in the file_name part.

Do I just put the actual filename there? And are there any extra JavaScript libraries or tracking codes I need to include on my site to make this work properly? Any help would be appreciated!

yep, use the real filename like ‘myfile.rar’. just ensure the gtag script is loaded first - GA4 should manage it. also, check the network tab to confirm if your events are tracked right.

The onclick approach works but gets messy fast with lots of download links. I built something similar last year and switched to a cleaner solution.

Skip adding onclick to every link. Use event delegation instead. Drop this JavaScript on your pages:

document.addEventListener('click', function(e) {
  if (e.target.tagName === 'A' && e.target.href.match(/\.(rar|7z|pkg|zip|pdf)$/i)) {
    gtag('event', 'file_download', {
      'file_name': e.target.href.split('/').pop(),
      'link_url': e.target.href
    });
  }
});

This automatically tracks any link ending with your file extensions. Way easier than updating every download link manually.

For file_name, just use the actual filename. GA4 shows it in your events report exactly as you send it.

Make sure your GA4 measurement ID is installed first. The gtag function won’t work without it.

Once it’s running, check your GA4 Events section under Reports. You’ll see file_download events within a few hours.