Skip to content

Analytics

There are a few ways ways to add analytics to your app.

The first option is one that’s built in, you can inject header or footer scripts into the settings of the site from your Keystatic setup, or by adding it to src/data/settings.json:

settings.json
...
"customscripts": {
"header": "",
"footer": ""
},
...

Any code added to the header or footer sections of customscripts will automatically be added to your site via middleware in the appropriate place..

2. Manually Adding Analytics to your Layout

Section titled “2. Manually Adding Analytics to your Layout”

Alternatively, you can also go straight to the source and add it to the src/layouts/HeadLayout.astro file. For example to add Vercel’s Analytics to it, we would do the following:

HeadLayout.astro
---
import { AstroSeo } from "@astrolib/seo";
import { config } from "@/config/config";
import Analytics from "@vercel/analytics/astro";
const { pageDescription, pageTitle, pageUrl, siteName } = Astro.props;
---
<head>
<link rel="icon" type="image/png" href="/icon.png" />
<link rel="sitemap" href="/sitemap-index.xml" />
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<meta name="generator" content={Astro.generator} />
<Analytics />
<AstroSeo
title={pageTitle}
titleTemplate={`%s | ${config.site.name}`}
description={pageDescription}
canonical={pageUrl}
openGraph={{
url: pageUrl,
title: pageTitle,
description: pageDescription,
site_name: siteName,
}}
/>
<title>{pageTitle} | {config.site.name}</title>
</head>

So those are two options that are available to add your Google Analytics, or other analytics here as well, and the site will use it on every page.