Adding goatcounter analytics to a Next.js website
1 minute read
I’m a fan of GoatCounter analytics as a privacy-friendly web analytics platform. I’ve been using it on this blog for a year or so and it’s been enlightening to see which of my poorly-formed notes people have found interesting!
I’ve been developing more with Next.js which has led me to have to figure out how to add it into that stack. Some of the articles that I found online made it seem quite complicated, so I thought I’d put this note together to explain how I did it.
You’re given this script to add at some point in the HTML on your website. It calls the script at "//gc.zgo.at/count.js"
and passes it the information data-goatcounter="https://YOUR_SITE_PROJECT_HERE.goatcounter.com/count"
. Essentially this tells GoatCounter when someone has loaded a page.
1
2
3
4
5
<script
data-goatcounter="https://YOUR_SITE_PROJECT_HERE.goatcounter.com/count"
async
src="//gc.zgo.at/count.js">
</script>
To add it to a Next.js website you need to rewrite that script within a Script
component, call that component in the layout page and then set the content security policy to allow the page to make requests to GoatCounter.
This is what the Next.js Script component looks like:
1
2
3
4
5
6
7
8
9
10
11
import Script from 'next/script'
...
// called after body of the layout page completes
<Script
data-goatcounter="https://YOUR_SITE_PROJECT_HERE.goatcounter.com/count"
async
src="//gc.zgo.at/count.js"
/>
I was building on top of the Tailwind Next.js starter blog for this project, so I just needed to extend the section in next.config.js
that added the domain gc.zgo.at
to the ContentSecurityPolicy
constant. You may have to figure out exactly what this looks like for your implementation.