Skip to content

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

add users page

Bill Yang56ad67f8e88e
diff --git a/client/src/app/[site]/sessions/components/SessionsTable.tsx b/client/src/app/[site]/sessions/components/SessionsTable.tsx
index f509937fc..3e2fc43a1 100644
--- a/client/src/app/[site]/sessions/components/SessionsTable.tsx
+++ b/client/src/app/[site]/sessions/components/SessionsTable.tsx
@@ -11,6 +11,8 @@ import { Browser } from "../../components/shared/icons/Browser";
import { CountryFlag } from "../../components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
import { Skeleton } from "@/components/ui/skeleton";
+import Link from "next/link";
+import { useParams } from "next/navigation";
type Session = {
session_id: string;
@@ -54,6 +56,8 @@ export default function SessionsTable({
hasNextPage,
isFetchingNextPage,
}: SessionsTableProps) {
+ const { site } = useParams();
+
// Reference for the scroll container
const tableContainerRef = useRef<HTMLDivElement>(null);
@@ -89,6 +93,22 @@ export default function SessionsTable({
const columns = useMemo(
() => [
+ columnHelper.accessor("user_id", {
+ header: "User",
+ cell: (info) => {
+ const userId = info.getValue();
+ return userId ? (
+ <Link
+ href={`/${site}/user/${userId}`}
+ className="text-blue-400 hover:text-blue-300 hover:underline"
+ >
+ {userId}
+ </Link>
+ ) : (
+ "Unknown"
+ );
+ },
+ }),
columnHelper.accessor("last_pageview_timestamp", {
header: "Last Seen",
cell: (info) => {
@@ -139,7 +159,7 @@ export default function SessionsTable({
cell: (info) => info.getValue() || "-",
}),
],
- []
+ [site]
);
// Table instance
@@ -152,7 +172,7 @@ export default function SessionsTable({
return (
<div
ref={tableContainerRef}
- className="overflow-auto rounded-lg"
+ className="overflow-auto rounded-lg bg-neutral-900 border border-neutral-800"
style={{ height: "calc(100vh - 200px)" }}
>
<table className="min-w-full divide-y divide-neutral-500">
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
new file mode 100644
index 000000000..cc609ae8f
--- /dev/null
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -0,0 +1,137 @@
+"use client";
+
+import { UserSessionsResponse, useGetUserSessions } from "@/hooks/api";
+import { useParams } from "next/navigation";
+import { format, parseISO } from "date-fns";
+import { Skeleton } from "@/components/ui/skeleton";
+import Link from "next/link";
+import { Browser } from "../../components/shared/icons/Browser";
+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
+import { CountryFlag } from "../../components/shared/icons/CountryFlag";
+import { getCountryName } from "@/lib/utils";
+import { useGetSiteMetadata } from "../../../../hooks/hooks";
+import { useStore } from "../../../../lib/store";
+
+export default function UserPage() {
+ const { userId } = useParams();
+ const { data, isLoading, error } = useGetUserSessions(userId as string);
+ const { site } = useStore();
+ const { siteMetadata, isLoading: isLoadingSiteMetadata } =
+ useGetSiteMetadata(site);
+ console.info(data);
+
+ // Sessions are now pre-grouped by the server
+ const groupedSessions = data?.data || [];
+
+ if (error) {
+ return <div className="p-6">Error: {(error as Error).message}</div>;
+ }
+
+ return (
+ <div className="container mx-auto py-8">
+ <div className="mb-8">
+ <h1 className="text-2xl font-bold mb-2">User Profile: {userId}</h1>
+ <div className="text-sm text-gray-400">
+ {groupedSessions.length > 0
+ ? `${groupedSessions.length} sessions recorded`
+ : isLoading
+ ? "Loading user data..."
+ : "No sessions found for this user"}
+ </div>
+ </div>
+
+ {isLoading ? (
+ <div className="space-y-8">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div
+ key={i}
+ className="bg-neutral-900 border border-neutral-800 rounded-lg p-6 mb-6"
+ >
+ <Skeleton className="h-6 w-48 mb-4" />
+ <Skeleton className="h-5 w-full mb-2" />
+ <Skeleton className="h-5 w-full mb-2" />
+ <Skeleton className="h-5 w-2/3" />
+ </div>
+ ))}
+ </div>
+ ) : (
+ <div className="space-y-8">
+ {groupedSessions.map((session: UserSessionsResponse[number]) => (
+ <div
+ key={session.session_id}
+ className="bg-neutral-900 border border-neutral-800 rounded-lg p-6 mb-6"
+ >
+ <div className="mb-4">
+ <h2 className="text-xl font-semibold mb-2">
+ Session from{" "}
+ {format(
+ parseISO(session.firstTimestamp),
+ "MMM d, yyyy h:mm a"
+ )}
+ </h2>
+ <div className="flex flex-wrap gap-4 text-sm text-gray-400">
+ <div className="flex items-center gap-2">
+ <Browser browser={session.browser || "Unknown"} />
+ {session.browser || "Unknown"}
+ </div>
+ <div className="flex items-center gap-2">
+ <OperatingSystem
+ os={session.operating_system || "Unknown"}
+ />
+ {session.operating_system || "Unknown"}
+ </div>
+ <div>{session.device_type || "Unknown Device"}</div>
+ <div className="flex items-center gap-2">
+ <CountryFlag country={session.country || "Unknown"} />
+ {getCountryName(session.country || "Unknown")}
+ </div>
+ </div>
+ </div>
+
+ <div className="space-y-4">
+ <h3 className="font-medium text-gray-300 mb-2">
+ Pages Viewed:
+ </h3>
+ {session.pageviews.map(
+ (
+ pageview: {
+ pathname: string;
+ title: string;
+ timestamp: string;
+ referrer: string;
+ },
+ index: number
+ ) => (
+ <div
+ key={index}
+ className="pl-4 border-l-2 border-neutral-800"
+ >
+ <div className="text-sm text-gray-400 mb-1">
+ {format(parseISO(pageview.timestamp), "h:mm:ss a")}
+ </div>
+ <div className="font-medium mb-1">
+ <a
+ href={`https://${siteMetadata?.domain}${pageview.pathname}`}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:underline"
+ >
+ {pageview.pathname}
+ </a>
+ </div>
+ {pageview.referrer ? (
+ <div className="text-sm text-gray-400">
+ Referrer: {pageview.referrer}
+ </div>
+ ) : null}
+ </div>
+ )
+ )}
+ </div>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/hooks/api.ts b/client/src/hooks/api.ts
index 7f115152f..f83e51601 100644
--- a/client/src/hooks/api.ts
+++ b/client/src/hooks/api.ts
@@ -211,6 +211,43 @@ export function useSiteHasData(siteId: string) {
return useGenericQuery<boolean>(`site-has-data/${siteId}`);
}
+// Updated type for grouped sessions from the API
+export type UserSessionsResponse = {
+ session_id: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ country: string;
+ firstTimestamp: string;
+ lastTimestamp: string;
+ pageviews: {
+ pathname: string;
+ title: string;
+ timestamp: string;
+ referrer: string;
+ }[];
+}[];
+
+export function useGetUserSessions(userId: string) {
+ const { time, site, filters } = useStore();
+ const { startDate, endDate } = getStartAndEndDate(time);
+
+ return useQuery({
+ queryKey: ["user-sessions", userId, time, site, filters],
+ queryFn: () => {
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ return authedFetch(
+ `${BACKEND_URL}/user/${userId}/sessions?${
+ startDate ? `startDate=${startDate}&` : ""
+ }${
+ endDate ? `endDate=${endDate}&` : ""
+ }timezone=${timezone}&site=${site}&filters=${JSON.stringify(filters)}`
+ ).then((res) => res.json());
+ },
+ staleTime: Infinity,
+ });
+}
+
type GetSessionsResponse = {
session_id: string;
user_id: string;
diff --git a/server/src/api/getUserSessions.ts b/server/src/api/getUserSessions.ts
new file mode 100644
index 000000000..3dea60d17
--- /dev/null
+++ b/server/src/api/getUserSessions.ts
@@ -0,0 +1,159 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import clickhouse from "../db/clickhouse/clickhouse.js";
+import {
+ getFilterStatement,
+ getTimeStatement,
+ processResults,
+} from "./utils.js";
+
+// Individual pageview type
+type Pageview = {
+ session_id: string;
+ timestamp: string;
+ pathname: string;
+ querystring: string;
+ page_title: string;
+ referrer: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ country: string;
+};
+
+// Grouped session type to be returned to the client
+type GroupedSession = {
+ session_id: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ country: string;
+ firstTimestamp: string;
+ lastTimestamp: string;
+ pageviews: {
+ pathname: string;
+ title: string;
+ timestamp: string;
+ referrer: string;
+ }[];
+};
+
+export interface GetUserSessionsRequest {
+ Querystring: {
+ startDate: string;
+ endDate: string;
+ timezone: string;
+ site: string;
+ filters: string;
+ };
+ Params: {
+ userId: string;
+ };
+}
+
+export async function getUserSessions(
+ {
+ query: { startDate, endDate, timezone, site, filters },
+ params: { userId },
+ }: FastifyRequest<GetUserSessionsRequest>,
+ res: FastifyReply
+) {
+ const filterStatement = getFilterStatement(filters);
+
+ const query = `
+SELECT
+ session_id,
+ timestamp,
+ pathname,
+ querystring,
+ page_title,
+ referrer,
+ browser,
+ operating_system,
+ device_type,
+ country
+FROM pageviews
+WHERE
+ site_id = ${site}
+ AND user_id = '${userId}'
+ ${filterStatement}
+ ${getTimeStatement(startDate, endDate, timezone)}
+ORDER BY timestamp ASC
+ `;
+
+ try {
+ const result = await clickhouse.query({
+ query,
+ format: "JSONEachRow",
+ });
+
+ const pageviews = await processResults<Pageview>(result);
+
+ // Group pageviews by session
+ const sessions: Record<string, GroupedSession> = {};
+
+ pageviews.forEach((pageview) => {
+ const {
+ session_id,
+ timestamp,
+ pathname,
+ querystring,
+ page_title,
+ referrer,
+ browser,
+ operating_system,
+ device_type,
+ country,
+ } = pageview;
+
+ // Construct full URL from pathname and querystring
+ const url = querystring ? `${pathname}?${querystring}` : pathname;
+
+ if (!sessions[session_id]) {
+ sessions[session_id] = {
+ session_id,
+ browser,
+ operating_system,
+ device_type,
+ country,
+ firstTimestamp: timestamp,
+ lastTimestamp: timestamp,
+ pageviews: [],
+ };
+ }
+
+ // Update timestamps
+ if (timestamp < sessions[session_id].firstTimestamp) {
+ sessions[session_id].firstTimestamp = timestamp;
+ }
+ if (timestamp > sessions[session_id].lastTimestamp) {
+ sessions[session_id].lastTimestamp = timestamp;
+ }
+
+ // Add pageview
+ sessions[session_id].pageviews.push({
+ pathname: url,
+ title: page_title || url,
+ timestamp,
+ referrer,
+ });
+
+ // Sort pageviews by timestamp in descending order
+ sessions[session_id].pageviews.sort(
+ (a, b) =>
+ new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime()
+ );
+ });
+
+ // Convert to array and sort by most recent session
+ const groupedSessions = Object.values(sessions).sort(
+ (a, b) =>
+ new Date(b.lastTimestamp).getTime() -
+ new Date(a.lastTimestamp).getTime()
+ );
+
+ return res.send({ data: groupedSessions });
+ } catch (error) {
+ console.error("Error fetching user sessions:", error);
+ return res.status(500).send({ error: "Failed to fetch user sessions" });
+ }
+}
diff --git a/server/src/index.ts b/server/src/index.ts
index 14a3d74bb..77582b579 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -24,6 +24,7 @@ import { mapHeaders } from "./lib/betterAuth.js";
import { trackPageView } from "./tracker/trackPageView.js";
import { createAccount } from "./api/createAccount.js";
import { getSessions } from "./api/getSessions.js";
+import { getUserSessions } from "./api/getUserSessions.js";
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
@@ -122,6 +123,7 @@ server.get("/overview-bucketed", getOverviewBucketed);
server.get("/single-col", getSingleCol);
server.get("/site-has-data/:site", getSiteHasData);
server.get("/sessions", getSessions);
+server.get("/user/:userId/sessions", getUserSessions);
// Administrative
server.post("/add-site", addSite);