Skip to content

🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.

Enhance event tracking capabilities and update documentation (#374)

Bill Yang95673b09377f
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 000000000..cf63cde70
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,21 @@
+# CLAUDE.md
+
+This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
+
+## Commands
+- Client: `cd client && npm run dev` (NextJS with Turbopack on port 3002)
+- Server: `cd server && npm run dev` (TypeScript backend)
+- Lint: `cd client && npm run lint` or `cd server && npm run build`
+- TypeCheck: `cd client && tsc --noEmit` or `cd server && tsc`
+- Database: `cd server && npm run db:push` (update DB schema)
+
+## Code Conventions
+- TypeScript with strict typing throughout both client and server
+- Client: React functional components with minimal useEffect and inline functions
+- Frontend: Next.js, Tailwind CSS, Shadcn UI, Tanstack Query, Zustand, Luxon, Nivo
+- Backend: Fastify, Drizzle ORM (Postgres), ClickHouse
+- Error handling: Use try/catch blocks with specific error types
+- Naming: camelCase for variables/functions, PascalCase for components/types
+- Imports: Group by external, then internal (alphabetical within groups)
+- File organization: Related functionality in same directory
+- Dark mode is default theme
\ No newline at end of file
diff --git a/docs/src/app/page.jsx b/docs/src/app/page.jsx
index e62a92df8..7d923b755 100644
--- a/docs/src/app/page.jsx
+++ b/docs/src/app/page.jsx
@@ -50,12 +50,20 @@ export default function IndexPage() {
</h2>
<div className="flex flex-col sm:flex-row my-8 md:my-10 items-center justify-center gap-4 md:gap-6 text-base md:text-lg px-4">
- <Link href="https://app.rybbit.io/signup" className="w-full sm:w-auto">
+ <Link
+ href="https://app.rybbit.io/signup"
+ className="w-full sm:w-auto"
+ data-rybbit-event="signup"
+ >
<button className="w-full sm:w-auto bg-emerald-600 hover:bg-emerald-500 text-white font-medium px-5 py-3 rounded-lg shadow-lg shadow-emerald-900/20 transform hover:-translate-y-0.5 transition-all duration-200 focus:outline-none focus:ring-2 focus:ring-emerald-500 focus:ring-opacity-50 cursor-pointer">
Track your Site
</button>
</Link>
- <Link href="https://demo.rybbit.io/1" className="w-full sm:w-auto">
+ <Link
+ href="https://demo.rybbit.io/1"
+ className="w-full sm:w-auto"
+ data-rybbit-event="demo"
+ >
<button className="w-full sm:w-auto bg-neutral-800 hover:bg-neutral-700 text-white font-medium px-5 py-3 rounded-lg border border-neutral-600 transform hover:-translate-y-0.5 transition-all duration-200 hover:border-neutral-400 focus:outline-none focus:ring-2 focus:ring-neutral-400 focus:ring-opacity-50 cursor-pointer">
View Live Demo
</button>
diff --git a/docs/src/content/sdks/web.mdx b/docs/src/content/sdks/web.mdx
index a04eb06ae..e07125a42 100644
--- a/docs/src/content/sdks/web.mdx
+++ b/docs/src/content/sdks/web.mdx
@@ -1,4 +1,6 @@
import { Callout } from "nextra/components"
+import Link from "next/link"
+
# JavaScript (Web)
@@ -37,6 +39,10 @@ rybbit.init({
### Configuration Options
+<Callout type="default">
+The SDK is currently does not have all features of the tracking script. Currently web vitals and tracking events data attributes are not supported.
+</Callout>
+
| Option (`init`) | Type | Default | Description |
| :------------------- | :----------------- | :------ | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `analyticsHost` | `string` | - | **Required.** URL of your Rybbit analytics instance (e.g., `https://rybbit.yourdomain.com/api`). |
diff --git a/docs/src/content/track-events.mdx b/docs/src/content/track-events.mdx
index 0a7fb5609..16ce78a89 100644
--- a/docs/src/content/track-events.mdx
+++ b/docs/src/content/track-events.mdx
@@ -1,6 +1,26 @@
# Track Custom Events
-The script exposes a global object `window.rybbit` with functions for manual tracking of events.
+The script exposes a global object `window.rybbit` with functions for manual tracking of events, as well as the ability to track events using data attributes on HTML elements.
+
+## Using Data Attributes
+
+You can track custom events by adding data attributes to any HTML element:
+
+```html
+<!-- Basic event tracking -->
+<button data-rybbit-event="signup_clicked">Sign Up</button>
+
+<!-- Event with custom properties -->
+<button
+ data-rybbit-event="purchase_click"
+ data-rybbit-prop-product="premium"
+ data-rybbit-prop-price="49.99"
+>
+ Buy Now
+</button>
+```
+
+This approach requires no JavaScript and works on any clickable element.
## Available Functions
@@ -152,6 +172,14 @@ interface Rybbit {
* @returns The current user ID or null if not set
*/
getUserId: () => string | null;
+
+ /**
+ * Manually tracks outbound link clicks
+ * @param url The URL of the outbound link
+ * @param text Optional text content of the link
+ * @param target Optional target attribute of the link
+ */
+ trackOutbound: (url: string, text?: string, target?: string) => void;
}
declare global {
diff --git a/server/package.json b/server/package.json
index 7ccd99c79..64cb25210 100644
--- a/server/package.json
+++ b/server/package.json
@@ -6,7 +6,7 @@
"type": "module",
"scripts": {
"pack-script": "sh -c 'if [ public/script-full.js -nt public/script.js ]; then terser --compress --mangle < public/script-full.js | tr -d \"\\n\" > public/script.js; else echo \"script.js up to date\"; fi'",
- "dev": "tsc && npm run pack-script && node dist/index.js",
+ "dev": "tsc && node dist/index.js",
"build": "tsc && npm run pack-script",
"start": "node dist/index.js",
"db:generate": "drizzle-kit generate --config=drizzle.config.ts",
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 12f81d687..9e7af2a24 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -346,9 +346,31 @@
? debounce(trackPageview, debounceDuration)
: trackPageview;
- // Track outbound link clicks
- if (trackOutbound) {
- document.addEventListener("click", function (e) {
+ // Track outbound link clicks and custom data-attribute events
+ document.addEventListener("click", function (e) {
+ // First check for custom events via data attributes
+ let target = e.target;
+ while (target && target !== document) {
+ if (target.hasAttribute("data-rybbit-event")) {
+ const eventName = target.getAttribute("data-rybbit-event");
+ if (eventName) {
+ // Collect additional properties from data-rybbit-prop-* attributes
+ const properties = {};
+ for (const attr of target.attributes) {
+ if (attr.name.startsWith("data-rybbit-prop-")) {
+ const propName = attr.name.replace("data-rybbit-prop-", "");
+ properties[propName] = attr.value;
+ }
+ }
+ track("custom_event", eventName, properties);
+ }
+ break;
+ }
+ target = target.parentElement;
+ }
+
+ // Then check for outbound links
+ if (trackOutbound) {
const link = e.target.closest("a");
if (!link || !link.href) return;
@@ -359,8 +381,8 @@
target: link.target || "_self",
});
}
- });
- }
+ }
+ });
if (autoTrackSpa) {
const originalPushState = history.pushState;
diff --git a/server/public/script.js b/server/public/script.js
index b143b0f25..230b9b935 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-!function(){const t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(new Promise(((t,e)=>{const r=document.createElement("script");r.src="https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js",r.onload=()=>t(),r.onerror=()=>e(new Error("Failed to load web-vitals library")),document.head.appendChild(r)})).then((()=>{_()})).catch((t=>{console.warn("Failed to load web vitals library:",t)})),!window.__RYBBIT_OPTOUT__&&null!==localStorage.getItem("disable-rybbit"))return void(window.rybbit={pageview:()=>{},event:()=>{},trackOutbound:()=>{},identify:()=>{},clearUserId:()=>{},getUserId:()=>null});if(!e)return void console.error("Please provide a valid analytics host");const r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r)))return void console.error("Please provide a valid site ID using the data-site-id attribute");const n=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,a="false"!==t.getAttribute("data-auto-track-pageview"),i="false"!==t.getAttribute("data-track-spa"),o="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound");let l=[];try{const e=t.getAttribute("data-skip-patterns");e&&(l=JSON.parse(e),Array.isArray(l)||(l=[]))}catch(t){console.error("Error parsing data-skip-patterns:",t)}let c=[];try{const e=t.getAttribute("data-mask-patterns");e&&(c=JSON.parse(e),Array.isArray(c)||(c=[]))}catch(t){console.error("Error parsing data-mask-patterns:",t)}let u=null;try{const t=localStorage.getItem("rybbit-user-id");t&&(u=t)}catch(t){}function d(t){const e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__";let n=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&");n=n.replace(/\//g,"\\/");let a=n.replace(new RegExp(e,"g"),".*").replace(new RegExp(r,"g"),"[^/]+");return new RegExp("^"+a+"$")}function p(t,e){for(const r of e)try{if(d(r).test(t))return r}catch(t){console.error(`Invalid pattern: ${r}`,t)}return null}const g=()=>{const t=new URL(window.location.href);let e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),p(e,l))return null;const n=p(e,c);n&&(e=n);const a={site_id:r,hostname:t.hostname,pathname:e,querystring:o?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return u&&(a.user_id=u),a},b=t=>{fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0}).catch(console.error)},f=(t="pageview",e="",r={})=>{if("custom_event"===t&&(!e||"string"!=typeof e))return void console.error("Event name is required and must be a string for custom events");const n=g();if(!n)return;const a={...n,type:t,event_name:e,properties:"custom_event"===t||"outbound"===t?JSON.stringify(r):void 0};b(a)};let h={lcp:null,cls:null,inp:null,fcp:null,ttfb:null},w=!1,m=null;const y=()=>{if(w)return;w=!0,m&&(clearTimeout(m),m=null);const t=g();if(!t)return;const e={...t,type:"performance",event_name:"web-vitals",lcp:h.lcp,cls:h.cls,inp:h.inp,fcp:h.fcp,ttfb:h.ttfb};b(e)},v=t=>{w||(h[t.name.toLowerCase()]=t.value,(()=>{if(w)return;Object.values(h).every((t=>null!==t))&&y()})())},_=()=>{if("undefined"!=typeof webVitals)try{webVitals.getLCP(v),webVitals.getCLS(v),webVitals.getINP(v),webVitals.getFCP(v),webVitals.getTTFB(v),m=setTimeout((()=>{w||y()}),2e4),window.addEventListener("beforeunload",(()=>{w||y()}))}catch(t){console.warn("Error initializing web vitals tracking:",t)}},S=()=>f("pageview"),E=n>0?function(t,e){let r;return(...n)=>{clearTimeout(r),r=setTimeout((()=>t.apply(this,n)),e)}}(S,n):S;if(s&&document.addEventListener("click",(function(t){const e=t.target.closest("a");e&&e.href&&function(t){try{const e=window.location.hostname,r=new URL(t).hostname;return r!==e&&""!==r}catch(t){return!1}}(e.href)&&f("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})})),i){const t=history.pushState,e=history.replaceState;history.pushState=function(...e){t.apply(this,e),E()},history.replaceState=function(...t){e.apply(this,t),E()},window.addEventListener("popstate",E),window.addEventListener("hashchange",E)}window.rybbit={pageview:S,event:(t,e={})=>f("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>f("outbound","",{url:t,text:e,target:r}),identify:t=>{if("string"==typeof t&&""!==t.trim()){u=t.trim();try{localStorage.setItem("rybbit-user-id",u)}catch(t){console.warn("Could not persist user ID to localStorage")}}else console.error("User ID must be a non-empty string")},clearUserId:()=>{u=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>u},a&&S()}();
\ No newline at end of file
+!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(new Promise((t,e)=>{let r=document.createElement("script");r.src="https://unpkg.com/web-vitals@3/dist/web-vitals.iife.js",r.onload=()=>t(),r.onerror=()=>e(Error("Failed to load web-vitals library")),document.head.appendChild(r)}).then(()=>{L()}).catch(t=>{console.warn("Failed to load web vitals library:",t)}),!window.__RYBBIT_OPTOUT__&&null!==localStorage.getItem("disable-rybbit")){window.rybbit={pageview(){},event(){},trackOutbound(){},identify(){},clearUserId(){},getUserId:()=>null};return}if(!e){console.error("Please provide a valid analytics host");return}let r=t.getAttribute("data-site-id")||t.getAttribute("site-id");if(!r||isNaN(Number(r))){console.error("Please provide a valid site ID using the data-site-id attribute");return}let a=t.getAttribute("data-debounce")?Math.max(0,parseInt(t.getAttribute("data-debounce"))):500,i="false"!==t.getAttribute("data-auto-track-pageview"),n="false"!==t.getAttribute("data-track-spa"),l="false"!==t.getAttribute("data-track-query"),s="false"!==t.getAttribute("data-track-outbound"),u=[];try{let o=t.getAttribute("data-skip-patterns");o&&(u=JSON.parse(o),Array.isArray(u)||(u=[]))}catch(c){console.error("Error parsing data-skip-patterns:",c)}let p=[];try{let d=t.getAttribute("data-mask-patterns");d&&(p=JSON.parse(d),Array.isArray(p)||(p=[]))}catch(b){console.error("Error parsing data-mask-patterns:",b)}let f=null;try{let g=localStorage.getItem("rybbit-user-id");g&&(f=g)}catch(h){}function y(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),i=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+i+"$")}function v(t,e){for(let r of e)try{let a=y(r);if(a.test(t))return r}catch(i){console.error(`Invalid pattern: ${r}`,i)}return null}let m=()=>{let t=new URL(window.location.href),e=t.pathname;if(t.hash&&t.hash.startsWith("#/")&&(e=t.hash.substring(1)),v(e,u))return null;let a=v(e,p);a&&(e=a);let i={site_id:r,hostname:t.hostname,pathname:e,querystring:l?t.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer};return f&&(i.user_id=f),i},w=t=>{fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(t),mode:"cors",keepalive:!0}).catch(console.error)},A=(t="pageview",e="",r={})=>{if("custom_event"===t&&(!e||"string"!=typeof e)){console.error("Event name is required and must be a string for custom events");return}let a=m();if(!a)return;let i={...a,type:t,event_name:e,properties:"custom_event"===t||"outbound"===t?JSON.stringify(r):void 0};w(i)},I={lcp:null,cls:null,inp:null,fcp:null,ttfb:null},k=!1,E=null,S=()=>{if(k)return;let t=Object.values(I).every(t=>null!==t);t&&T()},T=()=>{if(k)return;k=!0,E&&(clearTimeout(E),E=null);let t=m();if(!t)return;let e={...t,type:"performance",event_name:"web-vitals",lcp:I.lcp,cls:I.cls,inp:I.inp,fcp:I.fcp,ttfb:I.ttfb};w(e)},$=t=>{k||(I[t.name.toLowerCase()]=t.value,S())},L=()=>{if("undefined"!=typeof webVitals)try{webVitals.getLCP($),webVitals.getCLS($),webVitals.getINP($),webVitals.getFCP($),webVitals.getTTFB($),E=setTimeout(()=>{k||T()},2e4),window.addEventListener("beforeunload",()=>{k||T()})}catch(t){console.warn("Error initializing web vitals tracking:",t)}},C=()=>A("pageview"),O=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(C,a):C;if(document.addEventListener("click",function(t){let e=t.target;for(;e&&e!==document;){if(e.hasAttribute("data-rybbit-event")){let r=e.getAttribute("data-rybbit-event");if(r){let a={};for(let i of e.attributes)if(i.name.startsWith("data-rybbit-prop-")){let n=i.name.replace("data-rybbit-prop-","");a[n]=i.value}A("custom_event",r,a)}break}e=e.parentElement}if(s){let l=t.target.closest("a");if(!l||!l.href)return;(function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(i){return!1}})(l.href)&&A("outbound","",{url:l.href,text:l.innerText||l.textContent||"",target:l.target||"_self"})}}),n){let P=history.pushState,U=history.replaceState;history.pushState=function(...t){P.apply(this,t),O()},history.replaceState=function(...t){U.apply(this,t),O()},window.addEventListener("popstate",O),window.addEventListener("hashchange",O)}window.rybbit={pageview:C,event:(t,e={})=>A("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>A("outbound","",{url:t,text:e,target:r}),identify(t){if("string"!=typeof t||""===t.trim()){console.error("User ID must be a non-empty string");return}f=t.trim();try{localStorage.setItem("rybbit-user-id",f)}catch(e){console.warn("Could not persist user ID to localStorage")}},clearUserId(){f=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>f},i&&C()}();
\ No newline at end of file