Skip to content

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

Add user traits API and hooks for analytics (#860)

Goldflag1e142082f64a
diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.ts
index b0e2a7775..2799ea785 100644
--- a/client/src/api/analytics/endpoints/index.ts
+++ b/client/src/api/analytics/endpoints/index.ts
@@ -142,6 +142,19 @@ export type {
SessionReplaysParams,
} from "./sessionReplay";
+// User Traits endpoints
+export { fetchUserTraitKeys, fetchUserTraitValues, fetchUserTraitValueUsers } from "./userTraits";
+export type {
+ TraitKey,
+ TraitKeysResponse,
+ TraitValue,
+ TraitValuesResponse,
+ TraitValuesParams,
+ TraitValueUser,
+ TraitValueUsersResponse,
+ TraitValueUsersParams,
+} from "./userTraits";
+
// Export endpoints
export { exportPdfReport } from "./export";
export type { ExportPdfParams } from "./export";
diff --git a/client/src/api/analytics/endpoints/userTraits.ts b/client/src/api/analytics/endpoints/userTraits.ts
new file mode 100644
index 000000000..b246d6a23
--- /dev/null
+++ b/client/src/api/analytics/endpoints/userTraits.ts
@@ -0,0 +1,92 @@
+import { authedFetch } from "../../utils";
+
+export interface TraitKey {
+ key: string;
+ userCount: number;
+}
+
+export interface TraitKeysResponse {
+ keys: TraitKey[];
+}
+
+export interface TraitValue {
+ value: string;
+ userCount: number;
+}
+
+export interface TraitValuesResponse {
+ values: TraitValue[];
+ total: number;
+ hasMore: boolean;
+}
+
+export interface TraitValuesParams {
+ key: string;
+ limit?: number;
+ offset?: number;
+}
+
+/**
+ * Fetch all trait keys for a site
+ * GET /api/sites/:siteId/user-traits/keys
+ */
+export async function fetchUserTraitKeys(site: string | number): Promise<TraitKeysResponse> {
+ return authedFetch<TraitKeysResponse>(`/sites/${site}/user-traits/keys`);
+}
+
+/**
+ * Fetch trait values for a given key
+ * GET /api/sites/:siteId/user-traits/values
+ */
+export async function fetchUserTraitValues(
+ site: string | number,
+ params: TraitValuesParams
+): Promise<TraitValuesResponse> {
+ return authedFetch<TraitValuesResponse>(`/sites/${site}/user-traits/values`, {
+ key: params.key,
+ limit: params.limit,
+ offset: params.offset,
+ });
+}
+
+export interface TraitValueUser {
+ user_id: string;
+ identified_user_id: string;
+ traits: Record<string, unknown> | null;
+ country: string;
+ region: string;
+ city: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ sessions: number;
+}
+
+export interface TraitValueUsersResponse {
+ users: TraitValueUser[];
+ total: number;
+ hasMore: boolean;
+}
+
+export interface TraitValueUsersParams {
+ key: string;
+ value: string;
+ limit?: number;
+ offset?: number;
+}
+
+/**
+ * Fetch users that have a specific trait key+value
+ * GET /api/sites/:siteId/user-traits/users
+ */
+export async function fetchUserTraitValueUsers(
+ site: string | number,
+ params: TraitValueUsersParams
+): Promise<TraitValueUsersResponse> {
+ return authedFetch<TraitValueUsersResponse>(`/sites/${site}/user-traits/users`, {
+ key: params.key,
+ value: params.value,
+ limit: params.limit,
+ offset: params.offset,
+ });
+}
diff --git a/client/src/api/analytics/endpoints/users.ts b/client/src/api/analytics/endpoints/users.ts
index 3f03309d1..ad572e772 100644
--- a/client/src/api/analytics/endpoints/users.ts
+++ b/client/src/api/analytics/endpoints/users.ts
@@ -64,6 +64,8 @@ export interface UserSessionCountResponse {
export interface UsersParams extends CommonApiParams, PaginationParams, SortParams {
pageSize?: number;
identifiedOnly?: boolean;
+ search?: string;
+ searchField?: string;
}
export interface UserSessionsParams extends CommonApiParams {
@@ -94,6 +96,8 @@ export async function fetchUsers(site: string | number, params: UsersParams): Pr
sort_by: params.sortBy,
sort_order: params.sortOrder,
identified_only: params.identifiedOnly,
+ search: params.search || undefined,
+ search_field: params.searchField || undefined,
};
const response = await authedFetch<UsersListResponse>(`/sites/${site}/users`, queryParams);
diff --git a/client/src/api/analytics/hooks/useGetUserTraits.ts b/client/src/api/analytics/hooks/useGetUserTraits.ts
new file mode 100644
index 000000000..a02413e5d
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetUserTraits.ts
@@ -0,0 +1,65 @@
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { useStore } from "../../../lib/store";
+import {
+ fetchUserTraitKeys,
+ fetchUserTraitValues,
+ fetchUserTraitValueUsers,
+ TraitKeysResponse,
+ TraitValuesResponse,
+ TraitValueUsersResponse,
+} from "../endpoints";
+
+export function useGetUserTraitKeys() {
+ const { site } = useStore();
+
+ return useQuery<TraitKeysResponse>({
+ queryKey: ["user-trait-keys", site],
+ queryFn: () => fetchUserTraitKeys(site),
+ enabled: !!site,
+ });
+}
+
+export function useGetUserTraitValues(key: string | null) {
+ const { site } = useStore();
+ const limit = 1000;
+
+ return useInfiniteQuery<TraitValuesResponse>({
+ queryKey: ["user-trait-values", site, key],
+ queryFn: async ({ pageParam = 0 }) => {
+ return fetchUserTraitValues(site, {
+ key: key!,
+ limit,
+ offset: pageParam as number,
+ });
+ },
+ initialPageParam: 0,
+ getNextPageParam: (lastPage, allPages) => {
+ const totalFetched = allPages.reduce((acc, page) => acc + page.values.length, 0);
+ return lastPage.hasMore ? totalFetched : undefined;
+ },
+ enabled: !!site && !!key,
+ });
+}
+
+export function useGetUserTraitValueUsers(key: string | null, value: string | null) {
+ const { site } = useStore();
+ const limit = 250;
+
+ return useInfiniteQuery<TraitValueUsersResponse>({
+ queryKey: ["user-trait-value-users", site, key, value],
+ queryFn: async ({ pageParam = 0 }) => {
+ return fetchUserTraitValueUsers(site, {
+ key: key!,
+ value: value!,
+ limit,
+ offset: pageParam as number,
+ });
+ },
+ initialPageParam: 0,
+ getNextPageParam: (lastPage, allPages) => {
+ const totalFetched = allPages.reduce((acc, page) => acc + page.users.length, 0);
+ return lastPage.hasMore ? totalFetched : undefined;
+ },
+ enabled: !!site && !!key && value !== null,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetUsers.ts b/client/src/api/analytics/hooks/useGetUsers.ts
index 05c984ca1..61094bb32 100644
--- a/client/src/api/analytics/hooks/useGetUsers.ts
+++ b/client/src/api/analytics/hooks/useGetUsers.ts
@@ -13,12 +13,14 @@ export interface GetUsersOptions {
sortOrder: string;
filters?: Filter[];
identifiedOnly?: boolean;
+ search?: string;
+ searchField?: string;
}
export function useGetUsers(options: GetUsersOptions) {
const { time, site, timezone } = useStore();
- const { page, pageSize, sortBy, sortOrder, identifiedOnly = false } = options;
+ const { page, pageSize, sortBy, sortOrder, identifiedOnly = false, search, searchField } = options;
const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
const params = buildApiParams(time, { filters: filteredFilters });
@@ -29,7 +31,7 @@ export function useGetUsers(options: GetUsersOptions) {
pageSize: number;
}
>({
- queryKey: ["users", site, time, page, pageSize, sortBy, sortOrder, filteredFilters, identifiedOnly, timezone],
+ queryKey: ["users", site, time, page, pageSize, sortBy, sortOrder, filteredFilters, identifiedOnly, search, searchField, timezone],
queryFn: async () => {
const result = await fetchUsers(site, {
...params,
@@ -38,6 +40,8 @@ export function useGetUsers(options: GetUsersOptions) {
sortBy,
sortOrder: sortOrder as "asc" | "desc",
identifiedOnly,
+ search,
+ searchField,
});
return {
data: result.data as UsersResponse[],
diff --git a/client/src/app/[site]/users/components/TraitKeyRow.tsx b/client/src/app/[site]/users/components/TraitKeyRow.tsx
new file mode 100644
index 000000000..a016e0470
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitKeyRow.tsx
@@ -0,0 +1,35 @@
+"use client";
+
+import { useState } from "react";
+import { ChevronRight } from "lucide-react";
+import { TraitValuesList } from "./TraitValuesList";
+
+export function TraitKeyRow({
+ traitKey,
+ userCount,
+}: {
+ traitKey: string;
+ userCount: number;
+}) {
+ const [expanded, setExpanded] = useState(false);
+
+ return (
+ <div className="border-b border-neutral-100 dark:border-neutral-800 last:border-b-0">
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="w-full flex items-center justify-between px-4 py-3 hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
+ >
+ <div className="flex items-center gap-2">
+ <ChevronRight
+ className={`h-4 w-4 text-neutral-400 transition-transform ${expanded ? "rotate-90" : ""}`}
+ />
+ <span className="font-medium text-sm">{traitKey}</span>
+ </div>
+ <span className="text-neutral-500 dark:text-neutral-400 text-xs">
+ {userCount.toLocaleString()} {userCount === 1 ? "user" : "users"}
+ </span>
+ </button>
+ {expanded && <TraitValuesList traitKey={traitKey} />}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/users/components/TraitValueUsersList.tsx b/client/src/app/[site]/users/components/TraitValueUsersList.tsx
new file mode 100644
index 000000000..f0cc67c41
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitValueUsersList.tsx
@@ -0,0 +1,178 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useIntersectionObserver } from "@uidotdev/usehooks";
+import { Loader2, Search } from "lucide-react";
+import { Input } from "../../../../components/ui/input";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useGetUserTraitValueUsers } from "../../../../api/analytics/hooks/useGetUserTraits";
+import { Avatar } from "../../../../components/Avatar";
+import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
+import {
+ CountryFlagTooltipIcon,
+ BrowserTooltipIcon,
+ OperatingSystemTooltipIcon,
+ DeviceTypeTooltipIcon,
+} from "../../../../components/TooltipIcons/TooltipIcons";
+import { getUserDisplayName } from "../../../../lib/utils";
+
+export function TraitValueUsersList({
+ traitKey,
+ value,
+ userCount,
+}: {
+ traitKey: string;
+ value: string;
+ userCount: number;
+}) {
+ const [searchTerm, setSearchTerm] = useState("");
+ const { site } = useParams();
+ const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
+ useGetUserTraitValueUsers(traitKey, value);
+
+ const [ref, entry] = useIntersectionObserver({
+ threshold: 0,
+ root: null,
+ rootMargin: "0px 0px 200px 0px",
+ });
+
+ const flattenedUsers = useMemo(() => {
+ if (!data) return [];
+ return data.pages.flatMap((page) => page.users);
+ }, [data]);
+
+ const filteredUsers = useMemo(() => {
+ if (!searchTerm) return flattenedUsers;
+ const lower = searchTerm.toLowerCase();
+ return flattenedUsers.filter((user) =>
+ getUserDisplayName(user).toLowerCase().includes(lower)
+ );
+ }, [flattenedUsers, searchTerm]);
+
+ useEffect(() => {
+ if (
+ entry?.isIntersecting &&
+ hasNextPage &&
+ !isFetchingNextPage &&
+ !isLoading
+ ) {
+ fetchNextPage();
+ }
+ }, [
+ entry?.isIntersecting,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isLoading,
+ ]);
+
+ if (isLoading) {
+ return (
+ <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[19px]">
+ {Array.from({ length: Math.min(userCount, 10) }).map((_, i) => (
+ <div
+ key={i}
+ className="flex items-center gap-3 py-1.5 px-3 animate-pulse"
+ >
+ <div className="h-5 w-5 bg-neutral-200 dark:bg-neutral-800 rounded-full shrink-0" />
+ <div className="w-56 shrink">
+ <div
+ className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"
+ style={{ width: `${20 + Math.random() * 100}px` }}
+ />
+ </div>
+ <div className="flex items-center gap-1.5 shrink-0">
+ <div className="h-5 w-7 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div className="h-4 w-5 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div className="h-4 w-16 bg-neutral-200 dark:bg-neutral-800 rounded ml-1" />
+ </div>
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ if (flattenedUsers.length === 0) {
+ return (
+ <div className="pl-12 py-3 text-xs text-neutral-500 dark:text-neutral-400">
+ No users found
+ </div>
+ );
+ }
+
+ return (
+ <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[19px]">
+ {flattenedUsers.length > 5 && (
+ <div className="px-3 py-1.5">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-neutral-400" />
+ <Input
+ placeholder="Search users..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ className="h-7 pl-7 text-xs"
+ />
+ </div>
+ </div>
+ )}
+ {filteredUsers.map((user, index) => {
+ const isIdentified = !!user.identified_user_id;
+ const linkId = isIdentified ? user.identified_user_id : user.user_id;
+ const encodedLinkId = encodeURIComponent(linkId);
+ const displayName = getUserDisplayName(user);
+
+ return (
+ <div
+ key={`${linkId}-${index}`}
+ className="flex items-center gap-3 py-1.5 px-3 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
+ >
+ <Link
+ href={`/${site}/user/${encodedLinkId}`}
+ className="flex items-center gap-2 w-64 shrink"
+ target="_blank"
+ >
+ <Avatar size={20} id={linkId} />
+ <span
+ className="truncate hover:underline"
+ title={displayName}
+ >
+ {displayName}
+ </span>
+ </Link>
+ <div className="flex items-center gap-1.5 shrink-0">
+ {isIdentified && <IdentifiedBadge traits={user.traits} />}
+ <CountryFlagTooltipIcon
+ country={user.country || ""}
+ city={user.city || ""}
+ region={user.region || ""}
+ />
+ <BrowserTooltipIcon browser={user.browser || ""} />
+ <OperatingSystemTooltipIcon
+ operating_system={user.operating_system || ""}
+ />
+ <DeviceTypeTooltipIcon device_type={user.device_type || ""} />
+ <span className="text-neutral-500 dark:text-neutral-400 text-xs whitespace-nowrap ml-1">
+ {user.sessions.toLocaleString()}{" "}
+ {user.sessions === 1 ? "session" : "sessions"}
+ </span>
+ </div>
+ </div>
+ );
+ })}
+ {hasNextPage && (
+ <div ref={ref} className="py-2 flex justify-center">
+ {isFetchingNextPage && (
+ <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ Loading more...
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/users/components/TraitValuesList.tsx b/client/src/app/[site]/users/components/TraitValuesList.tsx
new file mode 100644
index 000000000..9d21b3e32
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitValuesList.tsx
@@ -0,0 +1,142 @@
+"use client";
+
+import { useEffect, useMemo, useState } from "react";
+import { useIntersectionObserver } from "@uidotdev/usehooks";
+import { ChevronRight, Loader2, Search } from "lucide-react";
+import { Input } from "../../../../components/ui/input";
+import { useGetUserTraitValues } from "../../../../api/analytics/hooks/useGetUserTraits";
+import { TraitValueUsersList } from "./TraitValueUsersList";
+
+function TraitValueRow({
+ traitKey,
+ value,
+ userCount,
+}: {
+ traitKey: string;
+ value: string;
+ userCount: number;
+}) {
+ const [expanded, setExpanded] = useState(false);
+
+ return (
+ <div>
+ <button
+ onClick={() => setExpanded(!expanded)}
+ className="w-full flex items-center justify-between py-1.5 px-3 text-sm hover:bg-neutral-50 dark:hover:bg-neutral-800/50 transition-colors"
+ >
+ <div className="flex items-center gap-2">
+ <ChevronRight
+ className={`h-4 w-4 text-neutral-400 transition-transform ${expanded ? "rotate-90" : ""}`}
+ />
+ <span className="text-neutral-700 dark:text-neutral-300 truncate">
+ {value || <span className="italic text-neutral-400">empty</span>}
+ </span>
+ </div>
+ <span className="text-neutral-500 dark:text-neutral-400 text-xs whitespace-nowrap">
+ {userCount.toLocaleString()} {userCount === 1 ? "user" : "users"}
+ </span>
+ </button>
+ {expanded && <TraitValueUsersList traitKey={traitKey} value={value} userCount={userCount} />}
+ </div>
+ );
+}
+
+export function TraitValuesList({ traitKey }: { traitKey: string }) {
+ const [searchTerm, setSearchTerm] = useState("");
+ const { data, isLoading, fetchNextPage, hasNextPage, isFetchingNextPage } =
+ useGetUserTraitValues(traitKey);
+
+ const [ref, entry] = useIntersectionObserver({
+ threshold: 0,
+ root: null,
+ rootMargin: "0px 0px 200px 0px",
+ });
+
+ const flattenedValues = useMemo(() => {
+ if (!data) return [];
+ return data.pages.flatMap((page) => page.values);
+ }, [data]);
+
+ const filteredValues = useMemo(() => {
+ if (!searchTerm) return flattenedValues;
+ const lower = searchTerm.toLowerCase();
+ return flattenedValues.filter((item) =>
+ item.value.toLowerCase().includes(lower)
+ );
+ }, [flattenedValues, searchTerm]);
+
+ useEffect(() => {
+ if (
+ entry?.isIntersecting &&
+ hasNextPage &&
+ !isFetchingNextPage &&
+ !isLoading
+ ) {
+ fetchNextPage();
+ }
+ }, [
+ entry?.isIntersecting,
+ fetchNextPage,
+ hasNextPage,
+ isFetchingNextPage,
+ isLoading,
+ ]);
+
+ if (isLoading) {
+ return (
+ <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[23px]">
+ {Array.from({ length: 3 }).map((_, i) => (
+ <div
+ key={i}
+ className="flex items-center justify-between py-2 px-3 animate-pulse"
+ >
+ <div className="flex items-center gap-2">
+ <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded shrink-0" />
+ <div
+ className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"
+ style={{ width: `${100 + i * 20}px` }}
+ />
+ </div>
+ <div className="h-4 w-16 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ return (
+ <div className="border-l border-neutral-150 dark:border-neutral-750 ml-[23px]">
+ {flattenedValues.length > 5 && (
+ <div className="px-3 py-1.5">
+ <div className="relative">
+ <Search className="absolute left-2 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-neutral-400" />
+ <Input
+ placeholder="Search values..."
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ className="h-7 pl-7 text-xs"
+ />
+ </div>
+ </div>
+ )}
+ {filteredValues.map((item, index) => (
+ <TraitValueRow
+ key={`${item.value}-${index}`}
+ traitKey={traitKey}
+ value={item.value}
+ userCount={item.userCount}
+ />
+ ))}
+ {hasNextPage && (
+ <div ref={ref} className="py-2 flex justify-center">
+ {isFetchingNextPage && (
+ <div className="flex items-center gap-2 text-neutral-600 dark:text-neutral-400 text-xs">
+ <Loader2 className="h-3 w-3 animate-spin" />
+ Loading more...
+ </div>
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/users/components/TraitsExplorer.tsx b/client/src/app/[site]/users/components/TraitsExplorer.tsx
new file mode 100644
index 000000000..e0e7991eb
--- /dev/null
+++ b/client/src/app/[site]/users/components/TraitsExplorer.tsx
@@ -0,0 +1,50 @@
+"use client";
+
+import { Tags } from "lucide-react";
+import { NothingFound } from "../../../../components/NothingFound";
+import { useGetUserTraitKeys } from "../../../../api/analytics/hooks/useGetUserTraits";
+import { TraitKeyRow } from "./TraitKeyRow";
+
+export function TraitsExplorer() {
+ const { data, isLoading } = useGetUserTraitKeys();
+
+ if (isLoading) {
+ return (
+ <div className="rounded-lg border border-neutral-100 dark:border-neutral-850 bg-white dark:bg-neutral-900">
+ {Array.from({ length: 5 }).map((_, i) => (
+ <div
+ key={i}
+ className="flex items-center justify-between px-4 py-3 border-b border-neutral-100 dark:border-neutral-800 last:border-b-0 animate-pulse"
+ >
+ <div className="flex items-center gap-2">
+ <div className="h-4 w-4 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ <div
+ className="h-5 bg-neutral-200 dark:bg-neutral-800 rounded"
+ style={{ width: `${80 + i * 16}px` }}
+ />
+ </div>
+ <div className="h-4 w-20 bg-neutral-200 dark:bg-neutral-800 rounded" />
+ </div>
+ ))}
+ </div>
+ );
+ }
+
+ if (!data?.keys?.length) {
+ return (
+ <NothingFound
+ icon={<Tags className="w-10 h-10" />}
+ title="No traits found"
+ description={<p>Traits will appear here once you <a href="https://rybbit.com/docs/identify-users" target="_blank" rel="noopener noreferrer" className="text-indigo-400 hover:underline">identify users</a> with custom properties.</p>}
+ />
+ );
+ }
+
+ return (
+ <div className="rounded-lg border border-neutral-100 dark:border-neutral-850 bg-white dark:bg-neutral-900">
+ {data.keys.map((item) => (
+ <TraitKeyRow key={item.key} traitKey={item.key} userCount={item.userCount} />
+ ))}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/users/components/UsersTable.tsx b/client/src/app/[site]/users/components/UsersTable.tsx
new file mode 100644
index 000000000..29b4faf06
--- /dev/null
+++ b/client/src/app/[site]/users/components/UsersTable.tsx
@@ -0,0 +1,456 @@
+"use client";
+
+import {
+ createColumnHelper,
+ flexRender,
+ getCoreRowModel,
+ getPaginationRowModel,
+ getSortedRowModel,
+ SortingState,
+ useReactTable,
+} from "@tanstack/react-table";
+import { addFilter, getTimezone } from "@/lib/store";
+import { ArrowDown, ArrowUp, ArrowUpDown, Info } from "lucide-react";
+import { DateTime } from "luxon";
+import Link from "next/link";
+import { useParams } from "next/navigation";
+import { useEffect, useState } from "react";
+import { useDebounce } from "@uidotdev/usehooks";
+import { UsersResponse } from "../../../../api/analytics/endpoints";
+import { useGetUsers } from "../../../../api/analytics/hooks/useGetUsers";
+import { Avatar } from "../../../../components/Avatar";
+import { ChannelIcon, extractDomain, getDisplayName } from "../../../../components/Channel";
+import { ErrorState } from "../../../../components/ErrorState";
+import { Favicon } from "../../../../components/Favicon";
+import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
+import { Pagination } from "../../../../components/pagination";
+import { Button } from "../../../../components/ui/button";
+import { Input } from "../../../../components/ui/input";
+import { Label } from "../../../../components/ui/label";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "../../../../components/ui/select";
+import { Switch } from "../../../../components/ui/switch";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
+import { FilterParameter } from "@rybbit/shared";
+import { getCountryName, getUserDisplayName } from "../../../../lib/utils";
+import { Browser } from "../../components/shared/icons/Browser";
+import { CountryFlag } from "../../components/shared/icons/CountryFlag";
+import { OperatingSystem } from "../../components/shared/icons/OperatingSystem";
+import { DeviceIcon } from "../../components/shared/icons/Device";
+
+const columnHelper = createColumnHelper<UsersResponse>();
+
+const handleFilterClick = (e: React.MouseEvent, parameter: FilterParameter, value: string | undefined) => {
+ e.stopPropagation();
+ if (!value) return;
+ addFilter({
+ parameter,
+ value: [value],
+ type: "equals",
+ });
+};
+
+const SortHeader = ({ column, children }: any) => {
+ const isSorted = column.getIsSorted();
+
+ return (
+ <Button
+ variant="ghost"
+ onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}
+ className="p-0 hover:bg-transparent"
+ >
+ {children}
+ {isSorted ? (
+ isSorted === "asc" ? (
+ <ArrowUp className="ml-2 h-4 w-4" />
+ ) : (
+ <ArrowDown className="ml-2 h-4 w-4" />
+ )
+ ) : (
+ <ArrowUpDown className="ml-2 h-4 w-4" />
+ )}
+ </Button>
+ );
+};
+
+const formatRelativeTime = (dateStr: string) => {
+ const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
+ const diff = Math.abs(date.diffNow(["minutes"]).minutes);
+
+ if (diff < 1) {
+ return "<1 min ago";
+ }
+
+ return date.toRelative();
+};
+
+export function UsersTable() {
+ const { site } = useParams();
+
+ const [pagination, setPagination] = useState({
+ pageIndex: 0,
+ pageSize: 50,
+ });
+ const [sorting, setSorting] = useState<SortingState>([{ id: "last_seen", desc: true }]);
+ const [identifiedOnly, setIdentifiedOnly] = useState(false);
+ const [searchTerm, setSearchTerm] = useState("");
+ const [searchField, setSearchField] = useState("username");
+ const debouncedSearch = useDebounce(searchTerm, 300);
+
+ useEffect(() => {
+ setPagination((prev) => ({ ...prev, pageIndex: 0 }));
+ }, [debouncedSearch]);
+
+ const effectiveIdentifiedOnly = identifiedOnly || debouncedSearch.length > 0;
+
+ const page = pagination.pageIndex + 1;
+ const sortBy = sorting.length > 0 ? sorting[0].id : "last_seen";
+ const sortOrder = sorting.length > 0 && !sorting[0].desc ? "asc" : "desc";
+
+ const { data, isLoading, isError } = useGetUsers({
+ page,
+ pageSize: pagination.pageSize,
+ sortBy,
+ sortOrder,
+ identifiedOnly: effectiveIdentifiedOnly,
+ search: debouncedSearch,
+ searchField,
+ });
+
+ const columns = [
+ columnHelper.accessor("user_id", {
+ header: "User",
+ cell: info => {
+ const identifiedUserId = info.row.original.identified_user_id;
+ const isIdentified = !!info.row.original.identified_user_id;
+ const linkId = isIdentified ? identifiedUserId : info.getValue();
+ const encodedLinkId = encodeURIComponent(linkId);
+ const displayName = getUserDisplayName(info.row.original);
+ const lastSeen = DateTime.fromSQL(info.row.original.last_seen, { zone: "utc" });
+
+ return (
+ <Link href={`/${site}/user/${encodedLinkId}`} className="flex items-center gap-2">
+ <Avatar size={20} id={linkId as string} lastActiveTime={lastSeen} />
+ <span className="max-w-32 truncate hover:underline" title={displayName}>
+ {displayName}
+ </span>
+ {isIdentified && <IdentifiedBadge traits={info.row.original.traits} />}
+ </Link>
+ );
+ },
+ }),
+ columnHelper.accessor("country", {
+ header: "Country",
+ cell: info => {
+ const country = info.getValue();
+ return (
+ <div
+ className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "country", country)}
+ >
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <CountryFlag country={country || ""} />
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{country ? getCountryName(country) : "Unknown"}</p>
+ </TooltipContent>
+ </Tooltip>
+ {info.row.original.city || info.row.original.region || getCountryName(country)}
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("referrer", {
+ header: "Channel",
+ cell: info => {
+ const channel = info.row.original.channel;
+ const referrer = info.getValue();
+ const domain = extractDomain(referrer);
+
+ if (domain) {
+ const displayName = getDisplayName(domain);
+ return (
+ <div
+ className="flex items-center gap-2 cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "channel", channel)}
+ >
+ <Favicon domain={domain} className="w-4 h-4" />
+ <span>{displayName}</span>
+ </div>
+ );
+ }
+
+ return (
+ <div
+ className="flex items-center gap-2 cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "channel", channel)}
+ >
+ <ChannelIcon channel={channel} />
+ <span>{channel}</span>
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("browser", {
+ header: "Browser",
+ cell: info => {
+ const browser = info.getValue();
+ return (
+ <div
+ className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "browser", browser)}
+ >
+ <Browser browser={browser || "Unknown"} />
+ {browser || "Unknown"}
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("operating_system", {
+ header: "OS",
+ cell: info => {
+ const os = info.getValue();
+ return (
+ <div
+ className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "operating_system", os)}
+ >
+ <OperatingSystem os={os || ""} />
+ {os || "Unknown"}
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("device_type", {
+ header: "Device",
+ cell: info => {
+ const deviceType = info.getValue();
+ return (
+ <div
+ className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
+ onClick={e => handleFilterClick(e, "device_type", deviceType)}
+ >
+ <DeviceIcon deviceType={deviceType || ""} />
+ {deviceType}
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("pageviews", {
+ header: ({ column }) => <SortHeader column={column}>Pageviews</SortHeader>,
+ cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
+ }),
+ columnHelper.accessor("events", {
+ header: ({ column }) => <SortHeader column={column}>Events</SortHeader>,
+ cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
+ }),
+ columnHelper.accessor("sessions", {
+ header: ({ column }) => <SortHeader column={column}>Sessions</SortHeader>,
+ cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
+ }),
+ columnHelper.accessor("last_seen", {
+ header: ({ column }) => <SortHeader column={column}>Last Seen</SortHeader>,
+ cell: info => {
+ const date = DateTime.fromSQL(info.getValue(), {
+ zone: "utc",
+ }).setZone(getTimezone());
+ const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
+ const relativeTime = formatRelativeTime(info.getValue());
+
+ return (
+ <div className="whitespace-nowrap">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>{relativeTime}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{formattedDate}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ );
+ },
+ }),
+ columnHelper.accessor("first_seen", {
+ header: ({ column }) => <SortHeader column={column}>First Seen</SortHeader>,
+ cell: info => {
+ const date = DateTime.fromSQL(info.getValue(), {
+ zone: "utc",
+ }).setZone(getTimezone());
+ const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
+ const relativeTime = formatRelativeTime(info.getValue());
+
+ return (
+ <div className="whitespace-nowrap">
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <span>{relativeTime}</span>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>{formattedDate}</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ );
+ },
+ }),
+ ];
+
+ const table = useReactTable({
+ data: data?.data || [],
+ columns,
+ pageCount: data?.totalCount ? Math.ceil(data.totalCount / pagination.pageSize) : -1,
+ state: {
+ pagination,
+ sorting,
+ },
+ onPaginationChange: setPagination,
+ onSortingChange: setSorting,
+ getCoreRowModel: getCoreRowModel(),
+ getSortedRowModel: getSortedRowModel(),
+ getPaginationRowModel: getPaginationRowModel(),
+ manualPagination: true,
+ manualSorting: true,
+ sortDescFirst: true,
+ });
+
+ if (isError) {
+ return (
+ <ErrorState
+ title="Failed to load users"
+ message="There was a problem fetching the users. Please try again later."
+ />
+ );
+ }
+
+ return (
+ <div className="space-y-3">
+ <div className="flex justify-between">
+ <div className="flex max-w-sm">
+ <Select value={searchField} onValueChange={setSearchField}>
+ <SelectTrigger className="w-[110px] shrink-0 rounded-r-none border-r-0">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ <SelectItem value="username">Username</SelectItem>
+ <SelectItem value="name">Name</SelectItem>
+ <SelectItem value="email">Email</SelectItem>
+ <SelectItem value="user_id">User ID</SelectItem>
+ </SelectContent>
+ </Select>
+ <Input
+ placeholder={`Search by ${searchField === "user_id" ? "user ID" : searchField}...`}
+ className="rounded-l-none"
+ type="search"
+ value={searchTerm}
+ onChange={(e) => setSearchTerm(e.target.value)}
+ />
+ </div>
+ <div className="flex items-center gap-2">
+ <Switch
+ id="identified-only"
+ checked={effectiveIdentifiedOnly}
+ onCheckedChange={setIdentifiedOnly}
+ disabled={debouncedSearch.length > 0}
+ />
+ <Label htmlFor="identified-only" className="text-sm text-neutral-600 dark:text-neutral-400 cursor-pointer">
+ Identified only
+ </Label>
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Link href="https://www.rybbit.io/docs/identify-users" target="_blank">
+ <Info className="h-4 w-4 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300 cursor-pointer" />
+ </Link>
+ </TooltipTrigger>
+ <TooltipContent>
+ <p>Learn how to identify users</p>
+ </TooltipContent>
+ </Tooltip>
+ </div>
+ </div>
+ <div className="rounded-md border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900">
+ <div className="relative overflow-x-auto">
+ <table className="w-full text-sm text-left">
+ <thead className="bg-neutral-50 dark:bg-neutral-850 text-neutral-500 dark:text-neutral-400 ">
+ {table.getHeaderGroups().map(headerGroup => (
+ <tr key={headerGroup.id}>
+ {headerGroup.headers.map(header => (
+ <th
+ key={header.id}
+ scope="col"
+ className="px-3 py-1 font-medium whitespace-nowrap"
+ style={{
+ minWidth: header.id === "user_id" ? "100px" : "auto",
+ }}
+ >
+ {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
+ </th>
+ ))}
+ </tr>
+ ))}
+ </thead>
+ <tbody>
+ {isLoading ? (
+ Array.from({ length: 15 }).map((_, index) => (
+ <tr key={index} className="border-b border-neutral-100 dark:border-neutral-800 animate-pulse">
+ {Array.from({ length: columns.length }).map((_, cellIndex) => (
+ <td key={cellIndex} className="px-3 py-3">
+ <div className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
+ </td>
+ ))}
+ </tr>
+ ))
+ ) : table.getRowModel().rows.length === 0 ? (
+ <tr>
+ <td
+ colSpan={columns.length}
+ className="px-3 py-8 text-center text-neutral-500 dark:text-neutral-400"
+ >
+ No users found
+ </td>
+ </tr>
+ ) : (
+ table.getRowModel().rows.map(row => {
+ const linkId = row.original.identified_user_id || row.original.user_id;
+ const href = `/${site}/user/${encodeURIComponent(linkId)}`;
+
+ return (
+ <tr key={row.id} className="border-b border-neutral-100 dark:border-neutral-800 group">
+ {row.getVisibleCells().map(cell => (
+ <td key={cell.id} className="px-3 py-3 relative">
+ {/* <Link
+ href={href}
+ className="absolute inset-0 z-10"
+ aria-label={`View user ${userId}`}
+ >
+ <span className="sr-only">View user details</span>
+ </Link> */}
+ <span className="relative z-0">
+ {flexRender(cell.column.columnDef.cell, cell.getContext())}
+ </span>
+ </td>
+ ))}
+ </tr>
+ );
+ })
+ )}
+ </tbody>
+ </table>
+ </div>
+
+ <div className="border-t border-neutral-100 dark:border-neutral-800">
+ <div className="px-4 py-3">
+ <Pagination
+ table={table}
+ data={{ items: data?.data || [], total: data?.totalCount || 0 }}
+ pagination={pagination}
+ setPagination={setPagination}
+ isLoading={isLoading}
+ itemName="users"
+ />
+ </div>
+ </div>
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsx
index 5c31eda96..6104b184a 100644
--- a/client/src/app/[site]/users/page.tsx
+++ b/client/src/app/[site]/users/page.tsx
@@ -1,439 +1,32 @@
"use client";
-import {
- createColumnHelper,
- flexRender,
- getCoreRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- SortingState,
- useReactTable,
-} from "@tanstack/react-table";
-import { addFilter, getTimezone } from "@/lib/store";
-import { ArrowDown, ArrowUp, ArrowUpDown, Monitor, Smartphone, Tablet } from "lucide-react";
-import { DateTime } from "luxon";
-import Link from "next/link";
-import { useParams } from "next/navigation";
-import { useState } from "react";
-import { UsersResponse } from "../../../api/analytics/endpoints";
-import { useGetUsers } from "../../../api/analytics/hooks/useGetUsers";
-import { Avatar } from "../../../components/Avatar";
-import { ChannelIcon, extractDomain, getDisplayName } from "../../../components/Channel";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
-import { ErrorState } from "../../../components/ErrorState";
-import { Favicon } from "../../../components/Favicon";
-import { IdentifiedBadge } from "../../../components/IdentifiedBadge";
-import { Pagination } from "../../../components/pagination";
-import { Button } from "../../../components/ui/button";
-import { Label } from "../../../components/ui/label";
-import { Switch } from "../../../components/ui/switch";
-import { Tooltip, TooltipContent, TooltipTrigger } from "../../../components/ui/tooltip";
-import { Info } from "lucide-react";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../components/ui/basic-tabs";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { USER_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { FilterParameter } from "@rybbit/shared";
-import { getCountryName, getUserDisplayName } from "../../../lib/utils";
-import { Browser } from "../components/shared/icons/Browser";
-import { CountryFlag } from "../components/shared/icons/CountryFlag";
-import { OperatingSystem } from "../components/shared/icons/OperatingSystem";
import { SubHeader } from "../components/SubHeader/SubHeader";
-import { DeviceIcon } from "../components/shared/icons/Device";
-
-// Set up column helper
-const columnHelper = createColumnHelper<UsersResponse>();
-
-// Helper to add filter on click
-const handleFilterClick = (e: React.MouseEvent, parameter: FilterParameter, value: string | undefined) => {
- e.stopPropagation();
- if (!value) return;
- addFilter({
- parameter,
- value: [value],
- type: "equals",
- });
-};
-
-// Create a reusable sort header component
-const SortHeader = ({ column, children }: any) => {
- const isSorted = column.getIsSorted();
-
- return (
- <Button
- variant="ghost"
- onClick={() => column.toggleSorting(isSorted ? isSorted === "asc" : true)}
- className="p-0 hover:bg-transparent"
- >
- {children}
- {isSorted ? (
- isSorted === "asc" ? (
- <ArrowUp className="ml-2 h-4 w-4" />
- ) : (
- <ArrowDown className="ml-2 h-4 w-4" />
- )
- ) : (
- <ArrowUpDown className="ml-2 h-4 w-4" />
- )}
- </Button>
- );
-};
+import { TraitsExplorer } from "./components/TraitsExplorer";
+import { UsersTable } from "./components/UsersTable";
export default function UsersPage() {
useSetPageTitle("Rybbit · Users");
- const { site } = useParams();
-
- // State for server-side operations
- const [pagination, setPagination] = useState({
- pageIndex: 0,
- pageSize: 50,
- });
- const [sorting, setSorting] = useState<SortingState>([{ id: "last_seen", desc: true }]);
- const [identifiedOnly, setIdentifiedOnly] = useState(false);
-
- // Convert page index to 1-based for the API
- const page = pagination.pageIndex + 1;
-
- // Get the first sorting column
- const sortBy = sorting.length > 0 ? sorting[0].id : "last_seen";
- const sortOrder = sorting.length > 0 && !sorting[0].desc ? "asc" : "desc";
-
- // Fetch data
- const { data, isLoading, isError } = useGetUsers({
- page,
- pageSize: pagination.pageSize,
- sortBy,
- sortOrder,
- identifiedOnly,
- });
-
- // Format relative time with special handling for times less than 1 minute
- const formatRelativeTime = (dateStr: string) => {
- const date = DateTime.fromSQL(dateStr, { zone: "utc" }).setZone(getTimezone());
- const diff = Math.abs(date.diffNow(["minutes"]).minutes);
-
- if (diff < 1) {
- return "<1 min ago";
- }
-
- return date.toRelative();
- };
-
- // Define table columns with consistent Title Case capitalization
- const columns = [
- columnHelper.accessor("user_id", {
- header: "User",
- cell: info => {
- const identifiedUserId = info.row.original.identified_user_id;
- const isIdentified = !!info.row.original.identified_user_id;
- // For links: use identified_user_id for identified users, device ID for anonymous
- const linkId = isIdentified ? identifiedUserId : info.getValue();
- const encodedLinkId = encodeURIComponent(linkId);
- const displayName = getUserDisplayName(info.row.original);
- const lastSeen = DateTime.fromSQL(info.row.original.last_seen, { zone: "utc" });
-
- return (
- <Link href={`/${site}/user/${encodedLinkId}`} className="flex items-center gap-2">
- <Avatar size={20} id={linkId as string} lastActiveTime={lastSeen} />
- <span className="max-w-32 truncate hover:underline" title={displayName}>
- {displayName}
- </span>
- {isIdentified && <IdentifiedBadge traits={info.row.original.traits} />}
- </Link>
- );
- },
- }),
- columnHelper.accessor("country", {
- header: "Country",
- cell: info => {
- const country = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "country", country)}
- >
- <Tooltip>
- <TooltipTrigger asChild>
- <CountryFlag country={country || ""} />
- </TooltipTrigger>
- <TooltipContent>
- <p>{country ? getCountryName(country) : "Unknown"}</p>
- </TooltipContent>
- </Tooltip>
- {info.row.original.city || info.row.original.region || getCountryName(country)}
- </div>
- );
- },
- }),
- columnHelper.accessor("referrer", {
- header: "Channel",
- cell: info => {
- const channel = info.row.original.channel;
- const referrer = info.getValue();
- const domain = extractDomain(referrer);
-
- if (domain) {
- const displayName = getDisplayName(domain);
- return (
- <div
- className="flex items-center gap-2 cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "channel", channel)}
- >
- <Favicon domain={domain} className="w-4 h-4" />
- <span>{displayName}</span>
- </div>
- );
- }
-
- return (
- <div
- className="flex items-center gap-2 cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "channel", channel)}
- >
- <ChannelIcon channel={channel} />
- <span>{channel}</span>
- </div>
- );
- },
- }),
- columnHelper.accessor("browser", {
- header: "Browser",
- cell: info => {
- const browser = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "browser", browser)}
- >
- <Browser browser={browser || "Unknown"} />
- {browser || "Unknown"}
- </div>
- );
- },
- }),
- columnHelper.accessor("operating_system", {
- header: "OS",
- cell: info => {
- const os = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "operating_system", os)}
- >
- <OperatingSystem os={os || ""} />
- {os || "Unknown"}
- </div>
- );
- },
- }),
- columnHelper.accessor("device_type", {
- header: "Device",
- cell: info => {
- const deviceType = info.getValue();
- return (
- <div
- className="flex items-center gap-2 whitespace-nowrap cursor-pointer hover:opacity-70"
- onClick={e => handleFilterClick(e, "device_type", deviceType)}
- >
- <DeviceIcon deviceType={deviceType || ""} />
- {deviceType}
- </div>
- );
- },
- }),
- columnHelper.accessor("pageviews", {
- header: ({ column }) => <SortHeader column={column}>Pageviews</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
- columnHelper.accessor("events", {
- header: ({ column }) => <SortHeader column={column}>Events</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
- columnHelper.accessor("sessions", {
- header: ({ column }) => <SortHeader column={column}>Sessions</SortHeader>,
- cell: info => <div className="whitespace-nowrap">{info.getValue().toLocaleString()}</div>,
- }),
-
- columnHelper.accessor("last_seen", {
- header: ({ column }) => <SortHeader column={column}>Last Seen</SortHeader>,
- cell: info => {
- const date = DateTime.fromSQL(info.getValue(), {
- zone: "utc",
- }).setZone(getTimezone());
- const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
- const relativeTime = formatRelativeTime(info.getValue());
-
- return (
- <div className="whitespace-nowrap">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{relativeTime}</span>
- </TooltipTrigger>
- <TooltipContent>
- <p>{formattedDate}</p>
- </TooltipContent>
- </Tooltip>
- </div>
- );
- },
- }),
- columnHelper.accessor("first_seen", {
- header: ({ column }) => <SortHeader column={column}>First Seen</SortHeader>,
- cell: info => {
- const date = DateTime.fromSQL(info.getValue(), {
- zone: "utc",
- }).setZone(getTimezone());
- const formattedDate = date.toLocaleString(DateTime.DATETIME_SHORT);
- const relativeTime = formatRelativeTime(info.getValue());
-
- return (
- <div className="whitespace-nowrap">
- <Tooltip>
- <TooltipTrigger asChild>
- <span>{relativeTime}</span>
- </TooltipTrigger>
- <TooltipContent>
- <p>{formattedDate}</p>
- </TooltipContent>
- </Tooltip>
- </div>
- );
- },
- }),
- ];
-
- // Set up table instance
- const table = useReactTable({
- data: data?.data || [],
- columns,
- pageCount: data?.totalCount ? Math.ceil(data.totalCount / pagination.pageSize) : -1,
- state: {
- pagination,
- sorting,
- },
- onPaginationChange: setPagination,
- onSortingChange: setSorting,
- getCoreRowModel: getCoreRowModel(),
- getSortedRowModel: getSortedRowModel(),
- getPaginationRowModel: getPaginationRowModel(),
- manualPagination: true,
- manualSorting: true,
- sortDescFirst: true,
- });
-
- if (isError) {
- return (
- <ErrorState
- title="Failed to load users"
- message="There was a problem fetching the users. Please try again later."
- />
- );
- }
-
return (
<DisabledOverlay message="Users" featurePath="users">
<div className="p-2 md:p-4 max-w-[1400px] mx-auto space-y-3">
<SubHeader availableFilters={USER_PAGE_FILTERS} />
- <div className="flex items-center justify-end gap-2">
- <Switch id="identified-only" checked={identifiedOnly} onCheckedChange={setIdentifiedOnly} />
- <Label htmlFor="identified-only" className="text-sm text-neutral-600 dark:text-neutral-400 cursor-pointer">
- Identified only
- </Label>
- <Tooltip>
- <TooltipTrigger asChild>
- <Link href="https://www.rybbit.io/docs/identify-users" target="_blank">
- <Info className="h-4 w-4 text-neutral-400 hover:text-neutral-600 dark:hover:text-neutral-300 cursor-pointer" />
- </Link>
- </TooltipTrigger>
- <TooltipContent>
- <p>Learn how to identify users</p>
- </TooltipContent>
- </Tooltip>
- </div>
- <div className="rounded-md border border-neutral-100 dark:border-neutral-800 bg-white dark:bg-neutral-900">
- <div className="relative overflow-x-auto">
- <table className="w-full text-sm text-left">
- <thead className="bg-neutral-50 dark:bg-neutral-850 text-neutral-500 dark:text-neutral-400 ">
- {table.getHeaderGroups().map(headerGroup => (
- <tr key={headerGroup.id}>
- {headerGroup.headers.map(header => (
- <th
- key={header.id}
- scope="col"
- className="px-3 py-1 font-medium whitespace-nowrap"
- style={{
- minWidth: header.id === "user_id" ? "100px" : "auto",
- }}
- >
- {header.isPlaceholder ? null : flexRender(header.column.columnDef.header, header.getContext())}
- </th>
- ))}
- </tr>
- ))}
- </thead>
- <tbody>
- {isLoading ? (
- Array.from({ length: 15 }).map((_, index) => (
- <tr key={index} className="border-b border-neutral-100 dark:border-neutral-800 animate-pulse">
- {Array.from({ length: columns.length }).map((_, cellIndex) => (
- <td key={cellIndex} className="px-3 py-3">
- <div className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded"></div>
- </td>
- ))}
- </tr>
- ))
- ) : table.getRowModel().rows.length === 0 ? (
- <tr>
- <td
- colSpan={columns.length}
- className="px-3 py-8 text-center text-neutral-500 dark:text-neutral-400"
- >
- No users found
- </td>
- </tr>
- ) : (
- table.getRowModel().rows.map(row => {
- // Use identified_user_id for identified users, device ID (user_id) for anonymous
- const linkId = row.original.identified_user_id || row.original.user_id;
- const href = `/${site}/user/${encodeURIComponent(linkId)}`;
-
- return (
- <tr key={row.id} className="border-b border-neutral-100 dark:border-neutral-800 group">
- {row.getVisibleCells().map(cell => (
- <td key={cell.id} className="px-3 py-3 relative">
- {/* <Link
- href={href}
- className="absolute inset-0 z-10"
- aria-label={`View user ${userId}`}
- >
- <span className="sr-only">View user details</span>
- </Link> */}
- <span className="relative z-0">
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </span>
- </td>
- ))}
- </tr>
- );
- })
- )}
- </tbody>
- </table>
- </div>
-
- {/* Pagination */}
- <div className="border-t border-neutral-100 dark:border-neutral-800">
- <div className="px-4 py-3">
- <Pagination
- table={table}
- data={{ items: data?.data || [], total: data?.totalCount || 0 }}
- pagination={pagination}
- setPagination={setPagination}
- isLoading={isLoading}
- itemName="users"
- />
- </div>
- </div>
- </div>
+ <Tabs defaultValue="users">
+ <TabsList>
+ <TabsTrigger value="users">Users</TabsTrigger>
+ <TabsTrigger value="traits">Traits</TabsTrigger>
+ </TabsList>
+ <TabsContent value="users">
+ <UsersTable />
+ </TabsContent>
+ <TabsContent value="traits">
+ <TraitsExplorer />
+ </TabsContent>
+ </Tabs>
</div>
</DisabledOverlay>
);
diff --git a/docs/src/app/(home)/sponsors/page.tsx b/docs/src/app/(home)/sponsors/page.tsx
index 79afe6509..32830d192 100644
--- a/docs/src/app/(home)/sponsors/page.tsx
+++ b/docs/src/app/(home)/sponsors/page.tsx
@@ -53,7 +53,7 @@ const sponsors: Sponsor[] = [
{
name: "Onyx",
logo: "/sponsors/onyx.jpeg",
- url: "https://onyx.com",
+ url: "https://onyx.app",
amount: 500,
},
{
diff --git a/server/src/api/analytics/index.ts b/server/src/api/analytics/index.ts
index ddb979566..4e6f99aff 100644
--- a/server/src/api/analytics/index.ts
+++ b/server/src/api/analytics/index.ts
@@ -44,6 +44,7 @@ export { getRetention } from "./getRetention.js";
export { getSession } from "./getSession.js";
export { getSessionLocations } from "./getSessionLocations.js";
export { getSessions } from "./getSessions.js";
-export { getUserInfo } from "./getUserInfo.js";
-export { getUserSessionCount } from "./getUserSessionCount.js";
-export { getUsers } from "./getUsers.js";
+export { getUserInfo } from "./users/getUserInfo.js";
+export { getUserSessionCount } from "./users/getUserSessionCount.js";
+export { getUsers } from "./users/getUsers.js";
+export { getUserTraitKeys, getUserTraitValues, getUserTraitValueUsers } from "./users/getUserTraits.js";
diff --git a/server/src/api/analytics/getUserInfo.ts b/server/src/api/analytics/users/getUserInfo.ts
similarity index 95%
rename from server/src/api/analytics/getUserInfo.ts
rename to server/src/api/analytics/users/getUserInfo.ts
index e84f336c0..662561ac7 100644
--- a/server/src/api/analytics/getUserInfo.ts
+++ b/server/src/api/analytics/users/getUserInfo.ts
@@ -1,9 +1,9 @@
import { FastifyReply, FastifyRequest } from "fastify";
import { eq, and } from "drizzle-orm";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { db } from "../../db/postgres/postgres.js";
-import { userProfiles, userAliases } from "../../db/postgres/schema.js";
-import { processResults } from "./utils/utils.js";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { db } from "../../../db/postgres/postgres.js";
+import { userProfiles, userAliases } from "../../../db/postgres/schema.js";
+import { processResults } from "../utils/utils.js";
interface UserPageviewData {
sessions: number;
diff --git a/server/src/api/analytics/getUserSessionCount.ts b/server/src/api/analytics/users/getUserSessionCount.ts
similarity index 92%
rename from server/src/api/analytics/getUserSessionCount.ts
rename to server/src/api/analytics/users/getUserSessionCount.ts
index 62c09f7ae..2559422a1 100644
--- a/server/src/api/analytics/getUserSessionCount.ts
+++ b/server/src/api/analytics/users/getUserSessionCount.ts
@@ -1,6 +1,6 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { processResults } from "./utils/utils.js";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { processResults } from "../utils/utils.js";
import SqlString from "sqlstring";
export interface GetUserSessionCountRequest {
diff --git a/server/src/api/analytics/users/getUserTraits.ts b/server/src/api/analytics/users/getUserTraits.ts
new file mode 100644
index 000000000..008506046
--- /dev/null
+++ b/server/src/api/analytics/users/getUserTraits.ts
@@ -0,0 +1,204 @@
+import { FastifyReply, FastifyRequest } from "fastify";
+import { sql } from "drizzle-orm";
+import { db } from "../../../db/postgres/postgres.js";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { processResults } from "../utils/utils.js";
+
+export async function getUserTraitKeys(
+ req: FastifyRequest<{
+ Params: { siteId: string };
+ }>,
+ res: FastifyReply
+) {
+ const siteId = Number(req.params.siteId);
+
+ try {
+ const result = await db.execute<{ key: string; user_count: number }>(sql`
+ SELECT key, COUNT(*)::int AS user_count
+ FROM user_profiles,
+ LATERAL jsonb_object_keys(COALESCE(traits, '{}'::jsonb)) AS key
+ WHERE site_id = ${siteId}
+ GROUP BY key
+ ORDER BY user_count DESC
+ `);
+
+ return res.send({
+ keys: (result as any[]).map((row) => ({
+ key: row.key,
+ userCount: row.user_count,
+ })),
+ });
+ } catch (error) {
+ console.error("Error fetching user trait keys:", error);
+ return res.status(500).send({ error: "Failed to fetch user trait keys" });
+ }
+}
+
+export async function getUserTraitValues(
+ req: FastifyRequest<{
+ Params: { siteId: string };
+ Querystring: { key: string; limit?: string; offset?: string };
+ }>,
+ res: FastifyReply
+) {
+ const siteId = Number(req.params.siteId);
+ const { key, limit: limitStr = "1000", offset: offsetStr = "0" } = req.query;
+
+ if (!key) {
+ return res.status(400).send({ error: "key query parameter is required" });
+ }
+
+ const limit = parseInt(limitStr, 10);
+ const offset = parseInt(offsetStr, 10);
+
+ try {
+ const [valuesResult, countResult] = await Promise.all([
+ db.execute<{ value: string; user_count: number }>(sql`
+ SELECT traits->>${key} AS value, COUNT(*)::int AS user_count
+ FROM user_profiles
+ WHERE site_id = ${siteId} AND traits ? ${key}
+ GROUP BY value
+ ORDER BY user_count DESC
+ LIMIT ${limit} OFFSET ${offset}
+ `),
+ db.execute<{ total: number }>(sql`
+ SELECT COUNT(DISTINCT traits->>${key})::int AS total
+ FROM user_profiles
+ WHERE site_id = ${siteId} AND traits ? ${key}
+ `),
+ ]);
+
+ const total = (countResult as any[])[0]?.total ?? 0;
+
+ return res.send({
+ values: (valuesResult as any[]).map((row) => ({
+ value: row.value,
+ userCount: row.user_count,
+ })),
+ total,
+ hasMore: offset + limit < total,
+ });
+ } catch (error) {
+ console.error("Error fetching user trait values:", error);
+ return res.status(500).send({ error: "Failed to fetch user trait values" });
+ }
+}
+
+export async function getUserTraitValueUsers(
+ req: FastifyRequest<{
+ Params: { siteId: string };
+ Querystring: { key: string; value: string; limit?: string; offset?: string };
+ }>,
+ res: FastifyReply
+) {
+ const siteId = Number(req.params.siteId);
+ const { key, value, limit: limitStr = "50", offset: offsetStr = "0" } = req.query;
+
+ if (!key || value === undefined) {
+ return res.status(400).send({ error: "key and value query parameters are required" });
+ }
+
+ const limit = parseInt(limitStr, 10);
+ const offset = parseInt(offsetStr, 10);
+
+ try {
+ // Step 1: Find matching user IDs and their traits from Postgres
+ const [profilesResult, countResult] = await Promise.all([
+ db.execute<{ user_id: string; traits: Record<string, unknown> | null }>(sql`
+ SELECT user_id, traits
+ FROM user_profiles
+ WHERE site_id = ${siteId} AND traits->>${key} = ${value}
+ ORDER BY user_id
+ LIMIT ${limit} OFFSET ${offset}
+ `),
+ db.execute<{ total: number }>(sql`
+ SELECT COUNT(*)::int AS total
+ FROM user_profiles
+ WHERE site_id = ${siteId} AND traits->>${key} = ${value}
+ `),
+ ]);
+
+ const profiles = profilesResult as any[];
+ const total = (countResult as any[])[0]?.total ?? 0;
+
+ if (profiles.length === 0) {
+ return res.send({ users: [], total, hasMore: offset + limit < total });
+ }
+
+ const userIds = profiles.map((p: any) => p.user_id);
+
+ // Step 2: Get session counts + metadata from ClickHouse
+ // Use events.identified_user_id to avoid conflict with the argMax alias
+ const chQuery = `
+ SELECT
+ COALESCE(NULLIF(events.identified_user_id, ''), events.user_id) AS effective_user_id,
+ argMax(events.user_id, timestamp) AS user_id,
+ argMax(events.identified_user_id, timestamp) AS identified_user_id,
+ argMax(country, timestamp) AS country,
+ argMax(region, timestamp) AS region,
+ argMax(city, timestamp) AS city,
+ argMax(browser, timestamp) AS browser,
+ argMax(operating_system, timestamp) AS operating_system,
+ argMax(device_type, timestamp) AS device_type,
+ count(DISTINCT session_id) AS sessions
+ FROM events
+ WHERE site_id = {siteId:Int32}
+ AND events.identified_user_id IN ({userIds:Array(String)})
+ GROUP BY effective_user_id
+ `;
+
+ const chResult = await clickhouse.query({
+ query: chQuery,
+ format: "JSONEachRow",
+ query_params: {
+ siteId,
+ userIds,
+ },
+ });
+
+ const chData = await processResults<{
+ effective_user_id: string;
+ user_id: string;
+ identified_user_id: string;
+ country: string;
+ region: string;
+ city: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ sessions: number;
+ }>(chResult);
+
+ // Step 3: Build lookup from ClickHouse data keyed by identified_user_id,
+ // then iterate Postgres profiles so every profile is returned even if
+ // ClickHouse has no matching events (zero-session fallback).
+ const chLookup = new Map(
+ chData.map((row) => [row.identified_user_id, row])
+ );
+
+ const users = profiles.map((p: any) => {
+ const ch = chLookup.get(p.user_id);
+ return {
+ user_id: ch?.user_id ?? p.user_id,
+ identified_user_id: p.user_id,
+ traits: p.traits ?? null,
+ country: ch?.country ?? "",
+ region: ch?.region ?? "",
+ city: ch?.city ?? "",
+ browser: ch?.browser ?? "",
+ operating_system: ch?.operating_system ?? "",
+ device_type: ch?.device_type ?? "",
+ sessions: ch?.sessions ?? 0,
+ };
+ });
+
+ return res.send({
+ users,
+ total,
+ hasMore: offset + limit < total,
+ });
+ } catch (error) {
+ console.error("Error fetching trait value users:", error);
+ return res.status(500).send({ error: "Failed to fetch trait value users" });
+ }
+}
diff --git a/server/src/api/analytics/getUsers.ts b/server/src/api/analytics/users/getUsers.ts
similarity index 72%
rename from server/src/api/analytics/getUsers.ts
rename to server/src/api/analytics/users/getUsers.ts
index cf5031bbc..0531316a7 100644
--- a/server/src/api/analytics/getUsers.ts
+++ b/server/src/api/analytics/users/getUsers.ts
@@ -1,8 +1,10 @@
import { FastifyReply, FastifyRequest } from "fastify";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { enrichWithTraits, getTimeStatement, processResults } from "./utils/utils.js";
+import { sql, SQL } from "drizzle-orm";
+import { clickhouse } from "../../../db/clickhouse/clickhouse.js";
+import { db } from "../../../db/postgres/postgres.js";
+import { enrichWithTraits, getTimeStatement, processResults } from "../utils/utils.js";
import { FilterParams } from "@rybbit/shared";
-import { getFilterStatement } from "./utils/getFilterStatement.js";
+import { getFilterStatement } from "../utils/getFilterStatement.js";
export type GetUsersResponse = {
user_id: string; // Device fingerprint
@@ -33,6 +35,8 @@ export interface GetUsersRequest {
sort_by?: string;
sort_order?: string;
identified_only?: string;
+ search?: string;
+ search_field?: string;
}>;
}
@@ -44,9 +48,44 @@ export async function getUsers(req: FastifyRequest<GetUsersRequest>, res: Fastif
sort_by: sortBy = "last_seen",
sort_order: sortOrder = "desc",
identified_only: identifiedOnly = "false",
+ search,
+ search_field: searchField = "username",
} = req.query;
const site = req.params.siteId;
- const filterIdentified = identifiedOnly === "true";
+ let filterIdentified = identifiedOnly === "true";
+
+ // Search for matching user IDs in Postgres when search is provided
+ const MAX_MATCHING_USER_IDS = 10000;
+ let matchingUserIds: string[] | null = null;
+ if (search && search.trim()) {
+ const searchTerm = `%${search.trim()}%`;
+ const siteId = Number(site);
+
+ const fieldConditions: Record<string, SQL> = {
+ username: sql`traits->>'username' ILIKE ${searchTerm}`,
+ name: sql`traits->>'name' ILIKE ${searchTerm}`,
+ email: sql`traits->>'email' ILIKE ${searchTerm}`,
+ user_id: sql`user_id ILIKE ${searchTerm}`,
+ };
+ const condition = fieldConditions[searchField] ?? fieldConditions.username;
+
+ const searchResult = await db.execute<{ user_id: string }>(sql`
+ SELECT user_id FROM user_profiles
+ WHERE site_id = ${siteId} AND ${condition}
+ LIMIT ${MAX_MATCHING_USER_IDS}
+ `);
+
+ matchingUserIds = searchResult.map((r) => r.user_id);
+ if (matchingUserIds.length === 0) {
+ return res.send({
+ data: [],
+ totalCount: 0,
+ page: parseInt(page, 10),
+ pageSize: parseInt(pageSize, 10),
+ });
+ }
+ filterIdentified = true;
+ }
const pageNum = parseInt(page, 10);
const pageSizeNum = parseInt(pageSize, 10);
@@ -91,6 +130,7 @@ WITH AggregatedUsers AS (
WHERE
site_id = {siteId:Int32}
${timeStatement}
+ ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
GROUP BY
effective_user_id
)
@@ -115,6 +155,7 @@ FROM (
AND identified_user_id != ''
${timeStatement}
${filterStatement}
+ ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
)
`
: `
@@ -125,6 +166,7 @@ WHERE
site_id = {siteId:Int32}
${filterStatement}
${timeStatement}
+ ${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
`;
try {
@@ -137,6 +179,7 @@ WHERE
siteId: Number(site),
limit: pageSizeNum,
offset,
+ ...(matchingUserIds ? { matchingUserIds } : {}),
},
}),
clickhouse.query({
@@ -144,6 +187,7 @@ WHERE
format: "JSONEachRow",
query_params: {
siteId: Number(site),
+ ...(matchingUserIds ? { matchingUserIds } : {}),
},
}),
]);
diff --git a/server/src/index.ts b/server/src/index.ts
index dd38f3d01..f214dbc1e 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -47,6 +47,9 @@ import {
getSiteEventCount,
getUserInfo,
getUserSessionCount,
+ getUserTraitKeys,
+ getUserTraitValueUsers,
+ getUserTraitValues,
getUsers,
updateGoal,
} from "./api/analytics/index.js";
@@ -247,6 +250,9 @@ async function analyticsRoutes(fastify: FastifyInstance) {
fastify.get("/sites/:siteId/users/session-count", publicSite, getUserSessionCount);
fastify.get("/sites/:siteId/users/:userId", publicSite, getUserInfo);
+ fastify.get("/sites/:siteId/user-traits/keys", publicSite, getUserTraitKeys);
+ fastify.get("/sites/:siteId/user-traits/values", publicSite, getUserTraitValues);
+ fastify.get("/sites/:siteId/user-traits/users", publicSite, getUserTraitValueUsers);
fastify.get("/sites/:siteId/session-locations", publicSite, getSessionLocations);
fastify.get("/sites/:siteId/funnels", publicSite, getFunnels);
fastify.get("/sites/:siteId/journeys", publicSite, getJourneys);