stacks-analytics

$npx mdskill add stacksjs/stacks/stacks-analytics

Configures and generates analytics scripts for Stacks applications

  • Automatically configures Fathom or self-hosted analytics in a Stacks application.
  • Deploys tracking scripts via @stacksjs/analytics and config/analytics.ts configuration files.
  • Determines appropriate analytics setup based on privacy and compliance requirements.
  • Delivers configured analytics scripts to the application for seamless integration.

SKILL.md

.github/skills/stacks-analyticsView on GitHub ↗
---
name: stacks-analytics
description: Use when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Analytics

Privacy-friendly analytics with Fathom and self-hosted driver support.

## Key Paths
- Core package: `storage/framework/core/analytics/src/`
- Configuration: `config/analytics.ts`

## Drivers

### Fathom Analytics
Privacy-focused, GDPR-compliant analytics. Requires a Fathom account.

### Self-Hosted Analytics
Generate tracking scripts for self-hosted analytics:

```typescript
import { generateSelfHostedScript, getSelfHostedAnalyticsHead, generateInlineScript } from '@stacksjs/analytics'

// Generate tracking script tag
const script = generateSelfHostedScript({
  siteId: 'ABCDEF',
  apiEndpoint: 'https://analytics.myapp.com/api/event',
  honorDnt: true,                // respect Do Not Track
  trackHashChanges: false,       // track hash URL changes
  trackOutboundLinks: true       // track external link clicks
})

// Generate head configuration for STX
const headConfig = getSelfHostedAnalyticsHead({
  siteId: 'ABCDEF',
  apiEndpoint: 'https://analytics.myapp.com/api/event'
})

// Generate inline script (no external JS file)
const inline = generateInlineScript(config)
```

## SelfHostedConfig Interface

```typescript
interface SelfHostedConfig {
  siteId: string                  // unique site identifier
  apiEndpoint: string             // analytics API URL
  honorDnt?: boolean              // respect Do Not Track header
  trackHashChanges?: boolean      // track SPA hash navigation
  trackOutboundLinks?: boolean    // track clicks to external sites
}
```

## config/analytics.ts

```typescript
{
  driver: 'fathom',              // 'fathom' | 'google-analytics'
  drivers: {
    googleAnalytics: {
      trackingId: ''              // GA tracking ID
    },
    fathom: {
      siteId: ''                  // Fathom site ID
    }
  }
}
```

## Dashboard Integration

Analytics dashboard at `/dashboard/analytics` displays:
- Page views and visitor counts
- Traffic sources
- Popular pages
- Engagement metrics

## Gotchas
- Default driver is `fathom` — privacy-focused by default
- Self-hosted analytics require your own analytics endpoint
- `honorDnt: true` respects browser Do Not Track settings
- `escapeAttr()` is used internally to prevent XSS in generated scripts
- Google Analytics tracking ID goes in config, not env (unless you override)
- Analytics scripts are generated server-side and injected into page head
- Fathom is a paid service — self-hosted is free but requires infrastructure
- `trackOutboundLinks` adds click handlers to external `<a>` tags

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.
stacks-browserUse when working with browser/frontend functionality in Stacks — the useAuth composable (login, register, logout, token management), Stripe billing utilities (loadCardElement, confirmPayment), the API fetch client, browser model loading, or auto-imported browser utilities. Covers @stacksjs/browser.