How to add analytics to Astro

Add the tracker to the layout that wraps your Astro pages. Mark it is:inline so Astro leaves it as-is instead of bundling it.

No cookies, no banner ~3 KB script About 2 minutes

Before you start

Create a free Cool Analytics account and add your site. You'll get a site ID — replace YOUR_SITE_ID in the code below with it. The dashboard shows the snippet with your ID already filled in.

Install on Astro

  1. 1Open your base layout, often src/layouts/Layout.astro or BaseLayout.astro.
  2. 2Paste the snippet inside <head> and add the is:inline directive.
  3. 3Build and deploy. If you use view transitions (<ClientRouter />), page swaps are tracked automatically.
src/layouts/Layout.astro
<head>
  <meta charset="utf-8" />
  <script is:inline defer src="https://coolanalytics.dev/hb.js" data-site="YOUR_SITE_ID"></script>
</head>

Check that it works

Open your live site in a new tab, then open your Cool Analytics dashboard. Your visit appears on the live map within seconds — with the page you're on, where you came from and your browser.

Nothing showing up? Make sure you're looking at the published site (not a preview or editor), that an ad blocker isn't blocking the script, and that you're not testing on localhost.

Track signups, purchases and clicks

Pageviews, sources, countries and outbound link clicks are tracked automatically. For the moments that matter to you, send a custom event. Events named like a signup show up as signups, and events with an amount show up as revenue — on the live map and per traffic source.

custom events
// anywhere in your Astro site's browser code
window.hb?.track("signup");

// with an amount, it shows up as revenue
window.hb?.track("purchase", { amount: 49 });

Astro tips

  • Without is:inline, Astro would try to process and bundle the script. With it, the tag is output exactly as written.
  • With view transitions, the tracker guards against loading twice and records each navigation as a pageview.
  • Visits from localhost are ignored so your own development doesn't count. To test locally, add data-dev="1" to the script tag for a moment — then remove it.

Want to keep your own visits out of the stats? Open your site once with #hb-ignore at the end of the URL. That browser is excluded until you visit with #hb-track.

Astro analytics FAQ

My Astro site has several layouts. Where do I put it?+

In each top-level layout, or better, in a shared <Head> component that all layouts use. Loading it twice on one page is harmless — the tracker only starts once.

Does it work with Starlight?+

Yes. Add it through the head option in your Starlight config in astro.config.mjs, with tag 'script' and the src, defer and data-site attributes.

Does the script affect my Lighthouse score?+

It's about 3 KB and loads with defer, so the impact is negligible.

See who's on your Astro site right now.

One line of code. No cookies. 7 days free.