minilytics README

项目的 README,来自 github.com/surendrapandar/minilytics。合并为一个 markdown 文件:README.md。

Minilytics

Revenue-first web analytics for your own websites, inspired by DataFast. It shows where visitors came from (which tweet, article, Google page or AI assistant), what they did, and which source made you money. It runs on Cloudflare's free plan.

Dashboard

Sponsors

SnitchFeed
SnitchFeed
Agentic social listening for GTM: X, LinkedIn, Reddit & more
Open Source Alternatives
Open Source Alternatives
Find Best Open Source Alternatives to Paid Software
Awesome Black Friday Deals
Awesome Black Friday Deals
Black Friday & Cyber Monday deals for devs & indie makers
DiskMate
DiskMate
Disk space analyzer & cleaner for Mac
PasteBuddy
PasteBuddy
Clipboard history for Mac: never lose what you copy
Your logo here
Reach indie hackers and developers who self-host their analytics

Become a sponsor →

Become a sponsor: $19/month early price

What it tracks

Deploy for free (about 10 minutes)

Every person deploys their own copy on their own free Cloudflare account. Your data stays on your account, and you get your own dashboard with its own password.

You need a free Cloudflare account, Node.js 20+ and Git. Run these commands in a terminal on your computer. You only do this once; afterwards the app runs on Cloudflare.

1. Download the code and log in to Cloudflare

git clone https://github.com/surendrapandar/minilytics.git
cd minilytics
npm install
npx wrangler login          # opens your browser; click "Allow"

2. Create the database

npx wrangler d1 create minilytics

If Wrangler asks "Would you like Wrangler to add it on your behalf?", answer No. Answer No to the optional "Cloudflare skills" questions too. Then copy the printed database_id and paste it into wrangler.jsonc, replacing 00000000-0000-0000-0000-000000000000. There must be exactly one entry under d1_databases, with "binding": "DB".

3. Set your password and a signing secret

npx wrangler secret put ADMIN_PASSWORD     # the password you'll log in with (use a strong one)
npx wrangler secret put SESSION_SECRET     # any long random text, e.g. the output of: openssl rand -hex 32

Typing is hidden; that's normal. If asked "There doesn't seem to be a Worker called minilytics… create it?", answer Yes.

4. Deploy

npm run deploy

This builds the dashboard, creates the database tables and deploys. It prints your link, e.g. https://minilytics.<you>.workers.dev. Open it, log in, add a website and copy its script tag. Each site's Settings page also has a Copy AI prompt button that lets Claude Code / Cursor do the install in your codebase for you.

If you see fetch failed, it's a network hiccup (VPN, proxy, Wi-Fi). Run npm run deploy again.

You can attach a custom domain such as analytics.yourdomain.com in Cloudflare → Workers & Pages → minilytics → Settings → Domains & Routes.

Updating later

git stash          # keeps your database_id edit in wrangler.jsonc safe
git pull
git stash pop
npm run deploy

What the free plan covers

Cloudflare free limit What it means here
100,000 Worker requests/day About 100k tracked events per day across all sites. The script and dashboard files are static and don't count.
100,000 D1 rows written/day About 10k pageviews per day
5M D1 rows read/day A dashboard load reads roughly 10 times the sessions in the range, so with 10k visitors/month that's hundreds of loads a day
5 GB D1 storage Years of data at side-project traffic

At 5–10k visitors a month you'll use a few percent of this. If you outgrow it, Cloudflare's Workers Paid plan is $5/month.

Run it as a hosted SaaS (optional)

By default Minilytics is single-user with a password. Set the Google values below and it becomes a hosted product: a landing page with pricing, Sign in with Google, a paid plan through Dodo Payments, and every customer sees only their own sites. Tracking stops (quietly) for sites whose owner's plan has ended.

npx wrangler secret put GOOGLE_CLIENT_ID        # Google Cloud → Credentials → OAuth client (Web)
npx wrangler secret put GOOGLE_CLIENT_SECRET    # redirect URI: https://YOUR-DOMAIN/api/auth/google/callback
npx wrangler secret put ADMIN_EMAILS            # your Google email(s): free, and you keep the existing sites
npx wrangler secret put PLAN_CHECKOUT_URL       # Dodo payment link for the plan
npx wrangler secret put PLAN_PRODUCT_ID         # that product's id (pdt_...)
npx wrangler secret put BILLING_WEBHOOK_SECRET  # Dodo webhook → https://YOUR-DOMAIN/api/billing/webhook
npx wrangler secret put PLAN_PRICE              # e.g. $29
npx wrangler secret put PLAN_INTERVAL           # lifetime | month | year
npx wrangler secret put PLAN_SPOTS              # e.g. 5 ("3 of 5 spots left"); optional
npx wrangler secret put PLAN_NEXT_PRICE         # e.g. $49 ("…, then $49"); optional
npx wrangler secret put PLAN_TIERS              # optional: "$29:5, $49:pdt_b:5, $100" steps the price up as spots sell
                                                # (one Dodo product per price; no pdt_ = sold out or only announced).
                                                # Replaces PRICE/SPOTS/NEXT_PRICE; sold-out prices show as "5 sold at $29"
npx wrangler secret put SUPPORT_EMAIL           # shown on pricing, billing and legal pages
npm run deploy

Subscribe the billing webhook to payment.succeeded, subscription.* and refund.succeeded. A one-time product (PLAN_INTERVAL=lifetime) gives lifetime access; a subscription gives access until it expires or is refunded. The Terms, Privacy and Refund pages (/terms, /privacy, /refund) are plain-language starting points: review them.

Install on a website

<script defer data-website-id="SITE_ID" src="https://YOUR-MINILYTICS-HOST/js/script.js"></script>

Tracking a specific tweet / article

X, Medium, LinkedIn and others hide which exact post sent someone; the referrer only says t.co or medium.com. To see the exact post, tag each link. Settings has a link builder for this:

https://yoursite.com/?utm_source=x&utm_medium=social&utm_campaign=launch-tweet
https://yoursite.com/?ref=launch-tweet            (short version)

For SEO, Google never shares the search keyword, but Entry page with the Google referrer tells you which article people found you through.

Revenue attribution

Pick your provider in site settings → Connect payments.

Dodo Payments

  1. In Dodo → Developer → Webhooks, add https://YOUR-HOST/api/webhooks/dodo/SITE_ID and subscribe to payment.succeeded and refund.succeeded. Paste the signing secret (whsec_…) into the site settings.
  2. Pass the visitor cookies as metadata when creating a checkout:
const jar = await cookies(); // next/headers
await dodo.checkoutSessions.create({
  product_cart: [{ product_id: 'pdt_xxx', quantity: 1 }],
  metadata: { ml_visitor_id: jar.get('ml_vid')?.value ?? '', ml_session_id: jar.get('ml_sid')?.value ?? '' },
});

Using Dodo payment links? The script adds metadata_ml_visitor_id / metadata_ml_session_id to any checkout.dodopayments.com link when it's clicked. That metadata doesn't always reach the payment, so also do step 3.

  1. Recommended: set the checkout's return / redirect URL to a page on your site (e.g. /thanks) that loads the script. Dodo adds ?payment_id=… to it, and Minilytics uses that to link the payment to the exact visitor even when metadata doesn't come through.

Stripe

  1. In Stripe → Developers → Webhooks, add https://YOUR-HOST/api/webhooks/stripe/SITE_ID and subscribe to checkout.session.completed, invoice.paid and charge.refunded. Paste the signing secret (whsec_…) into the site settings.
  2. Pass the visitor cookies as metadata when creating a Checkout Session, and add {CHECKOUT_SESSION_ID} to the success URL:
const jar = await cookies(); // next/headers
await stripe.checkout.sessions.create({
  // ...your existing options
  success_url: 'https://yoursite.com/thanks?session_id={CHECKOUT_SESSION_ID}',
  metadata: { ml_visitor_id: jar.get('ml_vid')?.value ?? '', ml_session_id: jar.get('ml_sid')?.value ?? '' },
});

Using Stripe Payment Links (buy.stripe.com)? The script puts the visitor in client_reference_id when the link is clicked (unless you already set your own). Set the link's confirmation page to redirect to https://yoursite.com/thanks?session_id={CHECKOUT_SESSION_ID} so the payment is also matched on the return page.

Subscription renewals (invoice.paid) are credited to the visitor who first subscribed. Refunds are subtracted.

One Stripe account selling for several of your sites? Point each site's webhook at Stripe as usual: a payment is skipped by sites it clearly isn't for (the buyer was only seen on another site, or a renewal from a customer who only paid on another site). To make it explicit, add ml_site_id: '<SITE_ID>' to the checkout's metadata.

How credit is given

A payment goes to the paying visitor's last visit that came from a real source (last non-direct touch). So "clicked a tweet, came back directly 17 days later and paid" is credited to the tweet. If metadata is missing, Minilytics tries, in order: the return page (?payment_id= / ?session_id=), an earlier payment by the same customer (renewals), an email you identify()'d, and finally checkout timing (used only when exactly one visitor clicked a Dodo or Stripe checkout link in the 3 hours before the payment). The Journey tab shows how each payment was matched, and Try matching again re-runs this for older payments. Refunds are subtracted from revenue.

Other providers (API)

Any other provider can use the generic API (the key is in site settings):

curl -X POST https://YOUR-HOST/api/v1/payments -H "Authorization: Bearer ml_..." -H "Content-Type: application/json" \
  -d '{"transaction_id":"txn_1","amount":29.99,"currency":"USD","visitor_id":"<ml_vid cookie>","email":"[email protected]"}'

Accuracy notes

No analytics tool is 100% accurate. These are the main gaps and how this project handles them:

Local development

cp .dev.vars.example .dev.vars        # password: change-me
npm run db:migrate:local
npm run build && npm run dev:api      # http://localhost:8787
npm run dev:web                       # optional: hot-reloading dashboard on http://localhost:5173

npm run seed                          # optional: 30 days of demo data ("ShipKit" site)
npm test                              # unit tests
npm run smoke                         # end-to-end test against the running dev server
node scripts/smoke-hosted.mjs         # hosted-mode test (see the comment at the top for how to start it)

How it's built

Contributing

Issues and pull requests are welcome. Before opening a PR, run npm run typecheck && npm test.

License

MIT: free to use, modify and self-host, including commercially.

minilytics (surendrapandar/minilytics)

正在搜索数据库…

这是什么?Minilytics 是一款自托管的、以收入为核心的网站分析工具,面向独立开发者和个人创业者。它能显示访客从哪里来、在你的网站上做了什么,以及哪个流量来源真正带来了收入。
我该怎么部署?克隆仓库,登录 Cloudflare,创建 D1 数据库,设置密码和签名密钥,然后运行 npm run deploy。整个过程大约需要 10 分钟,结束时会输出你的在线仪表板链接。
部署前我需要准备什么?一个免费的 Cloudflare 账户、Node.js 20+,以及你电脑上的 Git。部署之后,其他所有东西(数据库、托管)都运行在 Cloudflare 上。
统计数据总是准确无误吗?没有哪款分析工具是完美的:广告拦截器可能会屏蔽统计脚本(可通过你自己的域名转发该脚本来解决);Safari 会在 7 天后丢弃由 JS 设置的 Cookie,因此回访的访客可能被误算为新访客;机器人仅通过 user-agent 和 navigator.webdriver 标志进行过滤。
我的访客和收入数据存在哪里?所有数据都运行在你自己的 Cloudflare 账户和 D1 数据库中。每位部署者都有一个私人仪表板,由其自己的密码保护,因此数据永远不会离开你的账户。
Minilytics 如何将付款归因到正确的访客?它与 Dodo Payments 的 Webhook 集成,并将收入计入访客最后一个非直接触点(例如其点击的推文)。当元数据缺失时,则回退到返回页面的 paymentid、续费匹配、已识别的邮箱或结账时间。
什么是实时地球仪功能?按下 M 键后,可在 3D 地球仪或 2D 地图上实时显示所有当前访客,并附带页面浏览、目标和付款的实时动态。还可以选择开启声音,并切换浅色或深色地图主题。
我能把它变成面向我自己客户的付费 SaaS 吗?可以。设置 Google 登录和 Dodo Payments 相关的值后,Minilytics 就会从单用户模式切换为多租户托管产品,拥有自己的落地页、定价,以及每位客户各自的网站。
它是用什么构建的?运行在 Cloudflare Workers 上的 Hono 应用负责事件接收、Dodo Webhook 以及对 D1(SQLite)的统计查询;由 Vite、Tailwind 和 Recharts 构建的 React 仪表板,则以静态文件的形式由同一个 Worker 提供服务。
大小
2.3 MB
星标
838
更新
提交Nov 03
时长
26天
提交 · 90 天