Astro's component-based architecture and island-first approach make it ideal for adding tracking scripts through layout components that work efficiently with static generation and partial hydration.
Add tracking script to your Astro app
Astro's recommended approach is to create a layout component that includes your tracking script, which can then be reused across all your pages for consistent tracking.
- Create or open your main layout at
src/layouts/Layout.astro
- Add the tracking script in the
<head>
section - Use this layout across your pages:
---
export interface Props {
title: string;
}
const { title } = Astro.props;
---
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="description" content="Astro description" />
<meta name="viewport" content="width=device-width" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>{title}</title>
<script
async
defer
src="https://affonso.io/js/pixel.min.js"
data-affonso="YOUR_PUBLIC_PROGRAM_ID"
data-cookie_duration="YOUR_COOKIE_DURATION"
></script>
</head>
<body>
<slot />
</body>
</html>
Alternative: Use Astro's environment variables with the PUBLIC_
prefix to manage your Program ID dynamically.
Testing
- Start your Astro dev server:
npm run dev
- Visit
localhost:4321?atp=test
(or your configured port) - Check browser DevTools → Console → type
window.affonso_referral
- Build and deploy:
npm run build
- Verify tracking in your Affonso dashboard
Note: Astro's island architecture means client scripts run after page load, which works well with Affonso's deferred loading.
Next Steps
Once installed, you can access affiliate referral data and pass it to your payment provider. Connect your payment provider →