Skip to content

Add trackr.link analytics to Astro

Add the trackr.link snippet to the layout every Astro page shares, keep it working with view transitions and send custom events from client scripts.

An Astro site needs the snippet once, in the <head> of the layout its pages share. Static builds and server rendering work the same way, and navigation with view transitions is counted on its own.

1. Copy your snippet

Open your site in trackr.link and copy its snippet. It looks like this, with your own site id:

<script defer data-site="YOUR_SITE_ID" src="https://pulse.trackr.link/t.js"></script>

2. Add it to your layout

Put the snippet in the <head> of the layout every page uses, such as src/layouts/Layout.astro, and add is:inline:

---
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 defer data-site="YOUR_SITE_ID" src="https://pulse.trackr.link/t.js"></script>
    </head>
    <body>
        <slot />
    </body>
</html>

is:inline tells Astro to render the tag exactly as written. The tracker reads its site id from the data-site attribute of its own <script> tag, and a script that Astro bundles loses that tag, so the tracker can't find its site id and sends nothing.

Pages that render their own <html> instead of using the layout, such as a standalone landing page or 404.astro, need the snippet too. Add it to each layout once. A page that renders two copies counts every view twice.

On a Starlight docs site, add the snippet through the head option in astro.config.mjs:

starlight({
    title: 'My Docs',
    head: [
        {
            tag: 'script',
            attrs: {
                src: 'https://pulse.trackr.link/t.js',
                'data-site': 'YOUR_SITE_ID',
                defer: true,
            },
        },
    ],
});

3. View transitions

Without <ClientRouter />, each page is a full page load, and each load is counted.

With <ClientRouter />, Astro swaps pages without a full load and changes the URL with history.pushState. The tracker records each of those as a pageview, as it does the back and forward buttons. Astro runs a script with a given src once, so the tracker stays loaded across navigation. Don't add data-astro-rerun to the snippet. A copy that runs again counts later pageviews more than once.

The tracker records the path only. /pricing?plan=pro and /pricing#faq count as /pricing, and UTM tags in the query are kept as campaign data.

4. Send custom events

For a button or link, add data-trackr-event="cta_click", plus props such as data-trackr-prop-location="hero". The tracker sends the event on click, and it keeps working after view transitions without any setup:

<a href="/pricing" data-trackr-event="cta_click" data-trackr-prop-location="hero">See pricing</a>

For an action that has to succeed first, call the global trackr function from a client script:

<form id="signup" action="/api/signup" method="post">
    <!-- ... -->
</form>

<script>
    function setUpSignupForm() {
        const form = document.querySelector<HTMLFormElement>('#signup');

        form?.addEventListener('submit', async (event) => {
            event.preventDefault();
            const response = await fetch(form.action, {
                method: 'POST',
                body: new FormData(form),
            });

            if (response.ok) {
                window.trackr?.('event', 'signup', { plan: 'free' });
            }
        });
    }

    setUpSignupForm();
</script>

With <ClientRouter />, Astro runs this script once, but it replaces the form on each navigation. Replace the last line with document.addEventListener('astro:page-load', setUpSignupForm), so the listener is added again after each page swap. Components from React, Vue, Svelte and other frameworks call window.trackr the same way, from their client-side code.

Frontmatter and API endpoints run on the server, where there is no window, so send events from the browser only. With TypeScript, declare the function once, in src/env.d.ts:

interface Window {
    trackr?: (
        command: 'event',
        name: string,
        props?: Record<string, string | number | boolean>,
    ) => void;
}

5. Development and preview deployments

trackr.link records hits from your site's domain, its subdomains and localhost. Visits to astro dev and astro preview on localhost are counted, while a preview deployment on a host such as my-site.netlify.app or my-site.pages.dev is not, because it isn't on your domain. To keep development out of your numbers, render the snippet only in production builds:

{import.meta.env.PROD && (
    <script is:inline defer data-site="YOUR_SITE_ID" src="https://pulse.trackr.link/t.js"></script>
)}

Or keep it everywhere and run localStorage.setItem('trackr_ignore', '1') in the browser console of every browser you develop in. That browser then sends nothing.

6. Content Security Policy

If your site sends a Content-Security-Policy, from your host's headers or from Astro's security.csp option, allow the tracker's origin in both script-src and connect-src. The script loads from it and sends its hits back to it.

7. Check that it works

Deploy, then open your site in an ordinary browser window and click through a few pages. Your dashboard opens when the first pageview arrives. Hits from automated browsers, such as Playwright or Puppeteer, are dropped as bots, so test by hand. If nothing arrives, view the page source and search for data-site. If the tag is missing, the page doesn't use the layout with the snippet.

If you use Claude Code or Codex, copy the setup prompt from your site's page in trackr.link instead. The agent adds the snippet and your events, and saves your goals and funnels.

8. Read your first visits

Every visit counts in a channel, such as Organic Search, Email or AI. Channels and UTM parameters lists the rules that decide which one, and AI traffic shows how visits from ChatGPT, Claude, Perplexity and other assistants are recognized. To tag the links you share in campaigns, use the UTM builder.

Free for one site. No credit card.

Create free account