Adding goatcounter analytics to a Next.js website
How to add goatcounter analytics to a Next.js website.
GoatCounter analytics is a privacy-friendly web analytics platform worth recommending. Using it on this blog for over a year has revealed which notes attract readers most—insights difficult to gain otherwise.
Integrating GoatCounter into Next.js initially appeared difficult based on available guides. This note explains a straightforward approach.
GoatCounter provides a script snippet to add to your website’s HTML. The script loads from "//gc.zgo.at/count.js" and registers page loads via the data-goatcounter attribute pointing to your project’s endpoint.
<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:
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"
/>
When using the Tailwind Next.js starter blog, extend the next.config.js content security policy to include the domain gc.zgo.at. Your specific configuration will depend on your implementation’s existing CSP settings.