Skip to main content

Adding Plausible to Astro

Here's how to add Plausible Analytics to your Astro site.

Add privacy-friendly analytics to your Astro site. Try Plausible free for 30 days, no credit card required.

The script tag is the simplest setup and picks up changes from your Plausible site settings. Choose the NPM package if you want to bundle the tracker with your app or pin its version. Use one method to avoid counting pageviews twice.

Add the script tag to your base layout​

  • Open the layout that wraps all your pages, for example src/layouts/Layout.astro.
  • Paste your Plausible snippet inside the <head>. You can copy your snippet from the Site Installation area of the General section in your site settings.
  • Add is:inline to both script tags. Without it, Astro processes and bundles the scripts instead of leaving them as they are.
src/layouts/Layout.astro
---
const { title } = Astro.props
---

<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>{title}</title>
<script is:inline async src="https://plausible.io/js/pa-XXXXX.js"></script>
<script is:inline>
window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
plausible.init()
</script>
</head>
<body>
<slot />
</body>
</html>

Your snippet has a different script location than the example above. Use the https://plausible.io/js/pa-XXXXX.js URL from your own snippet. With the script tag, optional measurements are controlled in your site settings.

Using the ClientRouter​

Astro's <ClientRouter /> (called <ViewTransitions /> in older versions) turns your site into a single-page app with client-side navigation. It changes the URL with pushState, so Plausible counts those page changes automatically. Keep the snippet in the shared layout's <head> so it loads once. See single-page application support for details.

Use the NPM package instead​

If you want the tracker to be part of your own build, use the official NPM package. Install it:

npm install @plausible-analytics/tracker

Then call init once in a script in your base layout. Astro bundles this script and loads it as a module, so it runs once per page load:

src/layouts/Layout.astro
<script>
import { init } from '@plausible-analytics/tracker'

init({
domain: 'example.com'
})
</script>

Use the domain exactly as you added it to your Plausible account. Optional measurements are off by default and are configured in init. See all configuration options.

Verify your installation​

Open your deployed site and follow an internal link to a second page. In the realtime dashboard, look for both paths under Top Pages. Plausible ignores visits on localhost by default. If a page is missing, check your installation.

What's next?​

Ready to ditch Google Analytics?

Start your free trial today