Astro
Add Rybbit analytics to your Astro site
Astro pages share a layout component that renders the <html> document. Add the snippet to the <head> of that layout and every page that uses it is tracked.
Get your tracking snippet
In your Rybbit dashboard, open Site Settings → Tracking Script and copy your snippet. It looks like this:
<script src="https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID" defer></script>YOUR_SITE_ID is the numeric ID of your site. If you self-host Rybbit, app.rybbit.io is the domain of your own instance.
Add the snippet to Astro
Open your shared layout, usually src/layouts/Layout.astro, and paste the snippet inside <head>. Add is:inline so Astro leaves the tag as-is instead of bundling it:
---
const { title } = Astro.props;
---
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
<script is:inline src="https://app.rybbit.io/api/script.js?siteId=YOUR_SITE_ID" defer></script>
</head>
<body>
<slot />
</body>
</html>If you do not use a shared layout, add the same tag to the <head> of each page in src/pages/. A layout is easier to maintain.
Astro builds a multi-page site by default, so each navigation is a full page load and a new pageview. With view transitions enabled, client-side navigation is tracked automatically when the URL changes.
Verify installation
Open your live site in a new tab and click through a few pages. Within a few seconds the pageviews appear in the Rybbit dashboard.
If nothing shows up:
- View the page source and search for
script.js?siteId=to confirm the snippet is on the page. - Open the browser Network tab and check that
script.jsreturns200and thatPOSTrequests go to/api/track. - Disable ad blockers, or set up a proxy so the script loads from your own domain.
- See the script troubleshooting guide for other common causes.
Track custom events
Call window.rybbit.event() from a client-side <script> in any .astro component, or from inside a framework island the same way you would in that framework.
<button id="tracked-button">Click me</button>
<script>
document.getElementById("tracked-button")?.addEventListener("click", () => {
if (window.rybbit) {
window.rybbit.event("astro_button_click", { source: "TrackedButton.astro" });
}
});
</script>Troubleshooting
- Pageviews missing with view transitions: this is rare. If it happens, listen for Astro's
astro:after-swapevent in a client-side script and callwindow.rybbit.pageview(); test the default behaviour first. - Proxying through your own domain: Astro can serve the script from your domain with SSR middleware. See the Astro proxy guide.
Next steps
- Track custom events such as signups, purchases and button clicks.
- Identify users to connect sessions to accounts.
- Proxy the script through your own domain to bypass ad blockers.
- Script attributes let you skip or mask URLs and tag events.