Plausible Analytics Integration Guide
Technology: plausible · Category: monitoring · Last reviewed: 2026-10-20
Source: https://tech-stack.codeamanilabs.org/guide/plausible
Insight:
Plausible is the web-analytics layer: cookieless, no personal data, so a site that only runs Plausible needs no cookie banner. Proxy the per-site
pa-XXXXX.jsscript first-party, define goals (Lead,Purchase) that match event names exactly, and pull the Stats API v2 into ananalytics_dailyrollup on a signed QStash cron so/portal/analyticsreads from Postgres. Plan gates matter: the Stats API, revenue goals and funnels need Business; the Sites API needs Enterprise. Self-hosted CE must be on v3.2.1 or later (CVE-2026-8467 RCE fix).
██████╗ ██╗ █████╗ ██╗ ██╗███████╗██╗██████╗ ██╗ ███████╗
██╔══██╗██║ ██╔══██╗██║ ██║██╔════╝██║██╔══██╗██║ ██╔════╝
██████╔╝██║ ███████║██║ ██║███████╗██║██████╔╝██║ █████╗
██╔═══╝ ██║ ██╔══██║██║ ██║╚════██║██║██╔══██╗██║ ██╔══╝
██║ ███████╗██║ ██║╚██████╔╝███████║██║██████╔╝███████╗███████╗
╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═════╝ ╚══════╝╚═╝╚═════╝ ╚══════╝╚══════╝
Plausible Analytics Integration Guide
Focus: Cookieless web analytics for codeAmani sites and multi-tenant provider sites: the per-site script (proxied first-party), custom-event and revenue goals, funnels, the Stats API v2 rollup into Postgres, the Sites API for tenant provisioning, and self-hosted Community Edition.
Overview
Plausible is an open-source (AGPL), lightweight web analytics product. It sets no cookies, stores no IP addresses or persistent identifiers, and reports aggregates only. Plausible Cloud processes and stores all data in the EU, and a DPA applies to every customer automatically. Unique visitors are counted with a daily-rotating hash of IP + User-Agent + domain, so the same person is not linked across days or sites.
For codeAmani this means product sites can measure traffic and conversions without a consent banner, and the provider-site platform (Motionstack) gets per-tenant stats that roll up into its own Postgres. See Privacy, GDPR and US state laws below for what "no banner" does and doesn't cover.
flowchart LR
A["Site / tenant page"] --> B["First-party proxy<br/>/pa/js/script.js"]
B --> C["Plausible Cloud<br/>or self-hosted CE"]
A -. "plausible('Lead')" .-> C
S["Server route<br/>(success page)"] -. "POST /api/event" .-> C
C --> E["Stats API v2<br/>POST /api/v2/query"]
Q["QStash schedule<br/>(signed)"] --> F["/api/cron/plausible-rollup"]
F --> E
F --> G[("analytics_daily<br/>Neon Postgres")]
G --> H["/portal/analytics"]
What changed recently (2025-10 → 2026-10)
| Date | Change | Impact |
|---|---|---|
| Oct 2025 | New per-site tracking script pa-XXXXX.js + plausible.init() |
Old script.*.js extensions are legacy; data-api, data-exclude, data-include and multi-domain sending are gone in the new script |
| Nov 2025 | CE v3.1.0 ships the new script; interactive flag on events |
Non-interactive events don't affect bounce rate |
| Feb 2026 | Goals with up to three custom-property constraints | Property-filtered goals for funnels ("Pro Sign Up") |
| Apr–Sep 2026 | Funnels: strict (Apr), revenue + period comparison (Sep 9), flexible (Sep 23) | Three funnel types: sequential, flexible, strict |
| May 2026 | User Journeys (Explore tab) | Path exploration, Business plan |
| May 15, 2026 | CE v3.2.1: removes /storybook endpoint (CVE-2026-8467, RCE) |
Every CE install from v3.0.0 to v3.2.0 must upgrade |
| Jun 2026 | AI Assistants channel; full-URL page breakdowns | ChatGPT/Claude/Perplexity traffic split out |
| Jul 2026 | Chart annotations | Mark launches/deploys on the traffic graph |
Official Documentation
The docs site has no
.mdendpoints and nollms.txt. Usehttps://plausible.io/docs/sitemap.xmlfor the page list, and the doc sources athttps://github.com/plausible/docs/tree/master/docsfor raw markdown.
Plans and pricing (verified 2026-10-20)
Billing is by monthly pageviews + custom events across all sites in a team. Prices below are the entry tier (10k monthly pageviews); higher tiers cost more. Yearly billing charges 10 months for 12. 30-day free trial with Business features, no card.
| Plan | Monthly | Yearly | Sites | Team | Retention | Key features |
|---|---|---|---|---|---|---|
| Starter | $9 | $90 | 1 | — | 3 years | Dashboard, goals, custom events, script |
| Growth | $14 | $140 | 3 | 3 | not stated | + shared dashboards, team members |
| Business | $19 | $190 | 10 | 10 | 5 years | + Stats API (600 req/h), custom properties, revenue goals, funnels, user journeys, consolidated view |
| Enterprise | custom | custom | 10+ | 10+ | 5+ years | + Sites API, SSO (SAML), managed proxy, raw event exports to S3, higher API limits |
| Community Edition | free (self-host) | — | unlimited | unlimited | yours | Stats API included; no funnels, user journeys, revenue goals, SSO or Sites API; two releases a year |
Traffic spikes are not billed: one month over the tier needs no action. 15% discount on annual Business for nonprofits, education and open-source projects.
Script setup
The snippet (new, per-site)
Every site has its own snippet in Site Settings → General → Site installation. It is two
tags: the async loader and an inline queue stub, so plausible() calls made before the script
loads are queued.
<script async src="https://plausible.io/js/pa-XXXXX.js"></script>
<script>
window.plausible=window.plausible||function(){(plausible.q=plausible.q||[]).push(arguments)},plausible.init=plausible.init||function(i){plausible.o=i||{}};
plausible.init()
</script>
The pa-XXXXX ID encodes the site. Outbound links, file downloads, form submissions, 404
tracking and tagged events are switched on in Site Settings and take effect without editing
the snippet. Code-level options go into plausible.init({...}):
plausible.init() option |
Type | Default | Use |
|---|---|---|---|
endpoint |
string |
https://plausible.io/api/event |
Proxy or self-hosted event endpoint (replaces the old data-api) |
customProperties |
object or (eventName) => object |
{} |
Props on every event (replaces event-* data attributes) |
fileDownloads |
{ fileExtensions: string[] } |
built-in list | Limit download tracking to some extensions |
hashBasedRouting |
boolean |
false |
Hash-routed SPAs |
autoCapturePageviews |
boolean |
true |
false to send pageviews yourself (custom locations) |
captureOnLocalhost |
boolean |
false |
Dev testing |
transformRequest |
function | — | Rewrite or drop a payload before it is sent |
Removed in the new script: data-exclude / data-include (use the
excluding guide) and sending to multiple dashboards at
once (keep the legacy script, or use a consolidated view). Legacy script.*.js URLs still
work, but don't use them for new sites.
Next.js 16 App Router: next-plausible@4.0.0 + proxy (recommended)
next-plausible is a community package that Plausible's own Next.js page recommends. v4
tracks the new script; peers allow next 11 through 16 and React 16.8 through 19.
npm i next-plausible@4.0.0
// next.config.ts
import type { NextConfig } from "next";
import { withPlausibleProxy } from "next-plausible";
const nextConfig: NextConfig = {
reactStrictMode: true,
};
export default withPlausibleProxy({
// Site-specific script from Site Settings. Self-hosted CE: https://stats.example.com/js/pa-XXXXX.js
src: process.env.NEXT_PUBLIC_PLAUSIBLE_SRC ?? "https://plausible.io/js/pa-XXXXX.js",
// Defaults: /js/script.js and /api/event. Avoid "analytics", "stats", "tracking", "plausible".
scriptPath: "/pa/js/script.js",
apiPath: "/pa/api/event",
})(nextConfig); // a config object is mandatory, even if empty
// app/layout.tsx
import type { ReactNode } from "react";
import PlausibleProvider from "next-plausible";
export default function RootLayout({ children }: { children: ReactNode }) {
return (
<html lang="en">
<body>
<PlausibleProvider
enabled={process.env.VERCEL_ENV === "production"}
init={{
customProperties: { app_version: "2026.10" },
fileDownloads: { fileExtensions: ["pdf", "csv"] },
}}
>
{children}
</PlausibleProvider>
</body>
</html>
);
}
PlausibleProviderprops:src(omit when proxied),init,enabled(defaults to production viaNODE_ENV+VERCEL_ENV),integrity,scriptProps. It mounts in<body>.- Skip
integrity(SRI): thepa-XXXXX.jscontent changes whenever site tracking settings change, so a pinned hash would break the script. Serve it first-party instead. initis typed:outboundLinks/formSubmissionsare not accepted there (they are site settings), andfileDownloadstakes{ fileExtensions }, not a boolean. The previous version of this guide passedinit={{ outboundLinks: true }}, which failstsc.- The rewrites need a server:
next startor Vercel.output: "export"static builds can't proxy. - The proxied event route is on your domain, so it receives the visitor's cookies. Strip them
in
proxy.ts(Next.js 16 renamedmiddleware.ts→proxy.tsand the exported functionmiddleware→proxy). Merge into an existingproxy.ts(e.g. Clerk's) rather than adding a second file. Seeexamples/next-app/proxy.ts.
Per-tenant sites (Motionstack /sites/[subdomain]): the proxy is configured once per app with
one src. Either give each tenant its own Plausible site and render
<PlausibleProvider src={tenant.paScriptUrl}> without the proxy, or track all tenants in one
site and split them by hostname (event:hostname / visit:entry_page_hostname in the Stats
API). Trade-offs are in PATTERNS.md.
Other runtimes
| Setup | How |
|---|---|
| Any SPA / bundler | @plausible-analytics/tracker@0.4.6: init({ domain, ... }) + track(name, opts). Browser-only; domain is required. See examples/npm-tracker.ts |
| Vercel without next-plausible | vercel.json rewrites: /<dir>/js/script.js → your pa-XXXXX.js, /<dir>/api/event → https://plausible.io/api/event, then plausible.init({ endpoint: "/<dir>/api/event" }) |
| Cloudflare | Worker route on your zone; see examples/cloudflare-proxy-worker.ts (module syntax; Plausible's guide still shows service-worker syntax) |
| Mobile / server | Events API (POST /api/event) |
| Managed | Plausible-run proxy via CNAME, Enterprise only |
Expect 5–25% of visitors to be missed without a proxy, depending on audience.
Custom events, properties and goals
An event counts as a conversion only once a goal with the same name exists (Site Settings → Goals → Add goal → Custom event). Names are case-sensitive and goals are not backfilled.
"use client";
import { usePlausible } from "next-plausible";
type Events = {
Lead: { provider: string; source: string };
Download: { file: string };
Signup: never;
};
export function LeadForm({ providerSlug }: { providerSlug: string }) {
const plausible = usePlausible<Events>();
async function onSubmit(formData: FormData) {
const res = await fetch("/api/leads", { method: "POST", body: formData });
if (!res.ok) return;
plausible("Lead", { props: { provider: providerSlug, source: "site-form" } });
}
return (
<form action={onSubmit}>
<input name="message" aria-label="Message" />
<button type="submit">Send</button>
</form>
);
}
- No-JS option: CSS classes,
class="plausible-event-name=Sign+Up plausible-event-plan=pro"(+becomes a space). Requires "tagged events" enabled for the site. - Props: up to 30 per event, on custom events and pageviews. Custom properties in the dashboard and API are a Business feature. Never send personal data (names, emails, phone numbers, free text, user IDs) as props or in URLs.
- Property-filtered goals: a goal can require up to three prop values (e.g.
Sign Up+plan=pro→ "Pro Sign Up"). Funnels are built from goals, so this is how a funnel step matches one variant. - Non-interactive events:
plausible("Video Autoplay", { interactive: false })keeps the event out of bounce rate. - Built-in goals (when enabled):
Outbound Link: Click,File Download,Form: Submission,404. Scroll depth (1–100%) is recorded automatically; scroll-depth goals count visitors who pass a threshold on a given path.
Revenue goals (Business)
Create the goal with Enable revenue tracking and a base currency (fixed once set). Send the amount in major units in whatever currency the purchase used; Plausible converts it.
plausible("Purchase", { revenue: { currency: "USD", amount: 49.0 }, props: { plan: "Pro" } });
- Fire on the confirmation page, not the checkout click.
- Stripe amounts are minor units (
4900= $49.00): divide by 100, except Stripe's zero-decimal currencies.examples/server-event.tshasstripeAmountToRevenue(). - Plausible already excludes Stripe, PayPal and Paddle as referrers, so a round-trip through Stripe Checkout keeps the original source.
- Revenue shows in reports, funnels and the Stats API (
total_revenue,average_revenuereturn{ value, currency, short, long }ornullwith ameta.metric_warning). - Not available in CE, and not combined in consolidated views.
Funnels and user journeys (Business)
- Funnels: 2–8 steps built from pageview and custom-event goals (incl. revenue and property-filtered goals). Types: sequential (default; steps in order, other activity allowed), flexible (only first and last steps required), strict (exact consecutive order). Revenue per step and date comparison are supported. Sessions survive a trip to an external payment page.
- User journeys (Explore tab): pick a page/event as start or end point and follow up to 20 steps; good when you don't have a fixed path in mind.
- Funnels are configured in Site Settings only; the Stats API has no funnel endpoint. Use
behavioral filters (
has_done/has_not_done) for "converted after visiting X" queries.
Server-side events (Events API)
POST /api/event with domain, name, url, optional referrer, props, revenue,
interactive. No API key. It always returns 202, even for dropped events: check the
x-plausible-dropped: 1 response header, and use X-Debug-Request: true to see which IP
Plausible will use. The visitor's real User-Agent and X-Forwarded-For are required; a server
or CDN IP gets the event silently dropped by bot filtering.
export interface ServerEvent {
domain: string;
name: string;
url: string;
userAgent: string;
ip: string;
referrer?: string;
props?: Record<string, string | number | boolean>;
revenue?: { currency: string; amount: number | string };
interactive?: boolean;
}
export type SendResult = { recorded: true } | { recorded: false; reason: string };
export async function sendPlausibleEvent(
event: ServerEvent,
host: string = process.env.PLAUSIBLE_HOST ?? "https://plausible.io",
): Promise<SendResult> {
const { userAgent, ip, ...body } = event;
const res = await fetch(`${host}/api/event`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": userAgent,
"X-Forwarded-For": ip,
},
body: JSON.stringify(body),
});
if (!res.ok) return { recorded: false, reason: `HTTP ${res.status}` };
if (res.headers.get("x-plausible-dropped") === "1") {
return { recorded: false, reason: "dropped by bot filtering (check User-Agent / X-Forwarded-For)" };
}
return { recorded: true };
}
A Stripe webhook can't attribute a visitor: it arrives from Stripe's IPs. Record purchases from a request the visitor's browser makes (the success page's route handler, after verifying the Checkout Session), or client-side on that page. Don't store visitor IPs in Stripe metadata to work around this; that creates the personal data Plausible avoids.
Stats API v2 → analytics_daily rollup
Single endpoint POST /api/v2/query, Bearer key. Requirements:
- Business plan on Cloud (CE includes it).
- Key type Stats API, created under the team that owns the sites (keys are team-scoped; Owner/Admin/Editor/Billing roles can create them, Viewers and guests can't).
- 600 requests/hour per key by default (429 above it).
curl https://plausible.io/api/v2/query \
--request POST \
--header "Authorization: Bearer $PLAUSIBLE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
"site_id": "acme.providers.motionstack.app",
"metrics": ["visitors", "pageviews", "bounce_rate"],
"date_range": "7d",
"dimensions": ["time:day"]
}'
Query shape (full typed client in examples/plausible-stats.ts):
| Key | Notes |
|---|---|
site_id |
Domain as added to Plausible (required) |
date_range |
day, 24h, 7d, 28d, 30d, 91d, month, 6mo, 12mo, year, all, or [start, end] ISO dates/date-times. No yesterday |
metrics |
visitors, visits, pageviews, views_per_visit, bounce_rate, visit_duration, events, scroll_depth, percentage, conversion_rate, group_conversion_rate, average_revenue, total_revenue, time_on_page* (*need a matching filter/dimension) |
dimensions |
event:goal, event:page, event:hostname, visit:source, visit:channel, visit:referrer, visit:utm_*, visit:country/region/city (+ _name), visit:device, visit:browser, visit:os, visit:entry_page, visit:exit_page, event:props:<name>, time, time:hour/day/week/month |
filters |
[op, dimension, clauses, modifiers?] with is, is_not, contains, contains_not, matches, matches_not (re2); and / or / not; behavioral has_done / has_not_done; saved segments ["is", "segment", [id]] |
order_by |
[["visitors", "desc"]] |
include |
imports, time_labels, total_rows, trim_relative_date_range |
pagination |
default { limit: 10000, offset: 0 } |
Session metrics (bounce_rate, views_per_visit, visit_duration) can't be mixed with event
dimensions except event:page (and event:hostname alongside it). Time buckets use the site's
reporting timezone.
The daily rollup, triggered by a QStash schedule and verified with verifySignatureAppRouter
(the previous version of this guide had an unauthenticated cron route):
// app/api/cron/plausible-rollup/route.ts (next@16.4.2, @upstash/qstash@2.12.0)
import { verifySignatureAppRouter } from "@upstash/qstash/nextjs";
import { listActiveProviders, upsertAnalyticsDaily } from "@/lib/analytics-store";
import { num, queryStats, toRecords, yesterdayISO, type StatsQuery } from "@/lib/plausible-stats";
export const maxDuration = 300;
const MAX_PROVIDERS_PER_RUN = 250; // 2 queries each, under 600 req/h
async function rollupOne(siteId: string, day: string, apiKey: string, host: string) {
const traffic: StatsQuery = {
site_id: siteId,
metrics: ["visitors", "pageviews", "bounce_rate", "visit_duration"],
date_range: [day, day],
};
const leads: StatsQuery = {
site_id: siteId,
metrics: ["visitors", "events"], // events = total conversions under a goal filter
date_range: [day, day],
filters: [["is", "event:goal", ["Lead"]]],
};
const [t, l] = await Promise.all([
queryStats(traffic, { apiKey, host }),
queryStats(leads, { apiKey, host }),
]);
const tr = toRecords(traffic, t)[0] ?? {};
const lr = toRecords(leads, l)[0] ?? {};
return {
visitors: num(tr.visitors),
pageviews: num(tr.pageviews),
bounceRate: num(tr.bounce_rate),
visitDuration: num(tr.visit_duration),
leads: num(lr.events),
};
}
async function handler(): Promise<Response> {
const apiKey = process.env.PLAUSIBLE_API_KEY;
if (!apiKey) return Response.json({ error: "PLAUSIBLE_API_KEY missing" }, { status: 500 });
const host = process.env.PLAUSIBLE_HOST ?? "https://plausible.io";
const day = yesterdayISO();
const providers = (await listActiveProviders()).slice(0, MAX_PROVIDERS_PER_RUN);
const failed: string[] = [];
for (const p of providers) {
try {
const row = await rollupOne(p.plausibleSiteId, day, apiKey, host);
await upsertAnalyticsDaily({ providerId: p.id, date: day, ...row });
} catch {
failed.push(p.plausibleSiteId); // report to Sentry; don't fail the batch
}
}
return Response.json({ ok: failed.length === 0, day, providers: providers.length, failed });
}
export const POST = verifySignatureAppRouter(handler);
upsertAnalyticsDaily is an INSERT ... ON CONFLICT (provider_id, date) DO UPDATE against Neon
(Drizzle's onConflictDoUpdate works). yesterdayISO() uses UTC; if a site's reporting timezone
is US Eastern, run the cron after 05:00 UTC so "yesterday" is complete there.
Sites API (Enterprise): tenant provisioning
/api/v1/sites creates, updates and deletes sites, configures the tracker script, and manages
goals, custom properties, shared links and guests. Write calls need an Enterprise plan and a
Sites API key; the read endpoints also accept a Stats API key. Not available in CE.
curl -X POST https://plausible.io/api/v1/sites \
-H "Authorization: Bearer $PLAUSIBLE_SITES_API_KEY" \
-H "Content-Type: application/json" \
-d '{ "domain": "acme.providers.motionstack.app", "timezone": "America/New_York",
"tracker_script_configuration": { "outbound_links": true, "form_submissions": true } }'
The response's tracker_script_configuration.id (pa-...) gives the script URL
https://plausible.io/js/{id}.js. PUT /api/v1/sites/goals is idempotent (find-or-create).
Lists are cursor-paginated (after/before/limit). Full typed helpers: examples/sites-api.ts.
Without Enterprise, create tenant sites by hand (or use one site + hostname splitting, see
PATTERNS.md).
Self-hosting (Community Edition)
CE bundles Plausible, PostgreSQL and ClickHouse in Docker Compose. Current release v3.2.1 (2026-05-15). Host needs a CPU with SSE 4.2 or NEON (ClickHouse) and 2 GB+ RAM.
Security: CE v3.0.0 through v3.2.0 expose
/storybook, which allows remote code execution (CVE-2026-8467 / GHSA-55hg-8qxv-qj4p). Upgrade to v3.2.1, or block/storybookat the reverse proxy until you can.
git clone -b v3.2.1 --single-branch \
https://github.com/plausible/community-edition plausible-ce
cd plausible-ce
touch .env
echo "BASE_URL=https://stats.example.com" >> .env
echo "SECRET_KEY_BASE=$(openssl rand -base64 48)" >> .env # 64+ bytes
echo "HTTP_PORT=80" >> .env # 80 + 443 = built-in Let's Encrypt
echo "HTTPS_PORT=443" >> .env
cat > compose.override.yml <<'YML'
services:
plausible:
ports:
- 80:80
- 443:443
YML
docker compose up -d
- Config lives in
.env(not the oldplausible-conf.env);TOTP_VAULT_KEYis no longer required; there's no bundled Caddy. Behind your own reverse proxy, choose other ports. - Upgrading: from v3.2.0 on, check out the new tag (ClickHouse profile files change), keep
local changes in
.env/compose.override.yml, thendocker compose up -d. - CE gets two releases a year and lacks funnels, user journeys, revenue goals, SSO and the
Sites API. Everything else (script, Events API, Stats API v2) matches Cloud: point
srcathttps://stats.example.com/js/pa-XXXXX.jsand setPLAUSIBLE_HOST.
MCP server (agents)
Plausible publishes no official MCP server. Its docs list a community server built by the
Sentry team: getsentry/plausible-mcp (MIT, read-only tools get_timeseries,
get_breakdown, get_conversions, compare_periods). It calls the Stats API, so the key needs
a Business plan (or CE).
# Hosted, bring-your-own-key. Keep the URL before --header (--header is variadic).
claude mcp add --transport http plausible https://plausible-mcp.sentry.dev/mcp \
--header "Authorization: Bearer YOUR_PLAUSIBLE_API_KEY"
The hosted endpoint passes your key through a third party's Worker. For production data, prefer
the local stdio build (git clone, pnpm build, then
claude mcp add plausible -e PLAUSIBLE_API_KEY=... -- node <path>/dist/index.js) or self-host it
on Cloudflare Workers, and use a dedicated read-only Stats API key. The tech-stack MCP's
get_guide plausible serves this guide.
Privacy, GDPR and US state laws
| Regime | Position | What we still do |
|---|---|---|
| GDPR / ePrivacy (EU) | No cookies or device storage, no personal data, EU hosting, automatic DPA → no consent banner needed for Plausible alone | List Plausible in the privacy policy; link the DPA in vendor records |
| CCPA/CPRA and other US state laws (VA, CO, CT, TX, OR, …) | No sale/sharing for cross-context behavioral advertising and no persistent identifiers, so no "Do Not Sell or Share" or GPC handling is triggered by Plausible alone | Disclose analytics in the privacy notice; keep props and URLs free of personal data |
| HIPAA (US health) | Plausible doesn't receive PHI if URLs, titles and props carry no health details; we found no public BAA offer | Healthcare sites: no conditions/treatments in paths or props, or self-host CE; get counsel sign-off |
This is engineering guidance, not legal advice. Adding any other tracker (ads pixels, session replay) brings the banner back. Props and custom URLs are the usual way personal data leaks in.
Environment variables
Secrets (store in the Hazina vault and in Vercel project env; server-only):
PLAUSIBLE_API_KEY=pk_... # Stats API key (Account > API Keys > Stats API)
PLAUSIBLE_SITES_API_KEY=pk_... # Enterprise only: Sites API key for tenant provisioning
QSTASH_CURRENT_SIGNING_KEY=sig_... # verifies the rollup cron
QSTASH_NEXT_SIGNING_KEY=sig_...
Non-secret settings:
| Variable | Example | Notes |
|---|---|---|
PLAUSIBLE_HOST |
https://plausible.io |
CE: your BASE_URL. Used by server-side Events/Stats calls |
NEXT_PUBLIC_PLAUSIBLE_SRC |
https://plausible.io/js/pa-XXXXX.js |
Public; it's the snippet URL |
The pk_... / sig_... values are placeholders; real Plausible keys have no fixed prefix.
Automation workflows
QStash schedule (daily rollup)
# 06:15 UTC daily (after midnight US Eastern). See the `upstash` guide.
curl -X POST "https://qstash.upstash.io/v2/schedules/https://app.motionstack.app/api/cron/plausible-rollup" \
-H "Authorization: Bearer $QSTASH_TOKEN" \
-H "Upstash-Cron: 15 6 * * *"
Claude Code slash command: analytics snapshot
.claude/commands/analytics.md:
Summarize Plausible analytics for site: $ARGUMENTS
1. Read PLAUSIBLE_API_KEY from the environment (never print it).
2. POST /api/v2/query for site "$ARGUMENTS": metrics ["visitors","pageviews","bounce_rate","visit_duration"],
date_range "30d", dimensions ["time:day"].
3. Query metrics ["visitors","events","conversion_rate"] with dimensions ["event:goal"] for goal conversions.
4. Query metrics ["visitors"] with dimensions ["visit:channel"] to see source mix (incl. AI Assistants).
5. Compare with analytics_daily rows in Neon for the same window; flag drift over 2%.
6. Output a short week-over-week summary and any anomalies.
Common use cases
| Use case | Approach |
|---|---|
| Product site analytics | withPlausibleProxy + PlausibleProvider in app/layout.tsx |
| Per-tenant analytics | One site per tenant (src={tenant.paScriptUrl}) or one site split by hostname |
| Lead / signup conversions | Custom-event goal + plausible("Lead", { props }) |
| Purchase revenue | Revenue goal (Business) + revenue: { currency, amount } on the success page |
| Conversion paths | Funnels (sequential / flexible / strict) + user journeys |
| Daily rollup into Postgres | Stats API v2 per site → analytics_daily, signed QStash cron |
| Automated tenant onboarding | Sites API (Enterprise): create site, PUT /goals, store script URL |
| Ad-blocker resistance | First-party proxy (next-plausible, Vercel rewrites, Cloudflare Worker) |
| Data sovereignty / no plan gates on API | Self-hosted CE v3.2.1+ |
| Ask questions from Claude | getsentry/plausible-mcp with a read-only Stats key |
Troubleshooting
| Issue | Fix |
|---|---|
| No data appearing | Site domain in Plausible must match exactly (no scheme, no trailing slash); confirm the right pa-XXXXX.js loads and run the installation check in Site Settings |
plausible is not defined / early calls lost |
Include the inline plausible.init stub, not only the <script async> tag |
| Blocked by ad-blockers | Proxy first-party; avoid analytics/stats/tracking/plausible in the paths |
tsc error on init={{ outboundLinks: true }} |
Toggle outbound links / form submissions in Site Settings; init only takes the options listed above |
| Proxy 404 on a static export | Rewrites need next start or Vercel; static exports can't proxy |
| Custom event not counting | Create the matching goal (exact, case-sensitive; CSS + = space); goals don't backfill |
| Revenue missing or 100x too big | Business plan; amount in major units (Stripe cents ÷ 100); ISO 4217 currency |
Stats API 401 / 403 |
Wrong key type, key from another team, or plan without the Stats API |
Stats API 400 |
Invalid metric/dimension, "yesterday" date range, or a session metric mixed with an event dimension |
Stats API 429 |
Over 600 requests/hour; batch fewer queries or ask for a higher limit |
| Server event "accepted" but missing | Check x-plausible-dropped: 1; send the visitor's UA and IP (X-Debug-Request: true shows the IP) |
| Localhost shows no data | enabled on PlausibleProvider and init={{ captureOnLocalhost: true }} |
| CE script 404 / wrong host | BASE_URL in .env, and src / PLAUSIBLE_HOST pointing at the CE instance |
CE security scan flags /storybook |
Upgrade to v3.2.1 (CVE-2026-8467) |
codeAmani notes
- Where it fits: Plausible is the default product-analytics layer for marketing and product sites (US-first). Error and performance monitoring stay in Sentry; deeper product analytics (feature flags, replay) belong in PostHog only when a project needs them, and those bring a consent banner back.
- Secrets: the Stats and Sites API keys are server-only and live in the Hazina vault and
Vercel env. Never put them in
NEXT_PUBLIC_*, client components, or the MCP config in a repo. Use a dedicated read-only Stats key per integration so one can be revoked alone. - Payments: Stripe is the default rail; send revenue to Plausible from the verified success
page, in major units. For Kenya-targeted projects, M-Pesa amounts are already integer KES:
record the
Purchasegoal withcurrency: "KES"only after the STK callback has been validated and deduplicated onCheckoutRequestID, triggered from the visitor's own session (the callback comes from Safaricom's servers, so it can't attribute a visitor). - AI routing: the analytics summary command runs on Claude; the Stats API does the counting. Don't send raw rows with personal data to any model (there shouldn't be any).
- Kenya / East Africa: the script is about 1 KB and loads
async, so it is fine on 2G/3G. Proxying through the app's own domain also avoids an extra DNS lookup on slow networks.visit:country=KEand thevisit:regioncodes give county-level splits. - Plan choice: Business ($19/mo entry) is the minimum for any project that needs the rollup, revenue or funnels. Above 10 sites (e.g. Motionstack tenants) either use Enterprise, one site split by hostname, or CE.
Official docs:
- https://plausible.io/docs
- https://plausible.io/docs/plausible-script
- https://plausible.io/docs/script-update-guide
- https://plausible.io/docs/stats-api
- https://plausible.io/docs/sites-api
- https://plausible.io/docs/events-api
- https://plausible.io/docs/custom-event-goals
- https://plausible.io/docs/ecommerce-revenue-tracking
- https://plausible.io/docs/funnel-analysis
- https://plausible.io/docs/proxy/introduction
- https://github.com/plausible/community-edition