@vdaluz/astro-opt-in-analytics
v0.10.0
Published
Consent-first analytics for Astro: an opt-in prompt, a script gate, and zero tracking requests until the visitor says yes.
Maintainers
Readme
@vdaluz/astro-opt-in-analytics
Consent-first analytics for Astro. The tracker script does not exist on the page until the visitor says yes: no requests, no fingerprinting surface, nothing to block. An opt-in prompt asks once, the answer is remembered, and refusing is exactly as easy as accepting.
Built for Umami first, with a small adapter interface for other trackers. Ships raw .astro and .ts - the consuming app's Astro/Vite compiles them (no prebuild step). Used in production by the sites under Consumers.
Why opt-in
Most "privacy-respecting analytics" setups still track by default and put the burden of blocking on the visitor. This package flips the default: tracking is off until a real yes. That costs you data. That is the point.
- Zero requests until consent. Trackers activate only after a stored grant. Denied or unanswered means no request ever fires.
- Global Privacy Control is an answer.
navigator.globalPrivacyControl === truecounts as a no. The prompt never shows; asking again would be its own dark pattern. - Anti-dark-pattern by construction. Equal-weight buttons, decline first in DOM order, Esc or dismissal means deny, no overlay, no scroll lock. These are hard-coded, not configurable.
- Changeable, both directions.
openConsentPrompt()(or any element withdata-open-analytics-prompt) reopens the prompt, e.g. from a footer "Analytics preferences" link.
Install
npm install @vdaluz/astro-opt-in-analyticsPeer dependency: astro >= 6.
Use
// src/config/analytics.ts
import { defineAnalyticsConfig, umami } from '@vdaluz/astro-opt-in-analytics';
export const analytics = defineAnalyticsConfig({
tracker: umami({
src: 'https://umami.example.net/script.js',
websiteId: '00000000-0000-0000-0000-000000000000',
excludeSearch: true,
}),
prompt: {
message: 'Can I count your visit? Anonymous, cookieless, self-hosted analytics. No is a fine answer.',
accept: 'Count me',
decline: 'No thanks',
// Optional: a plain inline text link after the message, never a third button.
learnMore: { href: '/privacy', text: 'Learn more' },
},
});---
// src/layouts/Layout.astro
import ConsentGate from '@vdaluz/astro-opt-in-analytics/ConsentGate.astro';
import ConsentPrompt from '@vdaluz/astro-opt-in-analytics/ConsentPrompt.astro';
import { analytics } from '../config/analytics';
---
<!-- Gate before prompt, both once per page -->
<ConsentGate config={analytics} />
<ConsentPrompt config={analytics} />Footer link, no JS required:
<button type="button" data-open-analytics-prompt>Analytics preferences</button>Placement
<ConsentPrompt placement="corner" /> (the default) docks a card bottom-right. <ConsentPrompt placement="bar" /> renders a full-width bottom bar instead, for sites whose centered article column leaves no gutter wide enough for the corner card.
Placement only changes the desktop layout - at <=640px both render the same full-width bottom sheet. The bar variant's own styling (message left, buttons right) only applies at >=641px, and its inner content column caps at max-width: 64rem, centered, so it lines up with a typical centered article width rather than spanning edge-to-edge.
Example
ConsentPrompt live on vdaluz.com, first visit, no stored decision:

Privacy explainer page
PrivacyExplainer.astro renders the substantive sections of a /privacy page - what's collected, how consent gates it, and which tools are behind it - sourced directly from your analytics config so the page can't drift from what's actually injected. Wrap it in your own layout and hero copy:
---
// src/pages/privacy.astro
import Layout from '../layouts/Layout.astro';
import PrivacyExplainer from '@vdaluz/astro-opt-in-analytics/PrivacyExplainer.astro';
import { analytics } from '../config/analytics';
---
<Layout title="Privacy & Analytics">
<h1>Privacy & analytics</h1>
<PrivacyExplainer config={analytics} locale={Astro.currentLocale} />
</Layout>The "tools behind it" list only shows trackers that carry a privacyInfo field. Both bundled adapters set a sensible default - umami() points at umami.is/privacy, cloudflareBeacon() at cloudflare.com/web-analytics - override privacyInfo per adapter call to customize the label or add a description clause about your specific deployment (e.g. "that I run myself, on my own infrastructure"). A tracker with no privacyInfo is simply omitted from the list. privacyInfo.collects?: Localized[] renders as a trailing "Also collects: ..." clause on that tool's own entry - use it for a custom tracker whose payload includes something beyond the package-wide baseline (the bundled adapters don't set one: umami()'s specifics are already covered by the default "what's collected" copy below, and cloudflareBeacon()'s internal payload isn't something this package can verify).
Every other string PrivacyExplainer renders - headings, the "what's collected" body and bullets, the GPC/reopen copy - can be overridden with a strings prop typed against the exported PrivacyExplainerStrings: <PrivacyExplainer config={analytics} strings={{ whatsCollectedBody: { default: '...' } }} />. Each key is replaced wholesale (not deep-merged), so pass a full Localized value for any key you override. Use this to add a fourth locale, or to correct a claim the built-in copy can't know about your specific setup. A Localized value is matched by exact locale, then falls back to the primary subtag (pt-BR matches a pt entry), then to default.
Cloudflare Web Analytics
cloudflareBeacon({ token }) builds the manual (non-auto-injected) beacon script tag, gated by consent like any other adapter:
import { cloudflareBeacon } from '@vdaluz/astro-opt-in-analytics';
cloudflareBeacon({ token: '00000000000000000000000000000000' });This requires switching off Cloudflare's edge auto-injection for the zone (dashboard: Web Analytics → Manage Site → enable "JS snippet installation") - otherwise the auto-injected beacon loads unconditionally alongside this one, bypassing consent.
Custom events
trackEvent(name, data?) (from ./client) reports a custom event directly to Umami's /api/send, gated on live consent the same way the pageview tracker is: it no-ops when consent is denied, undecided, GPC applies, or the page has no Umami tracker (e.g. Cloudflare Beacon only - it has no custom-event API, so trackEvent is Umami-only by design). Consent is re-checked at call time, not at page load.
Affiliate click tracking
Affiliate click tracking is wired in automatically by bootConsentGate() - no extra setup needed. It's a delegated click listener for any [data-affiliate-key] anchor on the page, the contract @vdaluz/astro-affiliate's <AffiliateLink> renders. On click it reports an affiliate-click event with { key, channel, program } - channel defaults to 'default' when the link didn't pass one, so Umami's per-channel breakdown is always populated. Middle-click (auxclick) is not counted; this sits inside the same consent-gated undercount the rest of the package already accepts.
Harmless on pages with no affiliate links - the listener still binds (cheap, one delegated handler) but never matches anything.
How it works
ConsentGatereads a versioned record from localStorage (opt-in-analytics:consent). Grant: every configured tracker activates - Umami by posting a pageview straight to/api/send(see Why Umami skips the official script), anything else (e.g. Cloudflare Beacon) by injecting its<script>tag. Anything else: nothing loads.trackeralso accepts an array of adapters; one grant activates all of them, and the prompt copy should disclose every tracker it covers.ConsentPromptshows only when there is no decision and no GPC signal. The answer is stored as{ v, decision, at }.- Bump
consentVersionin your config when what you track changes; older stored decisions re-prompt. - A denial after a grant applies from the next navigation (an already-active tracker is not torn down; nothing new ever activates).
- Stored consent expires after
consentMaxAgeDays(default 365) and re-prompts the visitor - applies to a decline too, not just a grant. Set0orInfinityto disable expiry entirely.
Why Umami skips the official script
Umami's own tracker script initializes by reading document.currentScript - the <script> element it's currently running from - to find its config attributes. That's null for a script this package injects dynamically after consent, so the official script silently never initializes: no error, no network request beyond the initial (harmless) script fetch. umami() sidesteps this by posting directly to Umami's documented /api/send endpoint instead, reimplementing the parts of the official script this package needs (session-cache token, domain filtering, Do Not Track, search/hash stripping). cloudflareBeacon() has no such dependency and is unaffected - it still loads via an injected <script> tag.
Styling
The prompt reads CSS custom properties with sensible dark fallbacks: --surface, --fg, --accent, --on-accent. Same token contract as @vdaluz/astro-blog: values are R G B channel triplets (e.g. --surface: 26 26 26;), consumed as rgb(var(--name)). If your app already defines those, the prompt matches your theme with zero extra CSS.
PrivacyExplainer.astro is different: it's styled entirely with Tailwind token utility classes (text-fg, text-muted, text-accent, space-y-12, and similar), not CSS custom properties. For it to render styled at all, your app must:
- Alias the token colors in
tailwind.config.mjs- see@vdaluz/astro-blog's README for the exact color-alias block, since both packages share the same token names. - Include this package in your Tailwind
contentglob:./node_modules/@vdaluz/astro-opt-in-analytics/**/*.astro- without it,PrivacyExplainer's utility classes are never generated and the page renders unstyled.
Without both, PrivacyExplainer still works functionally (it's sourced from your live config, so it can't drift from what's actually injected) but renders as unstyled text.
Contributing
Issues welcome. PRs by discussion - open an issue first for anything beyond a typo or docs fix.
Releasing
Maintainer-only. Releases are tag-triggered and published to npm via GitHub Actions (Trusted Publishing / OIDC, no token secret):
- Test before tagging:
npm pack, install the tarball into a scratch Astro app (or a consumer locally),astro check && astro build. - Bump the version with
npm version X.Y.Z --no-git-tag-version, which updatespackage.jsonandpackage-lock.jsontogether, then commit both. - Tag
vX.Y.Zand push the tag. Pushing the tag runs.github/workflows/publish.yml, which type-checks, tests, verifies the tag matchespackage.json's version, and only then runsnpm publish. - Confirm the version is live:
npm view @vdaluz/astro-opt-in-analytics version. Consumers bump their own semver pin once it's confirmed live - see this package's CHANGELOG.md for what changed.
Consumers
- vdaluz.com
- imperfectsystems.com
- wq1k.com
- freetoolbox.net
- vicstradamus.com (
umami()andcloudflareBeacon()) - deepcutatlas.com
- roomforstars.com (components wired in; its Umami site ID is still a placeholder, so it doesn't track yet)
License
MIT
