Skip to content

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

feat(tracking): add user identification methods and enhance event tra… (#310)

Bill Yang34009fa40976
diff --git a/docs/src/content/track-events.mdx b/docs/src/content/track-events.mdx
index 1b6285582..0a7fb5609 100644
--- a/docs/src/content/track-events.mdx
+++ b/docs/src/content/track-events.mdx
@@ -32,6 +32,42 @@ Tracks a pageview. Useful when `data-track-spa` is set to `"false"` or when you
window.rybbit.pageview();
```
+### `window.rybbit.identify(userId)`
+
+Sets a custom user ID for tracking logged-in users across devices and sessions.
+
+* `userId` (String): The unique identifier for the user. This will be stored in localStorage and persist across browser sessions. **Note: Custom user IDs are stored exactly as provided without any hashing or modification.**
+
+```javascript
+// Identify a user when they log in
+window.rybbit.identify("user_12345");
+
+// All subsequent events and pageviews will be associated with this user ID
+```
+
+### `window.rybbit.clearUserId()`
+
+Clears the stored user ID. Useful when a user logs out.
+
+```javascript
+// Clear user identification when user logs out
+window.rybbit.clearUserId();
+```
+
+### `window.rybbit.getUserId()`
+
+Returns the currently set user ID, or `null` if none is set.
+
+```javascript
+// Check if a user is identified
+const currentUserId = window.rybbit.getUserId();
+if (currentUserId) {
+ console.log('Current user:', currentUserId);
+} else {
+ console.log('No user identified');
+}
+```
+
{/* ### `window.rybbit.trackOutbound(url, text, target)`
Manually tracks outbound link clicks. Useful for programmatic navigation or custom link handling.
@@ -45,6 +81,43 @@ Manually tracks outbound link clicks. Useful for programmatic navigation or cust
window.rybbit.trackOutbound("https://example.com", "Example Site", "_blank");
``` */}
+## User Identification Example
+
+Here's a typical workflow for user identification:
+
+```javascript
+// When user logs in
+function handleLogin(userData) {
+ // Set user identification
+ window.rybbit.identify(userData.id);
+
+ // Track login event
+ window.rybbit.event("User Login", {
+ method: "email",
+ plan: userData.plan
+ });
+}
+
+// When user logs out
+function handleLogout() {
+ // Track logout event
+ window.rybbit.event("User Logout");
+
+ // Clear user identification
+ window.rybbit.clearUserId();
+}
+
+// Check identification status
+function checkUserStatus() {
+ const userId = window.rybbit.getUserId();
+ if (userId) {
+ console.log("User is identified:", userId);
+ } else {
+ console.log("Anonymous user");
+ }
+}
+```
+
## TypeScript Support
Put this as `rybbit.d.ts` anywhere in your project to avoid having to do `(window as any).rybbit.event()` everywhere.
@@ -62,6 +135,23 @@ interface Rybbit {
* @param properties Optional properties for the event
*/
event: (name: string, properties?: Record<string, any>) => void;
+
+ /**
+ * Sets a custom user ID for tracking logged-in users
+ * @param userId The user ID to set (will be stored in localStorage)
+ */
+ identify: (userId: string) => void;
+
+ /**
+ * Clears the stored user ID
+ */
+ clearUserId: () => void;
+
+ /**
+ * Gets the currently set user ID
+ * @returns The current user ID or null if not set
+ */
+ getUserId: () => string | null;
}
declare global {
diff --git a/server/public/script-full.js b/server/public/script-full.js
index 58437b657..4d914e841 100644
--- a/server/public/script-full.js
+++ b/server/public/script-full.js
@@ -10,6 +10,9 @@
pageview: () => {},
event: () => {},
trackOutbound: () => {},
+ identify: () => {},
+ clearUserId: () => {},
+ getUserId: () => null,
};
return;
}
@@ -63,6 +66,19 @@
console.error("Error parsing data-mask-patterns:", e);
}
+ // Add user ID management
+ let customUserId = null;
+
+ // Load stored user ID from localStorage on script initialization
+ try {
+ const storedUserId = localStorage.getItem("rybbit-user-id");
+ if (storedUserId) {
+ customUserId = storedUserId;
+ }
+ } catch (e) {
+ // localStorage not available, ignore
+ }
+
// Helper function to convert wildcard pattern to regex
function patternToRegex(pattern) {
// Use a safer approach by replacing wildcards with unique tokens first
@@ -166,6 +182,8 @@
eventType === "custom_event" || eventType === "outbound"
? JSON.stringify(properties)
: undefined,
+ // Add custom user ID if available
+ user_id: customUserId,
};
fetch(`${ANALYTICS_HOST}/track`, {
@@ -226,6 +244,32 @@
event: (name, properties = {}) => track("custom_event", name, properties),
trackOutbound: (url, text = "", target = "_self") =>
track("outbound", "", { url, text, target }),
+
+ // New methods for user identification
+ identify: (userId) => {
+ if (typeof userId !== "string" || userId.trim() === "") {
+ console.error("User ID must be a non-empty string");
+ return;
+ }
+ customUserId = userId.trim();
+ try {
+ localStorage.setItem("rybbit-user-id", customUserId);
+ } catch (e) {
+ // localStorage not available, user ID will only persist for session
+ console.warn("Could not persist user ID to localStorage");
+ }
+ },
+
+ clearUserId: () => {
+ customUserId = null;
+ try {
+ localStorage.removeItem("rybbit-user-id");
+ } catch (e) {
+ // localStorage not available, ignore
+ }
+ },
+
+ getUserId: () => customUserId,
};
if (autoTrackPageview) {
diff --git a/server/public/script.js b/server/public/script.js
index 7f300b858..097c4a1c6 100644
--- a/server/public/script.js
+++ b/server/public/script.js
@@ -1 +1 @@
-!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(null!==localStorage.getItem("disable-rybbit")){window.rybbit={pageview(){},event(){},trackOutbound(){}};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,n="false"!==t.getAttribute("data-auto-track-pageview"),i="false"!==t.getAttribute("data-track-spa"),s="false"!==t.getAttribute("data-track-query"),u="false"!==t.getAttribute("data-track-outbound"),o=[];try{let l=t.getAttribute("data-skip-patterns");l&&(o=JSON.parse(l),Array.isArray(o)||(o=[]))}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(g){console.error("Error parsing data-mask-patterns:",g)}function h(t){let e="__DOUBLE_ASTERISK_TOKEN__",r="__SINGLE_ASTERISK_TOKEN__",a=t.replace(/\*\*/g,e).replace(/\*/g,r).replace(/[.+?^${}()|[\]\\]/g,"\\$&"),n=(a=a.replace(/\//g,"\\/")).replace(RegExp(e,"g"),".*").replace(RegExp(r,"g"),"[^/]+");return RegExp("^"+n+"$")}function f(t,e){for(let r of e)try{let a=h(r);if(a.test(t))return r}catch(n){console.error(`Invalid pattern: ${r}`,n)}return null}let b=(t="pageview",a="",n={})=>{if("custom_event"===t&&(!a||"string"!=typeof a)){console.error("Event name is required and must be a string for custom events");return}let i=new URL(window.location.href),u=i.pathname;if(i.hash&&i.hash.startsWith("#/")&&(u=i.hash.substring(1)),f(u,o))return;let l=f(u,p);l&&(u=l);let c={site_id:r,hostname:i.hostname,pathname:u,querystring:s?i.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer,type:t,event_name:a,properties:"custom_event"===t||"outbound"===t?JSON.stringify(n):void 0};fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),mode:"cors",keepalive:!0}).catch(console.error)},v=()=>b("pageview"),y=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(v,a):v;if(u&&document.addEventListener("click",function(t){let e=t.target.closest("a");e&&e.href&&function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(n){return!1}}(e.href)&&b("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}),i){let m=history.pushState,A=history.replaceState;history.pushState=function(...t){m.apply(this,t),y()},history.replaceState=function(...t){A.apply(this,t),y()},window.addEventListener("popstate",y),window.addEventListener("hashchange",y)}window.rybbit={pageview:v,event:(t,e={})=>b("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>b("outbound","",{url:t,text:e,target:r})},n&&v()}();
\ No newline at end of file
+!function(){let t=document.currentScript,e=t.getAttribute("src").split("/script.js")[0];if(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"),s="false"!==t.getAttribute("data-track-query"),u="false"!==t.getAttribute("data-track-outbound"),l=[];try{let o=t.getAttribute("data-skip-patterns");o&&(l=JSON.parse(o),Array.isArray(l)||(l=[]))}catch(c){console.error("Error parsing data-skip-patterns:",c)}let d=[];try{let p=t.getAttribute("data-mask-patterns");p&&(d=JSON.parse(p),Array.isArray(d)||(d=[]))}catch(g){console.error("Error parsing data-mask-patterns:",g)}let h=null;try{let b=localStorage.getItem("rybbit-user-id");b&&(h=b)}catch(f){}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 m(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 v=(t="pageview",a="",i={})=>{if("custom_event"===t&&(!a||"string"!=typeof a)){console.error("Event name is required and must be a string for custom events");return}let n=new URL(window.location.href),u=n.pathname;if(n.hash&&n.hash.startsWith("#/")&&(u=n.hash.substring(1)),m(u,l))return;let o=m(u,d);o&&(u=o);let c={site_id:r,hostname:n.hostname,pathname:u,querystring:s?n.search:"",screenWidth:window.innerWidth,screenHeight:window.innerHeight,language:navigator.language,page_title:document.title,referrer:document.referrer,type:t,event_name:a,properties:"custom_event"===t||"outbound"===t?JSON.stringify(i):void 0,user_id:h};fetch(`${e}/track`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c),mode:"cors",keepalive:!0}).catch(console.error)},A=()=>v("pageview"),I=a>0?function t(e,r){let a;return(...t)=>{clearTimeout(a),a=setTimeout(()=>e.apply(this,t),r)}}(A,a):A;if(u&&document.addEventListener("click",function(t){let e=t.target.closest("a");e&&e.href&&function t(e){try{let r=window.location.hostname,a=new URL(e).hostname;return a!==r&&""!==a}catch(i){return!1}}(e.href)&&v("outbound","",{url:e.href,text:e.innerText||e.textContent||"",target:e.target||"_self"})}),n){let k=history.pushState,E=history.replaceState;history.pushState=function(...t){k.apply(this,t),I()},history.replaceState=function(...t){E.apply(this,t),I()},window.addEventListener("popstate",I),window.addEventListener("hashchange",I)}window.rybbit={pageview:A,event:(t,e={})=>v("custom_event",t,e),trackOutbound:(t,e="",r="_self")=>v("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}h=t.trim();try{localStorage.setItem("rybbit-user-id",h)}catch(e){console.warn("Could not persist user ID to localStorage")}},clearUserId(){h=null;try{localStorage.removeItem("rybbit-user-id")}catch(t){}},getUserId:()=>h},i&&A()}();
\ No newline at end of file
diff --git a/server/src/tracker/trackEvent.ts b/server/src/tracker/trackEvent.ts
index 18f75f673..f2f16eddb 100644
--- a/server/src/tracker/trackEvent.ts
+++ b/server/src/tracker/trackEvent.ts
@@ -31,6 +31,7 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [
referrer: z.string().max(2048).optional(),
event_name: z.string().max(256).optional(),
properties: z.string().max(2048).optional(),
+ user_id: z.string().max(255).optional(),
}),
z.object({
type: z.literal("custom_event"),
@@ -59,6 +60,7 @@ export const trackingPayloadSchema = z.discriminatedUnion("type", [
{ message: "Properties must be a valid JSON string" }
)
.optional(), // Optional but must be valid JSON if present
+ user_id: z.string().max(255).optional(),
}),
]);
diff --git a/server/src/tracker/trackingUtils.ts b/server/src/tracker/trackingUtils.ts
index f86bbd90f..8d9d57fb6 100644
--- a/server/src/tracker/trackingUtils.ts
+++ b/server/src/tracker/trackingUtils.ts
@@ -124,7 +124,11 @@ export function createBasePayload(
const userAgent = request.headers["user-agent"] || "";
const ipAddress = getIpAddress(request);
const siteId = validatedBody.site_id;
- const userId = getUserId(ipAddress, userAgent, siteId);
+
+ // Use custom user ID if provided, otherwise generate one
+ const userId = validatedBody.user_id
+ ? validatedBody.user_id.trim()
+ : getUserId(ipAddress, userAgent, siteId);
return {
...validatedBody,