Skip to content

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

refactor trackPageView

Bill Yang33e1a747ec1a
diff --git a/server/public/analytics.js b/server/public/analytics.js
index a261cbb87..38c432559 100644
--- a/server/public/analytics.js
+++ b/server/public/analytics.js
@@ -6,8 +6,18 @@
.getAttribute("src")
.split("/analytics.js")[0];
+ if (!ANALYTICS_HOST) {
+ console.error("Please provide a valid analytics host");
+ return;
+ }
+
const SITE_ID = scriptTag.getAttribute("site-id");
+ if (!SITE_ID || isNaN(Number(SITE_ID))) {
+ console.error("Please provide a valid site ID");
+ return;
+ }
+
// Get debounce duration from data attribute or default to 300ms
const debounceDuration = scriptTag.getAttribute("data-debounce")
? Math.max(0, parseInt(scriptTag.getAttribute("data-debounce")))
diff --git a/server/src/actions/trackPageView.ts b/server/src/actions/trackPageView.ts
index 9f1ba3574..b2ff8c509 100644
--- a/server/src/actions/trackPageView.ts
+++ b/server/src/actions/trackPageView.ts
@@ -1,4 +1,4 @@
-import { FastifyRequest } from "fastify";
+import { FastifyReply, FastifyRequest } from "fastify";
import { TrackingPayload } from "../types.js";
import { getUserId, getDeviceType, getIpAddress } from "../utils.js";
import crypto from "crypto";
@@ -64,23 +64,34 @@ const updateSession = async (
};
export async function trackPageView(
- request: FastifyRequest<{ Body: TrackingPayload }>
+ request: FastifyRequest<{ Body: TrackingPayload }>,
+ reply: FastifyReply
) {
- const userAgent = request.headers["user-agent"] || "";
- const ipAddress = getIpAddress(request);
- const userId = getUserId(ipAddress, userAgent);
- const existingSession = await getExistingSession(userId);
+ try {
+ const userAgent = request.headers["user-agent"] || "";
+ const ipAddress = getIpAddress(request);
+ const userId = getUserId(ipAddress, userAgent);
+ const existingSession = await getExistingSession(userId);
- const payload = {
- ...request.body,
- ipAddress: ipAddress,
- timestamp: new Date().toISOString(),
- ua: userAgentParser(userAgent),
- userId: userId,
- sessionId: existingSession?.session_id || crypto.randomUUID(),
- };
+ const payload = {
+ ...request.body,
+ ipAddress: ipAddress,
+ timestamp: new Date().toISOString(),
+ ua: userAgentParser(userAgent),
+ userId: userId,
+ sessionId: existingSession?.session_id || crypto.randomUUID(),
+ };
+
+ pageviewQueue.add(payload);
+ // insertPageview(payload);
+ await updateSession(payload, existingSession);
- pageviewQueue.add(payload);
- // insertPageview(payload);
- updateSession(payload, existingSession);
+ return reply.status(200).send();
+ } catch (error) {
+ request.log.error(error);
+ return reply.status(500).send({
+ success: false,
+ error: "Failed to track pageview",
+ });
+ }
}
diff --git a/server/src/index.ts b/server/src/index.ts
index 0968b754e..b8891f44d 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -1,11 +1,14 @@
import cors from "@fastify/cors";
import fastifyStatic from "@fastify/static";
-import Fastify, { FastifyReply, FastifyRequest } from "fastify";
-import FastifyBetterAuth from "fastify-better-auth";
+import { toNodeHandler } from "better-auth/node";
+import Fastify from "fastify";
import cron from "node-cron";
import { dirname, join } from "path";
-import { fileURLToPath } from "url";
import { Headers, HeadersInit } from "undici"; // Ensure Undici is used for Headers
+import { fileURLToPath } from "url";
+import { addSite } from "./actions/sites/addSite.js";
+import { deleteSite } from "./actions/sites/deleteSite.js";
+import { getSites } from "./actions/sites/getSites.js";
import { trackPageView } from "./actions/trackPageView.js";
import { getBrowsers } from "./api/getBrowsers.js";
import { getCountries } from "./api/getCountries.js";
@@ -20,12 +23,7 @@ import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
import { initializePostgres } from "./db/postgres/postgres.js";
import { cleanupOldSessions } from "./db/postgres/session-cleanup.js";
import { auth } from "./lib/auth.js";
-import { TrackingPayload } from "./types.js";
-import { toNodeHandler } from "better-auth/node";
import { mapHeaders } from "./lib/betterAuth.js";
-import { addSite } from "./actions/sites/addSite.js";
-import { getSites } from "./actions/sites/getSites.js";
-import { deleteSite } from "./actions/sites/deleteSite.js";
// ESM replacement for __dirname:
const __filename = fileURLToPath(import.meta.url);
@@ -134,24 +132,7 @@ server.post("/delete-site/:id", deleteSite);
server.get("/get-sites", getSites);
// Track pageview endpoint
-server.post<{ Body: TrackingPayload }>(
- "/track/pageview",
- async (
- request: FastifyRequest<{ Body: TrackingPayload }>,
- reply: FastifyReply
- ) => {
- try {
- await trackPageView(request);
- return { success: true };
- } catch (error) {
- request.log.error(error);
- return reply.status(500).send({
- success: false,
- error: "Failed to track pageview",
- });
- }
- }
-);
+server.post("/track/pageview", trackPageView);
const start = async () => {
try {