How to Host Google Analytics Locally
Hosting your Google Analytics tracking script locally is a simple trick that can give your website a small but meaningful performance boost. Instead of forcing your visitors' browsers to fetch an extra file from Google's servers, you can serve it directly from your own. This article will walk you through exactly why you'd want to do this and provide clear, step-by-step instructions for getting it set up.
Why Bother Hosting Google Analytics Locally?
You might be wondering if this is worth the effort. For site owners obsessed with speed and performance - as we all should be - the answer is a clear yes. Here are the three main benefits of self-hosting the Google Analytics script.
1. Improved Website Speed
This is the biggest reason. Every file your website loads from an external source, like Google's servers, is another HTTP request a visitor's browser has to make. This adds a little bit of time to your page load speed due to DNS lookups, latency, and connection time.
When you host the analytics script on your own server, you eliminate that external request. The browser can fetch the script using the same connection it's already using to load your site's own files. This often leads to faster load times, happy users, and better scores in tools like Google PageSpeed Insights. It gives you one more optimized asset that search engines will appreciate when evaluating your Core Web Vitals.
2. Greater Control Over Caching
When you use the standard Google Analytics snippet, the script is served from Google's CDN with a very short browser cache time (often just a few hours). Google does this to ensure users quickly get updates to the tracking script.
However, by hosting the file yourself, you gain full control over the caching headers. You can set a much longer cache expiry time. This means after a user's first visit, the script will load directly from their browser's local cache on subsequent visits, making return trips to your site even faster. Because you'll be setting up an automated process to keep the script updated on your server, you can enjoy these caching benefits without worrying about using an outdated file.
Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
3. Removes a Third-Party Dependency
Google's servers are incredibly reliable, but they aren't immune to outages. While rare, any issue with Google's CDN could potentially impact your site's ability to track users or even, in some cases, affect page loading. By serving the script from your own domain, you remove one more external reliance. It's a small step, but it gives you more direct control over your site's assets and reduces the number of things that are outside your immediate control.
Some also argue there are minor privacy benefits, as it reduces direct calls to third-party domains, which can be seen favorably by privacy-focused browser extensions and users.
Your Step-by-Step Guide to Self-Hosting Google Analytics
The process involves three main parts: grabbing a copy of the script, setting up a system to keep it updated, and modifying your website's code to load it. Let's walk you through it.
Step 1: Get a Local Copy of the Google Analytics Script
First, you need to download the official script file from Google. The URL depends on whether you're using Universal Analytics (UA) or Google Analytics 4.
- For Universal Analytics (analytics.js): The file is located at https://www.google-analytics.com/analytics.js.
- For Google Analytics 4 (gtag.js):
The URL includes your unique measurement ID:
https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX. Make sure to replaceG-XXXXXXXXXXwith your actual Measurement ID.
Simply navigate to the correct URL in your browser, and you'll see a wall of code. Right-click and "Save As..." to download the file. Give it a simple, memorable name like local-ga.js and save it to your computer.
Next, use FTP or your hosting control panel's File Manager to upload this file to your website's server. A good practice is to create a dedicated folder for JavaScript files, like /js/, in your website's root directory (e.g., in public_html). Upload your local-ga.js file into that folder.
Step 2: Keep Your Local Script Fresh (The Automation Part)
This step is critical. Google updates its tracking scripts regularly with bug fixes and new features. If you just "set it and forget it" with your downloaded file, your tracking could break in the future.
The solution is to automate the process of downloading a fresh copy of the script every day. The most common way to do this is with a cron job, a scheduled task that runs on a server. Most hosting providers let you manage cron jobs through cPanel or similar dashboards.
You can create a new cron job that runs once per day (e.g., at midnight) and executes a command to grab the latest script and overwrite your local file.
Here’s an example command using wget, a common command-line utility for downloading files. Replace the path and URL with your own:
Example for Universal Analytics:
0 0 * * * wget -q -O /home/yourusername/public_html/js/local-ga.js https://www.google-analytics.com/analytics.jsExample for Google Analytics 4:
0 0 * * * wget -q -O /home/yourusername/public_html/js/local-ga.js "https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"What this does:
0 0 * * *: Runs every day at midnightwget -q -O: Downloads quietly and saves as the specified file/home/yourusername/public_html/js/local-ga.js: Your server's path to the local script- The URL: The source script to download (must match your GA version)
Step 3: Update Your Website's Tracking Snippet
Now that the script is hosted on your server and automatically updating, modify your site's tracking code to load it from your local directory instead of Google.
For Universal Analytics (analytics.js):
Original snippet:
<!-- Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r,i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(),a=s.createElement(o),
m=s.getElementsByTagName(o)[0],a.async=1,a.src='https://www.google-analytics.com/analytics.js',m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga'),
ga('create', 'UA-XXXXX-Y', 'auto'),
ga('send', 'pageview'),
</script>
<!-- End Google Analytics -->Modified snippet:
<!-- Locally Hosted Google Analytics -->
<script>
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r,i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date(),a=s.createElement(o),
m=s.getElementsByTagName(o)[0],a.async=1,a.src='/js/local-ga.js',m.parentNode.insertBefore(a,m)
})(window,document,'script','/js/local-ga.js','ga'), // Changed the URL
// GA creation and send calls remain the same
ga('create', 'UA-XXXXX-Y', 'auto'),
ga('send', 'pageview'),
</script>
<!-- End Locally Hosted Google Analytics -->For Google Analytics 4 (gtag.js):
Original snippet:
<!-- Google tag (gtag.js) -->
<script async src="https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX"></script>
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', 'G-XXXXXXXXXX'),
</script>Modified snippet:
<!-- Locally Hosted Google tag (gtag.js) -->
<script async src="/js/local-ga.js"></script> <!-- Changed the src -->
<script>
window.dataLayer = window.dataLayer || [],
function gtag(){dataLayer.push(arguments),}
gtag('js', new Date()),
gtag('config', 'G-XXXXXXXXXX'),
</script>Free PDF · the crash course
AI Agents for Marketing Crash Course
Learn how to deploy AI marketing agents across your go-to-market — the best tools, prompts, and workflows to turn your data into autonomous execution without writing code.
Step 4: Confirm Everything Is Working
After these changes, verify your setup:
- Check in your browser’s developer tools:
- Open your site, right-click, select "Inspect", go to the "Network" tab.
- Reload the page.
- Look for your
local-ga.jsfile. It should load successfully with a 200 status. - There should be no requests to
google-analytics.comorgoogletagmanager.comfor the script.
- Check Google Analytics real-time reports:
- Log into your GA account, open the real-time report.
- Visit your site in a new tab or incognito window.
- Your visit should appear within a minute, confirming tracking works.
Easier Methods for WordPress Users
If you use WordPress and don’t want to mess with cron jobs and code updates, there are plugins designed for this.
Plugins like Perfmatters, FlyingPress, or WP Rocket have features to host Google Analytics locally. You just enter your Tracking ID, enable the feature, and the plugin manages downloading, updating, and replacing the script automatically.
Final Thoughts
Self-hosting the Google Analytics script can improve your site’s load time, give you more control over caching, and remove reliance on third-party servers. Downloading the script, setting up automation, and adjusting your tracking code is a straightforward way to optimize your website’s performance.
Remember, understanding the data is just as important as collecting it. If you want an easier way to analyze your data and generate reports, check out Graphed. It allows you to get real-time dashboards and insights from GA and other marketing tools in plain English—saving you time and simplifying your marketing analysis.
Related Articles
How to Create Facebook Ads API for Claude Code
Create a Meta Marketing API access token that never expires, using a system user, so Claude Code can pull Facebook ad reports and manage campaigns.
ClickHouse vs Postgres: When to Switch to Columnar
Comparing ClickHouse vs PostgreSQL means matching storage architecture to workload. Row storage wins for transactions. Columnar wins for scan-heavy analytics.
Google Ads for Orthodontists: Get More Booked Consults
Most orthodontic Google Ads campaigns waste money on low-intent searches. The problem is structure, not the platform.