Skip to content

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

refactor(client): collapse the analytics query layer onto one descriptor-driven seam (#1121)

Goldflag8dbed0d7e46b
diff --git a/client/CLAUDE.md b/client/CLAUDE.md
index d1ebac232..c503d19d7 100644
--- a/client/CLAUDE.md
+++ b/client/CLAUDE.md
@@ -65,7 +65,17 @@ messages/ # Translation files (en.json, de.json, etc.)
## API Layer Pattern
-Every data domain has two layers:
+**Analytics reads** go through one query module. A hook declares a descriptor β€” what differs between endpoints β€” and nothing else:
+
+```ts
+export function useGetEventNames() {
+ return useAnalyticsQuery<EventName[]>({ key: "event-names", path: "events/names" });
+}
+```
+
+`useAnalyticsQuery` / `useAnalyticsInfiniteQuery` (`api/analytics/useAnalyticsQuery.ts`) resolve the store context through selectors, serialise the time window, build the queryKey from the same request object they send (so key and request cannot drift), unwrap the `{ data }` envelope, and own the same-site placeholder policy, `staleTime`, and `enabled: !!site`. Non-React callers (CSV export, `useQueries` fan-outs) use `buildAnalyticsRequest` / `fetchAnalytics` from `api/analytics/analyticsRequest.ts` directly. Never hand-assemble a queryKey listing store inputs, and never call `authedFetch` for an analytics read.
+
+**Everything else** (admin, gsc, stripe β€” and analytics *writes*) keeps two layers:
**1. Endpoints** (`api/[domain]/endpoints/*.ts`) – pure async functions, no React:
```ts
@@ -85,16 +95,14 @@ export function useGetSomething(siteId?: string) {
}
```
-**`authedFetch<T>(url, options?)`** (`api/utils.ts`):
+**`authedFetch<T>(url, params?, config?)`** (`api/utils.ts`):
- Prepends `BACKEND_URL`
- Sends `credentials: "include"`
-- Adds `x-private-key` header if present
+- Adds `x-private-key` header if present β€” resolved via `api/requestContext.ts`, so the HTTP layer imports neither the store nor routing
- Converts array params to JSON strings
- Extracts and throws backend errors from `response.data.error`
-**`buildApiParams(time, { filters? })`** (`api/utils.ts`) returns a plain `CommonApiParams` object; the free functions `toQueryParams` / `toBucketedQueryParams` / `toMetricQueryParams` (`api/analytics/endpoints/types.ts`) convert it to snake_case wire params inside endpoint functions.
-
-**`useAnalyticsQuery` / `useAnalyticsInfiniteQuery`** (`api/analytics/useAnalyticsQuery.ts`) β€” the standard way to build analytics hooks. Reads site/time/filters/timezone from the store once, derives the wire params, and builds the queryKey from the same params object so key and request cannot drift. Handles the same-site placeholder policy, `staleTime`, and `enabled: !!site`. Per-endpoint hooks only declare their key prefix, endpoint-specific `extraParams`, and fetcher. Never hand-assemble a queryKey listing store inputs in an analytics hook.
+**`buildApiParams(time, { timeZone, filters? })`** (`api/utils.ts`) is a pure function returning a `CommonApiParams` object; `toQueryParams` (`api/analytics/endpoints/types.ts`) converts it to snake_case wire params. The timezone is injected, never read from the store β€” use `useTimezone()` in components, `getTimezone()` outside React.
## State Management
diff --git a/client/src/api/CLAUDE.md b/client/src/api/CLAUDE.md
index 95a8a4c41..b62b778de 100644
--- a/client/src/api/CLAUDE.md
+++ b/client/src/api/CLAUDE.md
@@ -20,22 +20,33 @@ api/
## Architecture Pattern
-### Separation of Concerns
+### Analytics reads: one descriptor, one query module
-Each domain (admin, analytics) follows a two-layer pattern:
+Analytics reads do **not** get a per-endpoint fetcher. A hook declares a
+descriptor β€” what differs between endpoints β€” and `useAnalyticsQuery` does the
+rest: resolves the store context, serialises the time window, builds the query
+key from the same object it sends, unwraps the `{ data }` envelope.
-1. **endpoints/** - Pure async functions that call `authedFetch`
- - Contains TypeScript interfaces and types
- - No React dependencies
- - Reusable across different contexts
- - Exports via `index.ts` barrel file
+```typescript
+// analytics/hooks/useGetOverview.ts
+export function useGetOverview({ lite }: { lite?: boolean } = {}) {
+ return useAnalyticsQuery<GetOverviewResponse>({
+ key: "overview",
+ path: lite ? "overview-lite" : "overview",
+ });
+}
+```
+
+`analytics/endpoints/*.ts` still holds the response **types** (and the write
+endpoints β€” create/update/delete, which are ordinary mutations). It no longer
+holds read fetchers.
-2. **hooks/** - React Query hooks wrapping endpoints
- - Uses `useQuery` for data fetching
- - Uses `useMutation` for data mutations
- - Handles caching, invalidation, and React lifecycle
+### Everything else: endpoints + hooks
-### Example
+Non-analytics domains (admin, gsc, stripe) keep the two-layer pattern:
+
+1. **endpoints/** β€” pure async functions calling `authedFetch`, no React
+2. **hooks/** β€” React Query wrappers
```typescript
// endpoints/sites.ts
@@ -64,29 +75,49 @@ Wrapper around axios that:
- Includes private key header when present
- Extracts and throws backend error messages
-### `buildApiParams(time, options?)`
+It knows nothing about the store or routing: the private key comes from
+`requestContext.ts`, whose resolver is installed once by
+`installRequestContext.ts` (side-effect imported in `app/Providers.tsx`).
+Tests and non-browser callers can swap the resolver instead of faking a store.
+
+### `buildApiParams(time, { timeZone, filters? })`
+
+Pure function converting a `Time` object to `CommonApiParams`, covering every
+time mode (date range, exact datetime range, past-minutes). The timezone is
+injected, never read from the store.
+
+### `buildAnalyticsRequest` / `fetchAnalytics` (`analytics/analyticsRequest.ts`)
-Converts a `Time` object to `CommonApiParams` for analytics endpoints.
+The analytics read layer as a value. A descriptor is `{ path, params?, body?,
+unwrap? }` β€” path under `/sites/:site`, params already named as the wire
+expects them (undefined dropped), `body` for the POST reads, `unwrap: false`
+when the response is not `{ data }`. `buildAnalyticsRequest(descriptor,
+context)` returns the exact request; `fetchAnalytics(site, request)` sends it.
+No React, so non-hook callers (CSV export, the globe timeline, rollup
+`useQueries`) go through the same seam. Covered by `analyticsRequest.test.ts`.
### `useAnalyticsQuery` / `useAnalyticsInfiniteQuery` (`analytics/useAnalyticsQuery.ts`)
-The standard base for analytics query hooks. Reads the store context (site,
-time, previousTime, filters, timezone) once, derives the wire params, and
-builds the queryKey from the same params object β€” key and request cannot
-drift. Owns the same-site placeholder policy, `staleTime: 60_000`, and
-`enabled: !!site`. A per-endpoint hook declares only:
+The standard base for analytics query hooks. `useAnalyticsContext` reads the
+store through selectors (site, time, previousTime, filters, timezone) β€” so a
+`selectedStat` change does not re-render every analytics hook β€” and the
+queryKey is built from the same request object that gets sent, so key and
+request cannot drift. Owns the same-site placeholder policy, `staleTime:
+60_000`, and `enabled: !!site`. A hook declares:
- `key` β€” the historical key prefix (mutations invalidate by it)
-- `extraParams` β€” endpoint params beyond time/filters (also keyed automatically)
-- `keyExtras` β€” only for values that select the fetcher itself (e.g. `lite`)
-- `fetch` β€” the endpoint function, plus any response reshaping
+- the descriptor fields (`path`, `params`, `body`, `unwrap`)
+- context options where needed: `useTime: false` for endpoints not scoped to
+ the selected period, `useFilters`, `periodTime`, `overrideTime`, `site`
-Do not hand-assemble queryKeys that list store inputs in analytics hooks.
+Do not hand-assemble queryKeys that list store inputs in analytics hooks, and
+do not call `authedFetch` directly for an analytics read.
## Conventions
- **Naming**: Endpoint functions use `fetch*`, `create*`, `update*`, `delete*` prefixes
- **Naming**: Hooks use `use*` prefix (e.g., `useGetSite`, `useCreateGoal`)
+- **Analytics reads**: add a descriptor to a hook, not a new fetcher
- **Types**: Export types alongside functions from endpoint files
- **Query Keys**: Use descriptive array keys like `["get-site", siteId]`
- **Error Handling**: Let errors propagate; hooks handle via React Query
diff --git a/client/src/api/analytics/analyticsRequest.test.ts b/client/src/api/analytics/analyticsRequest.test.ts
new file mode 100644
index 000000000..25f118eaf
--- /dev/null
+++ b/client/src/api/analytics/analyticsRequest.test.ts
@@ -0,0 +1,131 @@
+import { Filter } from "@rybbit/shared";
+import { describe, expect, it } from "vitest";
+import { Time } from "../../components/DateSelector/types";
+import { buildAnalyticsRequest } from "./analyticsRequest";
+
+const timeZone = "America/New_York";
+
+const build = (descriptor: Parameters<typeof buildAnalyticsRequest>[0], time: Time | null, filters?: Filter[]) =>
+ buildAnalyticsRequest(descriptor, { time, timeZone, filters });
+
+describe("buildAnalyticsRequest", () => {
+ it("serialises a day as a whole-day date range", () => {
+ const request = build({ path: "overview" }, { mode: "day", day: "2026-08-14" });
+
+ expect(request.path).toBe("overview");
+ expect(request.params).toEqual({
+ start_date: "2026-08-14",
+ end_date: "2026-08-14",
+ time_zone: timeZone,
+ });
+ expect(request.body).toBeUndefined();
+ expect(request.unwrap).toBe(true);
+ });
+
+ it("closes week, month and year ranges on the period boundary", () => {
+ expect(build({ path: "overview" }, { mode: "week", week: "2026-08-10" }).params).toMatchObject({
+ start_date: "2026-08-10",
+ end_date: "2026-08-16",
+ });
+ expect(build({ path: "overview" }, { mode: "month", month: "2026-08-01" }).params).toMatchObject({
+ start_date: "2026-08-01",
+ end_date: "2026-08-31",
+ });
+ expect(build({ path: "overview" }, { mode: "year", year: "2026-01-01" }).params).toMatchObject({
+ start_date: "2026-01-01",
+ end_date: "2026-12-31",
+ });
+ });
+
+ it("sends past-minutes rather than a date range", () => {
+ const request = build({ path: "overview" }, { mode: "past-minutes", pastMinutesStart: 60, pastMinutesEnd: 0 });
+
+ expect(request.params).toEqual({
+ past_minutes_start: 60,
+ past_minutes_end: 0,
+ time_zone: timeZone,
+ });
+ expect(request.params).not.toHaveProperty("start_date");
+ });
+
+ it("converts an exact datetime range to UTC datetimes", () => {
+ const request = build(
+ { path: "overview" },
+ {
+ mode: "range",
+ startDate: "2026-08-14",
+ endDate: "2026-08-14",
+ startTime: "09:00",
+ endTime: "17:00",
+ }
+ );
+
+ // 09:00–17:00 in New York (UTC-4 in August) is 13:00–21:00 UTC.
+ expect(request.params).toEqual({
+ start_datetime: "2026-08-14 13:00:00",
+ end_datetime: "2026-08-14 21:00:00",
+ time_zone: timeZone,
+ });
+ });
+
+ it("sends an empty window for all-time", () => {
+ const request = build({ path: "overview" }, { mode: "all-time" });
+
+ expect(request.params).toEqual({ start_date: "", end_date: "", time_zone: timeZone });
+ });
+
+ it("omits the window entirely when there is no time context", () => {
+ const request = build({ path: "user-traits/keys" }, null);
+
+ expect(request.params).toEqual({ time_zone: timeZone });
+ });
+
+ it("carries filters, but drops empty ones", () => {
+ const real: Filter = { parameter: "browser", type: "equals", value: ["Chrome"] };
+ const blank: Filter = { parameter: "country", type: "equals", value: [""] };
+
+ expect(build({ path: "overview" }, { mode: "day", day: "2026-08-14" }, [real, blank]).params.filters).toEqual([
+ real,
+ ]);
+ expect(build({ path: "overview" }, { mode: "day", day: "2026-08-14" }, [blank]).params).not.toHaveProperty(
+ "filters"
+ );
+ expect(build({ path: "user-traits/keys" }, null, [real]).params.filters).toEqual([real]);
+ });
+
+ it("merges endpoint params over the shared context and drops undefined ones", () => {
+ const request = build(
+ { path: "metric", params: { parameter: "pathname", limit: 10, page: undefined } },
+ { mode: "day", day: "2026-08-14" }
+ );
+
+ expect(request.params).toEqual({
+ start_date: "2026-08-14",
+ end_date: "2026-08-14",
+ time_zone: timeZone,
+ parameter: "pathname",
+ limit: 10,
+ });
+ });
+
+ it("hands the resolved window to body-carrying endpoints", () => {
+ const request = build(
+ {
+ path: "funnels/analyze",
+ body: common => ({ steps: ["/"], startDate: common.startDate, endDate: common.endDate }),
+ unwrap: false,
+ },
+ { mode: "day", day: "2026-08-14" }
+ );
+
+ expect(request.body).toEqual({ steps: ["/"], startDate: "2026-08-14", endDate: "2026-08-14" });
+ expect(request.unwrap).toBe(false);
+ });
+
+ it("produces identical requests for identical inputs, so query keys cannot drift", () => {
+ const descriptor = { path: "metric", params: { parameter: "browser" } };
+ const time: Time = { mode: "day", day: "2026-08-14" };
+
+ expect(build(descriptor, time)).toEqual(build(descriptor, time));
+ });
+});
diff --git a/client/src/api/analytics/analyticsRequest.ts b/client/src/api/analytics/analyticsRequest.ts
new file mode 100644
index 000000000..8c4115e40
--- /dev/null
+++ b/client/src/api/analytics/analyticsRequest.ts
@@ -0,0 +1,84 @@
+import { Filter } from "@rybbit/shared";
+import { Time } from "../../components/DateSelector/types";
+import { authedFetch, buildApiParams } from "../utils";
+import { CommonApiParams, toQueryParams } from "./endpoints/types";
+
+/**
+ * The analytics read layer, as a value.
+ *
+ * Every analytics endpoint is `/sites/:site/<path>` carrying the shared time
+ * window and filters on the query string plus a handful of endpoint params.
+ * A descriptor says only what differs between them; `buildAnalyticsRequest`
+ * turns it into the exact request that goes on the wire, and the query key is
+ * built from that same object β€” so key and request cannot drift.
+ */
+export interface AnalyticsDescriptor {
+ /** Path under `/sites/:site` β€” e.g. "overview", "events/names". */
+ path: string;
+ /**
+ * Endpoint params beyond the shared time/filter context, already named as
+ * the API expects them on the wire. Undefined values are dropped.
+ */
+ params?: Record<string, unknown>;
+ /**
+ * Present β‡’ the read is a POST carrying this JSON body (funnel analysis,
+ * dashboard cards). Receives the resolved time context for the endpoints
+ * that take the window in the body rather than the query string.
+ */
+ body?: (common: CommonApiParams) => unknown;
+ /** Response body is `{ data: T }` and T is what the caller wants. Default true. */
+ unwrap?: boolean;
+}
+
+/**
+ * The resolved time/filter context a request is made in. `time: null` is for
+ * the handful of endpoints that are not scoped to the selected period (trait
+ * keys, saved funnels, retention) β€” they send no window and, just as
+ * importantly, do not refetch when the date selector moves.
+ */
+export interface AnalyticsContext {
+ time: Time | null;
+ timeZone: string;
+ filters?: Filter[];
+}
+
+export interface AnalyticsRequest {
+ path: string;
+ params: Record<string, unknown>;
+ body?: unknown;
+ unwrap: boolean;
+}
+
+const omitUndefined = (params: Record<string, unknown>) =>
+ Object.fromEntries(Object.entries(params).filter(([, value]) => value !== undefined));
+
+export function buildAnalyticsRequest(descriptor: AnalyticsDescriptor, context: AnalyticsContext): AnalyticsRequest {
+ const common: CommonApiParams = context.time
+ ? buildApiParams(context.time, { timeZone: context.timeZone, filters: context.filters })
+ : { startDate: "", endDate: "", timeZone: context.timeZone, filters: context.filters };
+
+ // Period-less endpoints still carry the timezone and any filters, just no window.
+ const contextParams = context.time
+ ? toQueryParams(common)
+ : { time_zone: common.timeZone, filters: common.filters?.length ? common.filters : undefined };
+
+ return {
+ path: descriptor.path,
+ params: omitUndefined({ ...contextParams, ...descriptor.params }),
+ body: descriptor.body?.(common),
+ unwrap: descriptor.unwrap ?? true,
+ };
+}
+
+/**
+ * Issue an analytics request. Used by the query hooks and by the non-React
+ * callers (CSV export), so both go through the same seam.
+ */
+export async function fetchAnalytics<TData>(site: number | string, request: AnalyticsRequest): Promise<TData> {
+ const response = await authedFetch<TData | { data: TData }>(
+ `/sites/${site}/${request.path}`,
+ request.params,
+ request.body === undefined ? {} : { method: "POST", data: request.body }
+ );
+ return request.unwrap ? (response as { data: TData }).data : (response as TData);
+}
diff --git a/client/src/api/analytics/endpoints/bots.ts b/client/src/api/analytics/endpoints/bots.ts
index 066152d05..124947059 100644
--- a/client/src/api/analytics/endpoints/bots.ts
+++ b/client/src/api/analytics/endpoints/bots.ts
@@ -1,6 +1,5 @@
import { FilterParameter, TimeBucket } from "@rybbit/shared";
-import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+import { CommonApiParams, PaginationParams } from "./types";
export type BotLayerKey = "ua_pattern" | "header_heuristics" | "client_signals" | "bot_asn" | "rate_anomaly";
@@ -44,40 +43,3 @@ export interface PaginatedBotDimensionResponse {
data: BotDimensionItem[];
totalCount: number;
}
-
-export async function fetchBotOverview(
- site: string | number,
- params: BotOverviewParams
-): Promise<GetBotOverviewResponse> {
- const response = await authedFetch<{ data: GetBotOverviewResponse }>(`/sites/${site}/bots/overview`, {
- ...toQueryParams(params),
- layer: params.layer || undefined,
- });
- return response.data;
-}
-
-export async function fetchBotTimeSeries(
- site: string | number,
- params: BotTimeSeriesParams
-): Promise<GetBotTimeSeriesResponse> {
- const response = await authedFetch<{ data: GetBotTimeSeriesResponse }>(`/sites/${site}/bots/time-series`, {
- ...toQueryParams(params),
- bucket: params.bucket,
- layer: params.layer || undefined,
- });
- return response.data;
-}
-
-export async function fetchBotDimension(
- site: string | number,
- params: BotDimensionParams
-): Promise<PaginatedBotDimensionResponse> {
- const response = await authedFetch<{ data: PaginatedBotDimensionResponse }>(`/sites/${site}/bots/by-dimension`, {
- ...toQueryParams(params),
- dimension: params.dimension,
- limit: params.limit,
- page: params.page,
- layer: params.layer || undefined,
- });
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/dashboards.ts b/client/src/api/analytics/endpoints/dashboards.ts
index 403f0a9c7..d1df04505 100644
--- a/client/src/api/analytics/endpoints/dashboards.ts
+++ b/client/src/api/analytics/endpoints/dashboards.ts
@@ -1,7 +1,6 @@
import type { Dashboard, DashboardConfig, TimeBucket } from "@rybbit/shared";
import { authedFetch } from "../../utils";
import type { CommonApiParams } from "./types";
-import type { RunCustomQueryResponse } from "./customQuery";
export function fetchDashboards(site: string | number) {
return authedFetch<Dashboard[]>(`/sites/${site}/dashboards`);
@@ -39,13 +38,3 @@ export type RunDashboardCardBody = {
query: string;
bucket: TimeBucket;
} & CommonApiParams;
-
-export function runDashboardCard(site: string | number, body: RunDashboardCardBody) {
- // Body is sent as camelCase JSON (the server schema matches), so filters
- // (which aren't used by card execution) are stripped before sending.
- const { filters: _filters, ...rest } = body;
- return authedFetch<RunCustomQueryResponse>(`/sites/${site}/dashboards/run-card`, undefined, {
- method: "POST",
- data: rest,
- });
-}
diff --git a/client/src/api/analytics/endpoints/errors.ts b/client/src/api/analytics/endpoints/errors.ts
index d0e3c8608..76c824284 100644
--- a/client/src/api/analytics/endpoints/errors.ts
+++ b/client/src/api/analytics/endpoints/errors.ts
@@ -1,6 +1,5 @@
import { TimeBucket } from "@rybbit/shared";
-import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+import { CommonApiParams, PaginationParams } from "./types";
// Error Name Item type
export type ErrorNameItem = {
@@ -70,67 +69,3 @@ export interface ErrorBucketedParams extends CommonApiParams {
errorMessage: string;
bucket: TimeBucket;
}
-
-/**
- * Fetch error names with counts
- * GET /api/sites/:site/errors/names
- */
-export async function fetchErrorNames(
- site: string | number,
- params: ErrorNamesParams
-): Promise<ErrorNamesPaginatedResponse> {
- const queryParams = {
- ...toQueryParams(params),
- limit: params.limit,
- page: params.page,
- };
-
- const response = await authedFetch<{ data: ErrorNamesPaginatedResponse }>(
- `/sites/${site}/errors/names`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch individual error events
- * GET /api/sites/:site/errors/events
- */
-export async function fetchErrorEvents(
- site: string | number,
- params: ErrorEventsParams
-): Promise<ErrorEventsPaginatedResponse> {
- const queryParams = {
- ...toQueryParams(params),
- errorMessage: params.errorMessage,
- limit: params.limit,
- page: params.page,
- };
-
- const response = await authedFetch<{ data: ErrorEventsPaginatedResponse }>(
- `/sites/${site}/errors/events`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch error counts over time
- * GET /api/sites/:site/errors/time-series
- */
-export async function fetchErrorBucketed(
- site: string | number,
- params: ErrorBucketedParams
-): Promise<GetErrorBucketedResponse> {
- const queryParams = {
- ...toQueryParams(params),
- errorMessage: params.errorMessage,
- bucket: params.bucket,
- };
-
- const response = await authedFetch<{ data: GetErrorBucketedResponse }>(
- `/sites/${site}/errors/time-series`,
- queryParams
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/events.ts b/client/src/api/analytics/endpoints/events.ts
index 87c3ff045..f852b486a 100644
--- a/client/src/api/analytics/endpoints/events.ts
+++ b/client/src/api/analytics/endpoints/events.ts
@@ -1,11 +1,5 @@
-import { Filter } from "@rybbit/shared";
import { authedFetch } from "../../utils";
-import {
- BucketedParams,
- CommonApiParams,
- toBucketedQueryParams,
- toQueryParams,
-} from "./types";
+import { BucketedParams, CommonApiParams, toBucketedQueryParams } from "./types";
// Event type
export type Event = {
@@ -113,167 +107,6 @@ export interface EventPropertiesParams extends CommonApiParams {
eventName: string;
}
-/**
- * Poll for events newer than sinceTimestamp (Realtime mode).
- * Only sends filters β€” no time range.
- */
-export async function fetchNewEvents(
- site: string | number,
- params: { sinceTimestamp: string; filters?: Filter[]; timeZone: string }
-): Promise<NewEventsResponse> {
- const queryParams: Record<string, any> = {
- since_timestamp: params.sinceTimestamp,
- time_zone: params.timeZone,
- start_date: "",
- end_date: "",
- };
- if (params.filters?.length) {
- queryParams.filters = params.filters;
- }
-
- return authedFetch<NewEventsResponse>(
- `/sites/${site}/events`,
- queryParams
- );
-}
-
-/**
- * Cursor-based fetch for historical scrolling / initial load.
- */
-export async function fetchEventsCursor(
- site: string | number,
- params: CommonApiParams & {
- beforeTimestamp?: string;
- pageSize?: number;
- }
-): Promise<CursorEventsResponse> {
- const queryParams: Record<string, any> = {
- ...toQueryParams(params),
- page_size: params.pageSize ?? 50,
- };
-
- if (params.beforeTimestamp) {
- queryParams.before_timestamp = params.beforeTimestamp;
- }
-
- return authedFetch<CursorEventsResponse>(
- `/sites/${site}/events`,
- queryParams
- );
-}
-
-/**
- * Fetch event names
- * GET /api/events/names/:site
- */
-export async function fetchEventNames(
- site: string | number,
- params: CommonApiParams
-): Promise<EventName[]> {
- const response = await authedFetch<{ data: EventName[] }>(
- `/sites/${site}/events/names`,
- toQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch event properties for a specific event name
- * GET /api/events/properties/:site
- */
-export async function fetchEventProperties(
- site: string | number,
- params: EventPropertiesParams
-): Promise<EventProperty[]> {
- const queryParams = {
- ...toQueryParams(params),
- event_name: params.eventName,
- };
-
- const response = await authedFetch<{ data: EventProperty[] }>(
- `/sites/${site}/events/properties`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch outbound link clicks
- * GET /api/events/outbound/:site
- */
-export async function fetchOutboundLinks(
- site: string | number,
- params: CommonApiParams
-): Promise<OutboundLink[]> {
- const response = await authedFetch<{ data: OutboundLink[] }>(
- `/sites/${site}/events/outbound`,
- toQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch autocapture events of a type (button clicks, form submissions,
- * copies) grouped by display value, with counts and last occurrence
- * GET /api/sites/:site/events/autocapture
- */
-export async function fetchAutocaptureEvents(
- site: string | number,
- params: CommonApiParams & { type: string }
-): Promise<AutocaptureEvent[]> {
- const queryParams = {
- ...toQueryParams(params),
- type: params.type,
- };
-
- const response = await authedFetch<{ data: AutocaptureEvent[] }>(
- `/sites/${site}/events/autocapture`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch common values for an autocapture event type (outbound urls, button
- * texts, form names/ids, copied texts)
- * GET /api/sites/:site/events/autocapture-values
- */
-export async function fetchAutocaptureValues(
- site: string | number,
- params: CommonApiParams & { type: string }
-): Promise<AutocaptureValue[]> {
- const queryParams = {
- ...toQueryParams(params),
- type: params.type,
- };
-
- const response = await authedFetch<{ data: AutocaptureValue[] }>(
- `/sites/${site}/events/autocapture-values`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch bucketed event counts for top custom events
- * GET /api/sites/:site/events/time-series
- */
-export async function fetchEventBucketed(
- site: string | number,
- params: EventBucketedParams
-): Promise<EventBucketedPoint[]> {
- const queryParams = {
- ...toBucketedQueryParams(params),
- limit: params.limit,
- };
-
- const response = await authedFetch<{ data: EventBucketedPoint[] }>(
- `/sites/${site}/events/time-series`,
- queryParams
- );
- return response.data;
-}
-
/**
* Fetch site-level event count breakdown by type
* GET /sites/:site/events/count
diff --git a/client/src/api/analytics/endpoints/experiments.ts b/client/src/api/analytics/endpoints/experiments.ts
index 0e3143a87..a0ec40915 100644
--- a/client/src/api/analytics/endpoints/experiments.ts
+++ b/client/src/api/analytics/endpoints/experiments.ts
@@ -117,15 +117,3 @@ export async function deleteExperiment(site: string | number, experimentId: numb
method: "DELETE",
});
}
-
-export async function fetchExperimentResults(
- site: string | number,
- experimentId: number,
- params: CommonApiParams
-): Promise<ExperimentResults> {
- const response = await authedFetch<{ data: ExperimentResults }>(
- `/sites/${site}/experiments/${experimentId}/results`,
- toQueryParams(params)
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/funnels.ts b/client/src/api/analytics/endpoints/funnels.ts
index ed6b58379..2fadd5ed6 100644
--- a/client/src/api/analytics/endpoints/funnels.ts
+++ b/client/src/api/analytics/endpoints/funnels.ts
@@ -1,7 +1,6 @@
import type { AutocaptureTargetType } from "../../../lib/events";
import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
-import type { GetSessionsResponse } from "./sessions";
+import { CommonApiParams, PaginationParams } from "./types";
// Funnel step types: page paths, custom events, and autocaptured event types
export type FunnelStepType = "page" | "event" | AutocaptureTargetType;
@@ -82,69 +81,6 @@ export interface SaveFunnelParams {
reportId?: number;
}
-/**
- * Fetch all saved funnels
- * GET /api/funnels/:site
- */
-export async function fetchFunnels(
- site: string | number
-): Promise<SavedFunnel[]> {
- const response = await authedFetch<{ data: SavedFunnel[] }>(
- `/sites/${site}/funnels`
- );
- return response.data;
-}
-
-/**
- * Analyze a funnel configuration
- * POST /api/funnels/analyze/:site
- */
-export async function analyzeFunnel(
- site: string | number,
- params: AnalyzeFunnelParams
-): Promise<FunnelResponse[]> {
- const queryParams = toQueryParams(params);
-
- const response = await authedFetch<{ data: FunnelResponse[] }>(
- `/sites/${site}/funnels/analyze`,
- queryParams,
- {
- method: "POST",
- data: {
- steps: params.steps,
- name: params.name,
- },
- }
- );
- return response.data;
-}
-
-/**
- * Get sessions at a specific funnel step
- * POST /api/funnels/:stepNumber/sessions/:site
- */
-export async function fetchFunnelStepSessions(
- site: string | number,
- params: FunnelStepSessionsParams
-): Promise<{ data: GetSessionsResponse }> {
- const queryParams = {
- ...toQueryParams(params),
- mode: params.mode,
- page: params.page,
- limit: params.limit,
- };
-
- const response = await authedFetch<{ data: GetSessionsResponse }>(
- `/sites/${site}/funnels/${params.stepNumber}/sessions`,
- queryParams,
- {
- method: "POST",
- data: { steps: params.steps },
- }
- );
- return response;
-}
-
/**
* Create or update a saved funnel
* POST /api/funnels/:site
diff --git a/client/src/api/analytics/endpoints/goals.ts b/client/src/api/analytics/endpoints/goals.ts
index f6df823f1..4123ec6f7 100644
--- a/client/src/api/analytics/endpoints/goals.ts
+++ b/client/src/api/analytics/endpoints/goals.ts
@@ -1,14 +1,6 @@
import type { AutocaptureTargetType } from "../../../lib/events";
import { authedFetch } from "../../utils";
-import {
- BucketedParams,
- CommonApiParams,
- PaginationParams,
- SortParams,
- toBucketedQueryParams,
- toQueryParams,
-} from "./types";
-import type { GetSessionsResponse } from "./sessions";
+import { BucketedParams, CommonApiParams, PaginationParams, SortParams } from "./types";
// Goal types: page paths, custom events, and autocaptured event types
export type GoalType = "path" | "event" | AutocaptureTargetType;
@@ -87,61 +79,6 @@ export interface UpdateGoalParams extends CreateGoalParams {
siteId: number;
}
-/**
- * Fetch goals with pagination
- * GET /api/goals/:site
- */
-export async function fetchGoals(site: string | number, params: GoalsParams): Promise<GoalsResponse> {
- const queryParams = {
- ...toQueryParams(params),
- page: params.page,
- page_size: params.pageSize ?? params.limit,
- sort: params.sort,
- order: params.order,
- };
-
- const response = await authedFetch<GoalsResponse>(`/sites/${site}/goals`, queryParams);
- return response;
-}
-
-/**
- * Fetch bucketed conversion data for goals
- * GET /api/sites/:site/goals/time-series
- */
-export async function fetchGoalTimeSeries(
- site: string | number,
- params: GoalTimeSeriesParams
-): Promise<GoalTimeSeriesPoint[]> {
- const queryParams = {
- ...toBucketedQueryParams(params),
- goal_ids: params.goalIds,
- };
-
- const response = await authedFetch<{ data: GoalTimeSeriesPoint[] }>(`/sites/${site}/goals/time-series`, queryParams);
- return response.data;
-}
-
-/**
- * Fetch sessions that completed a goal
- * GET /api/goals/:goalId/sessions/:site
- */
-export async function fetchGoalSessions(
- site: string | number,
- params: GoalSessionsParams
-): Promise<{ data: GetSessionsResponse }> {
- const queryParams = {
- ...toQueryParams(params),
- page: params.page,
- limit: params.limit,
- };
-
- const response = await authedFetch<{ data: GetSessionsResponse }>(
- `/sites/${site}/goals/${params.goalId}/sessions`,
- queryParams
- );
- return response;
-}
-
/**
* Create a new goal
* POST /api/goals/:site
diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.ts
index 247f58248..1b7717fad 100644
--- a/client/src/api/analytics/endpoints/index.ts
+++ b/client/src/api/analytics/endpoints/index.ts
@@ -1,16 +1,7 @@
// Types
export * from "./types";
-// Overview endpoints
-export {
- fetchOverview,
- fetchOverviewBucketed,
- fetchMetric,
- fetchLiveUserCount,
- fetchOverviewLite,
- fetchOverviewBucketedLite,
- fetchMetricLite,
-} from "./overview";
+// Overview types
export type {
GetOverviewResponse,
GetOverviewBucketedResponse,
@@ -19,17 +10,7 @@ export type {
} from "./overview";
// Events endpoints
-export {
- fetchEventBucketed,
- fetchNewEvents,
- fetchEventsCursor,
- fetchEventNames,
- fetchEventProperties,
- fetchAutocaptureEvents,
- fetchAutocaptureValues,
- fetchOutboundLinks,
- fetchSiteEventCount,
-} from "./events";
+export { fetchSiteEventCount } from "./events";
export type {
Event,
EventBucketedPoint,
@@ -47,14 +28,7 @@ export type {
} from "./events";
// Dashboards endpoints
-export {
- fetchDashboards,
- fetchDashboard,
- createDashboard,
- updateDashboard,
- deleteDashboard,
- runDashboardCard,
-} from "./dashboards";
+export { fetchDashboards, fetchDashboard, createDashboard, updateDashboard, deleteDashboard } from "./dashboards";
export type { RunDashboardCardBody } from "./dashboards";
// Custom query endpoints
@@ -67,8 +41,7 @@ export type {
RunCustomQueryResponse,
} from "./customQuery";
-// Errors endpoints
-export { fetchErrorNames, fetchErrorEvents, fetchErrorBucketed } from "./errors";
+// Errors types
export type {
ErrorNameItem,
ErrorNamesPaginatedResponse,
@@ -83,7 +56,7 @@ export type {
} from "./errors";
// Goals endpoints
-export { fetchGoals, fetchGoalTimeSeries, fetchGoalSessions, createGoal, updateGoal, deleteGoal } from "./goals";
+export { createGoal, updateGoal, deleteGoal } from "./goals";
export type {
Goal,
GoalType,
@@ -114,13 +87,7 @@ export type {
} from "./featureFlags";
// Experiment endpoints
-export {
- createExperiment,
- deleteExperiment,
- fetchExperimentResults,
- fetchExperiments,
- updateExperiment,
-} from "./experiments";
+export { createExperiment, deleteExperiment, fetchExperiments, updateExperiment } from "./experiments";
export type {
Experiment,
ExperimentFeatureFlag,
@@ -133,15 +100,7 @@ export type {
} from "./experiments";
// Funnels endpoints
-export {
- fetchFunnels,
- analyzeFunnel,
- fetchFunnelStepSessions,
- saveFunnel,
- deleteFunnel,
- stepRequiresValue,
- hasIncompleteSteps,
-} from "./funnels";
+export { saveFunnel, deleteFunnel, stepRequiresValue, hasIncompleteSteps } from "./funnels";
export type {
SavedFunnel,
FunnelStep,
@@ -154,8 +113,7 @@ export type {
SaveFunnelParams,
} from "./funnels";
-// Performance endpoints
-export { fetchPerformanceOverview, fetchPerformanceTimeSeries, fetchPerformanceByDimension } from "./performance";
+// Performance types
export type {
GetPerformanceOverviewResponse,
GetPerformanceTimeSeriesResponse,
@@ -166,8 +124,7 @@ export type {
PaginatedPerformanceResponse,
} from "./performance";
-// Bots endpoints
-export { fetchBotDimension, fetchBotOverview, fetchBotTimeSeries } from "./bots";
+// Bots types
export type {
BotDimensionKey,
BotDimensionItem,
@@ -182,7 +139,7 @@ export type {
} from "./bots";
// Sessions endpoints
-export { fetchSessions, fetchSession, fetchSessionLocations } from "./sessions";
+export { fetchSessions } from "./sessions";
export type {
GetSessionsResponse,
SessionDetails,
@@ -195,14 +152,7 @@ export type {
} from "./sessions";
// Users endpoints
-export {
- fetchUsers,
- fetchUserSessionCount,
- fetchUserInfo,
- identifyUser,
- updateUserTraits,
- deleteUser,
-} from "./users";
+export { fetchUsers, identifyUser, updateUserTraits, deleteUser } from "./users";
export type {
UsersResponse,
UserInfo,
@@ -219,7 +169,7 @@ export type {
} from "./users";
// Misc endpoints (retention, journeys, page titles, org event count)
-export { fetchRetention, fetchJourneys, fetchPageTitles, fetchOrgEventCount } from "./misc";
+export { fetchOrgEventCount } from "./misc";
export type {
ProcessedRetentionData,
RetentionMode,
@@ -237,7 +187,7 @@ export type {
} from "./misc";
// Session Replay endpoints
-export { fetchSessionReplays, fetchSessionReplayEvents, deleteSessionReplay } from "./sessionReplay";
+export { deleteSessionReplay } from "./sessionReplay";
export type {
SessionReplayListItem,
SessionReplayListResponse,
@@ -247,8 +197,7 @@ export type {
SessionReplaysParams,
} from "./sessionReplay";
-// User Traits endpoints
-export { fetchUserTraitKeys, fetchUserTraitValues, fetchUserTraitValueUsers } from "./userTraits";
+// User Traits types
export type {
TraitKey,
TraitKeysResponse,
diff --git a/client/src/api/analytics/endpoints/misc.ts b/client/src/api/analytics/endpoints/misc.ts
index 53de5801b..e25fe9146 100644
--- a/client/src/api/analytics/endpoints/misc.ts
+++ b/client/src/api/analytics/endpoints/misc.ts
@@ -1,5 +1,5 @@
import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+import { CommonApiParams, PaginationParams } from "./types";
// Retention types
export interface ProcessedRetentionData {
@@ -70,48 +70,6 @@ export interface JourneysParams extends CommonApiParams {
stepFilters?: Record<number, string>;
}
-/**
- * Fetch retention cohort data
- * GET /api/retention/:site
- */
-export async function fetchRetention(
- site: string | number,
- params: RetentionParams = {}
-): Promise<ProcessedRetentionData> {
- const { mode = "week", range = 90 } = params;
-
- const response = await authedFetch<{ data: ProcessedRetentionData }>(
- `/sites/${site}/retention`,
- { mode, range }
- );
- return response.data;
-}
-
-/**
- * Fetch user journey paths
- * GET /api/journeys/:site
- */
-export async function fetchJourneys(
- site: string | number,
- params: JourneysParams
-): Promise<JourneysResponse> {
- const queryParams = {
- ...toQueryParams(params),
- steps: params.steps ?? 3,
- limit: params.limit ?? 100,
- stepFilters:
- params.stepFilters && Object.keys(params.stepFilters).length > 0
- ? JSON.stringify(params.stepFilters)
- : undefined,
- };
-
- const response = await authedFetch<JourneysResponse>(
- `/sites/${site}/journeys`,
- queryParams
- );
- return response;
-}
-
export interface PageTitlesParams extends CommonApiParams, PaginationParams {
useFilters?: boolean;
}
@@ -122,27 +80,6 @@ export interface OrgEventCountParams {
timeZone?: string;
}
-/**
- * Fetch page titles with pagination
- * GET /api/page-titles/:site
- */
-export async function fetchPageTitles(
- site: string | number,
- params: PageTitlesParams
-): Promise<PageTitlesPaginatedResponse> {
- const queryParams = {
- ...toQueryParams(params),
- limit: params.limit,
- page: params.page,
- };
-
- const response = await authedFetch<{ data: PageTitlesPaginatedResponse }>(
- `/sites/${site}/page-titles`,
- queryParams
- );
- return response.data;
-}
-
/**
* Fetch organization event count
* GET /api/org-event-count/:organizationId
diff --git a/client/src/api/analytics/endpoints/overview.ts b/client/src/api/analytics/endpoints/overview.ts
index e7a36600e..f6e0e3242 100644
--- a/client/src/api/analytics/endpoints/overview.ts
+++ b/client/src/api/analytics/endpoints/overview.ts
@@ -1,4 +1,3 @@
-import { authedFetch } from "../../utils";
import {
CommonApiParams,
BucketedParams,
@@ -46,106 +45,3 @@ export type MetricResponse = {
export interface LiveUserCountResponse {
count: number;
}
-
-/**
- * Fetch overview metrics for a site
- * GET /api/overview/:site
- */
-export async function fetchOverview(
- site: string | number,
- params: CommonApiParams
-): Promise<GetOverviewResponse> {
- const response = await authedFetch<{ data: GetOverviewResponse }>(
- `/sites/${site}/overview`,
- toQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch time-series overview data
- * GET /api/sites/:site/overview/time-series
- */
-export async function fetchOverviewBucketed(
- site: string | number,
- params: BucketedParams
-): Promise<GetOverviewBucketedResponse> {
- const response = await authedFetch<{ data: GetOverviewBucketedResponse }>(
- `/sites/${site}/overview/time-series`,
- toBucketedQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch dimensional metric data
- * GET /api/metric/:site
- */
-export async function fetchMetric(
- site: string | number,
- params: MetricParams
-): Promise<{ data: MetricResponse[]; totalCount: number }> {
- const response = await authedFetch<{
- data: { data: MetricResponse[]; totalCount: number };
- }>(`/sites/${site}/metric`, toMetricQueryParams(params));
- return response.data;
-}
-
-/**
- * Fetch live user count
- * GET /api/live-user-count/:site
- */
-export async function fetchLiveUserCount(
- site: string | number,
- minutes: number = 5
-): Promise<LiveUserCountResponse> {
- const response = await authedFetch<LiveUserCountResponse>(
- `/sites/${site}/live-user-count`,
- { minutes }
- );
- return response;
-}
-
-/**
- * Fetch lite overview (MV-backed, no filters).
- * GET /api/sites/:site/overview-lite
- */
-export async function fetchOverviewLite(
- site: string | number,
- params: CommonApiParams
-): Promise<GetOverviewResponse> {
- const response = await authedFetch<{ data: GetOverviewResponse }>(
- `/sites/${site}/overview-lite`,
- toQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch lite bucketed overview (MV-backed).
- * GET /api/sites/:site/overview-bucketed-lite
- */
-export async function fetchOverviewBucketedLite(
- site: string | number,
- params: BucketedParams
-): Promise<GetOverviewBucketedResponse> {
- const response = await authedFetch<{ data: GetOverviewBucketedResponse }>(
- `/sites/${site}/overview-bucketed-lite`,
- toBucketedQueryParams(params)
- );
- return response.data;
-}
-
-/**
- * Fetch lite metric (MV-backed). Supports pathname, country, and device type.
- * GET /api/sites/:site/metric-lite
- */
-export async function fetchMetricLite(
- site: string | number,
- params: MetricParams
-): Promise<{ data: MetricResponse[]; totalCount: number }> {
- const response = await authedFetch<{
- data: { data: MetricResponse[]; totalCount: number };
- }>(`/sites/${site}/metric-lite`, toMetricQueryParams(params));
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/performance.ts b/client/src/api/analytics/endpoints/performance.ts
index b22ae8ff2..b0dfd1245 100644
--- a/client/src/api/analytics/endpoints/performance.ts
+++ b/client/src/api/analytics/endpoints/performance.ts
@@ -1,6 +1,5 @@
import { TimeBucket } from "@rybbit/shared";
-import { authedFetch } from "../../utils";
-import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
+import { CommonApiParams, PaginationParams, SortParams } from "./types";
// Performance Overview Response
export type GetPerformanceOverviewResponse = {
@@ -97,68 +96,3 @@ export interface PaginatedPerformanceResponse {
data: PerformanceByDimensionItem[];
totalCount: number;
}
-
-/**
- * Fetch performance overview (Core Web Vitals)
- * GET /api/performance/overview/:site
- */
-export async function fetchPerformanceOverview(
- site: string | number,
- params: PerformanceOverviewParams
-): Promise<GetPerformanceOverviewResponse> {
- const queryParams = {
- ...toQueryParams(params),
- percentile: params.percentile,
- };
-
- const response = await authedFetch<{ data: GetPerformanceOverviewResponse }>(
- `/sites/${site}/performance/overview`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch performance time series data
- * GET /api/performance/time-series/:site
- */
-export async function fetchPerformanceTimeSeries(
- site: string | number,
- params: PerformanceTimeSeriesParams
-): Promise<GetPerformanceTimeSeriesResponse> {
- const queryParams = {
- ...toQueryParams(params),
- bucket: params.bucket,
- };
-
- const response = await authedFetch<{ data: GetPerformanceTimeSeriesResponse }>(
- `/sites/${site}/performance/time-series`,
- queryParams
- );
- return response.data;
-}
-
-/**
- * Fetch performance broken down by dimension
- * GET /api/performance/by-dimension/:site
- */
-export async function fetchPerformanceByDimension(
- site: string | number,
- params: PerformanceByDimensionParams
-): Promise<PaginatedPerformanceResponse> {
- const queryParams = {
- ...toQueryParams(params),
- dimension: params.dimension,
- limit: params.limit,
- page: params.page,
- sort_by: params.sortBy,
- sort_order: params.sortOrder,
- percentile: params.percentile,
- };
-
- const response = await authedFetch<{ data: PaginatedPerformanceResponse }>(
- `/sites/${site}/performance/by-dimension`,
- queryParams
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/sessionReplay.ts b/client/src/api/analytics/endpoints/sessionReplay.ts
index 7dc2446df..614dfabfe 100644
--- a/client/src/api/analytics/endpoints/sessionReplay.ts
+++ b/client/src/api/analytics/endpoints/sessionReplay.ts
@@ -1,5 +1,5 @@
import { authedFetch } from "../../utils";
-import { CommonApiParams, toQueryParams } from "./types";
+import { CommonApiParams } from "./types";
// Session replay list item type
export interface SessionReplayListItem {
@@ -83,37 +83,6 @@ export interface SessionReplaysParams extends CommonApiParams {
minDuration?: number;
}
-/**
- * Fetch session replays list
- * GET /api/session-replay/list/:site
- */
-export async function fetchSessionReplays(
- site: string | number,
- params: SessionReplaysParams
-): Promise<SessionReplayListResponse> {
- const queryParams = {
- ...toQueryParams(params),
- limit: params.limit,
- offset: params.offset,
- minDuration: params.minDuration,
- };
-
- const response = await authedFetch<SessionReplayListResponse>(`/sites/${site}/session-replay/list`, queryParams);
- return response;
-}
-
-/**
- * Fetch session replay events for a specific session
- * GET /api/session-replay/:sessionId/:site
- */
-export async function fetchSessionReplayEvents(
- site: string | number,
- sessionId: string
-): Promise<GetSessionReplayEventsResponse> {
- const response = await authedFetch<GetSessionReplayEventsResponse>(`/sites/${site}/session-replay/${sessionId}`);
- return response;
-}
-
/**
* Delete a session replay
* DELETE /api/session-replay/:sessionId/:site
diff --git a/client/src/api/analytics/endpoints/sessions.ts b/client/src/api/analytics/endpoints/sessions.ts
index fb8a5aaea..99c00d0b0 100644
--- a/client/src/api/analytics/endpoints/sessions.ts
+++ b/client/src/api/analytics/endpoints/sessions.ts
@@ -158,42 +158,3 @@ export async function fetchSessions(
);
return response;
}
-
-/**
- * Fetch details of a specific session
- * GET /api/sessions/:sessionId/:site
- */
-export async function fetchSession(
- site: string | number,
- params: SessionDetailsParams
-): Promise<{ data: SessionPageviewsAndEvents }> {
- const queryParams: Record<string, any> = {
- limit: params.limit,
- offset: params.offset,
- };
-
- if (params.minutes) {
- queryParams.minutes = params.minutes;
- }
-
- const response = await authedFetch<{ data: SessionPageviewsAndEvents }>(
- `/sites/${site}/sessions/${params.sessionId}`,
- queryParams
- );
- return response;
-}
-
-/**
- * Fetch session locations for map visualization
- * GET /api/sites/:site/sessions/locations
- */
-export async function fetchSessionLocations(
- site: string | number,
- params: CommonApiParams
-): Promise<LiveSessionLocation[]> {
- const response = await authedFetch<{ data: LiveSessionLocation[] }>(
- `/sites/${site}/sessions/locations`,
- toQueryParams(params)
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/endpoints/userTraits.ts b/client/src/api/analytics/endpoints/userTraits.ts
index b246d6a23..26a65dec0 100644
--- a/client/src/api/analytics/endpoints/userTraits.ts
+++ b/client/src/api/analytics/endpoints/userTraits.ts
@@ -1,5 +1,3 @@
-import { authedFetch } from "../../utils";
-
export interface TraitKey {
key: string;
userCount: number;
@@ -26,29 +24,6 @@ export interface TraitValuesParams {
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;
@@ -74,19 +49,3 @@ export interface TraitValueUsersParams {
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 df461438a..2713a1d2d 100644
--- a/client/src/api/analytics/endpoints/users.ts
+++ b/client/src/api/analytics/endpoints/users.ts
@@ -1,7 +1,6 @@
import { Filter } from "@rybbit/shared";
import { authedFetch } from "../../utils";
import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
-import type { GetSessionsResponse } from "./sessions";
// User response type
export type UsersResponse = {
@@ -153,38 +152,6 @@ export async function fetchUsers(site: string | number, params: UsersParams): Pr
return response;
}
-/**
- * Fetch session count per day for a user
- * GET /api/users/session-count/:site
- */
-export async function fetchUserSessionCount(
- site: string | number,
- params: UserSessionCountParams
-): Promise<{ data: UserSessionCountResponse[] }> {
- const response = await authedFetch<{ data: UserSessionCountResponse[] }>(`/sites/${site}/users/session-count`, {
- user_id: params.userId,
- time_zone: params.timeZone,
- filters: params.filters?.length ? params.filters : undefined,
- });
- return response;
-}
-
-/**
- * Fetch detailed user information, optionally scoped to a time range and filters
- * GET /api/users/:userId/:site
- */
-export async function fetchUserInfo(
- site: string | number,
- userId: string,
- params?: CommonApiParams
-): Promise<UserInfo> {
- const response = await authedFetch<{ data: UserInfo }>(
- `/sites/${site}/users/${encodeURIComponent(userId)}`,
- params ? toQueryParams(params) : undefined
- );
- return response.data;
-}
-
export interface IdentifyUserPayload {
anonymousId: string;
userId: string;
diff --git a/client/src/api/analytics/hooks/bots/useGetBotDimension.ts b/client/src/api/analytics/hooks/bots/useGetBotDimension.ts
index a042ff84c..7684ade7b 100644
--- a/client/src/api/analytics/hooks/bots/useGetBotDimension.ts
+++ b/client/src/api/analytics/hooks/bots/useGetBotDimension.ts
@@ -1,11 +1,6 @@
import { useBotsStore } from "../../../../app/[site]/bots/botsStore";
import { useStore } from "../../../../lib/store";
-import {
- type BotDimensionKey,
- type BotDimensionParams,
- fetchBotDimension,
- type PaginatedBotDimensionResponse,
-} from "../../endpoints";
+import { type BotDimensionKey, type PaginatedBotDimensionResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
import { BOT_AVAILABLE_FILTERS } from "./constants";
@@ -20,17 +15,17 @@ export function useGetBotDimension({
limit?: number;
page?: number;
}) {
- const { filters } = useStore();
+ const filters = useStore(state => state.filters);
const { selectedLayer } = useBotsStore();
const botFilters = filters.filter(filter => BOT_AVAILABLE_FILTERS.includes(filter.parameter));
- return useAnalyticsQuery<{ data: PaginatedBotDimensionResponse }, BotDimensionParams>({
+ return useAnalyticsQuery<PaginatedBotDimensionResponse>({
key: "bot-dimension",
+ path: "bots/by-dimension",
site,
// Only bot-relevant filters go on the wire; when none apply, send no filters.
useFilters: botFilters.length > 0,
customFilters: botFilters,
- extraParams: { dimension, limit, page, layer: selectedLayer },
- fetch: (site, params) => fetchBotDimension(site, params).then(data => ({ data })),
+ params: { dimension, limit, page, layer: selectedLayer || undefined },
});
}
diff --git a/client/src/api/analytics/hooks/bots/useGetBotOverview.ts b/client/src/api/analytics/hooks/bots/useGetBotOverview.ts
index 8ec71acff..45d9f0f6d 100644
--- a/client/src/api/analytics/hooks/bots/useGetBotOverview.ts
+++ b/client/src/api/analytics/hooks/bots/useGetBotOverview.ts
@@ -1,21 +1,21 @@
import { useBotsStore } from "../../../../app/[site]/bots/botsStore";
import { useStore } from "../../../../lib/store";
-import { type BotOverviewParams, fetchBotOverview, type GetBotOverviewResponse } from "../../endpoints";
+import { type GetBotOverviewResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
import { BOT_AVAILABLE_FILTERS } from "./constants";
export function useGetBotOverview({ site }: { site?: number | string }) {
- const { filters } = useStore();
+ const filters = useStore(state => state.filters);
const { selectedLayer } = useBotsStore();
const botFilters = filters.filter(filter => BOT_AVAILABLE_FILTERS.includes(filter.parameter));
- return useAnalyticsQuery<{ data: GetBotOverviewResponse }, BotOverviewParams>({
+ return useAnalyticsQuery<GetBotOverviewResponse>({
key: "bot-overview",
+ path: "bots/overview",
site,
// Only bot-relevant filters go on the wire; when none apply, send no filters.
useFilters: botFilters.length > 0,
customFilters: botFilters,
- extraParams: { layer: selectedLayer },
- fetch: (site, params) => fetchBotOverview(site, params).then(data => ({ data })),
+ params: { layer: selectedLayer || undefined },
});
}
diff --git a/client/src/api/analytics/hooks/bots/useGetBotTimeSeries.ts b/client/src/api/analytics/hooks/bots/useGetBotTimeSeries.ts
index 30c830f8b..823f9c341 100644
--- a/client/src/api/analytics/hooks/bots/useGetBotTimeSeries.ts
+++ b/client/src/api/analytics/hooks/bots/useGetBotTimeSeries.ts
@@ -2,8 +2,7 @@ import { TimeBucket } from "@rybbit/shared";
import { UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import { useBotsStore } from "../../../../app/[site]/bots/botsStore";
import { useStore } from "../../../../lib/store";
-import { APIResponse } from "../../../types";
-import { type BotTimeSeriesParams, fetchBotTimeSeries, GetBotTimeSeriesResponse } from "../../endpoints";
+import { GetBotTimeSeriesResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
import { BOT_AVAILABLE_FILTERS } from "./constants";
@@ -14,21 +13,21 @@ export function useGetBotTimeSeries({
}: {
site: number | string;
bucket?: TimeBucket;
- props?: Partial<UseQueryOptions<APIResponse<GetBotTimeSeriesResponse>>>;
-}): UseQueryResult<APIResponse<GetBotTimeSeriesResponse>> {
- const { filters, bucket: storeBucket } = useStore();
+ props?: Partial<UseQueryOptions<GetBotTimeSeriesResponse, Error>>;
+}): UseQueryResult<GetBotTimeSeriesResponse> {
+ const filters = useStore(state => state.filters);
+ const storeBucket = useStore(state => state.bucket);
const { selectedLayer } = useBotsStore();
- const bucketToUse = bucket || storeBucket;
const botFilters = filters.filter(filter => BOT_AVAILABLE_FILTERS.includes(filter.parameter));
- return useAnalyticsQuery<APIResponse<GetBotTimeSeriesResponse>, BotTimeSeriesParams>({
+ return useAnalyticsQuery<GetBotTimeSeriesResponse>({
key: "bot-time-series",
+ path: "bots/time-series",
site,
// Only bot-relevant filters go on the wire; when none apply, send no filters.
useFilters: botFilters.length > 0,
customFilters: botFilters,
- extraParams: { bucket: bucketToUse, layer: selectedLayer },
+ params: { bucket: bucket || storeBucket, layer: selectedLayer || undefined },
props,
- fetch: (site, params) => fetchBotTimeSeries(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts b/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
index 891d06b3d..6629f3e99 100644
--- a/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
@@ -1,6 +1,6 @@
import { useStore } from "@/lib/store";
import { UseQueryResult } from "@tanstack/react-query";
-import { ErrorBucketedParams, fetchErrorBucketed, GetErrorBucketedResponse } from "../../endpoints";
+import { GetErrorBucketedResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
type UseGetErrorBucketedOptions = {
@@ -10,13 +10,13 @@ type UseGetErrorBucketedOptions = {
export function useGetErrorBucketed({
errorMessage,
}: UseGetErrorBucketedOptions): UseQueryResult<GetErrorBucketedResponse> {
- const { bucket } = useStore();
+ const bucket = useStore(state => state.bucket);
- return useAnalyticsQuery<GetErrorBucketedResponse, ErrorBucketedParams>({
+ return useAnalyticsQuery<GetErrorBucketedResponse>({
key: "error-bucketed",
- extraParams: { errorMessage, bucket },
+ path: "errors/time-series",
+ params: { errorMessage, bucket },
enabled: !!errorMessage,
staleTime: Infinity,
- fetch: (site, params) => fetchErrorBucketed(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
index 4c4d49ed7..94a51f8fa 100644
--- a/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
@@ -1,33 +1,19 @@
-import { useStore } from "@/lib/store";
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { buildApiParams } from "../../../utils";
-import { ErrorEventsPaginatedResponse, fetchErrorEvents } from "../../endpoints";
+import { ErrorEventsPaginatedResponse } from "../../endpoints";
+import { useAnalyticsInfiniteQuery } from "../../useAnalyticsQuery";
+
+const PAGE_SIZE = 20;
// Hook for infinite scrolling
export function useGetErrorEventsInfinite(errorMessage: string, enabled: boolean = true) {
- const { time, site, filters, timezone } = useStore();
-
- return useInfiniteQuery({
- queryKey: ["error-events-infinite", time, site, filters, errorMessage, timezone],
- queryFn: async ({ pageParam = 1 }) => {
- const data = await fetchErrorEvents(site, {
- ...buildApiParams(time, { filters }),
- errorMessage,
- limit: 20,
- page: pageParam,
- });
- return { data };
- },
+ return useAnalyticsInfiniteQuery<ErrorEventsPaginatedResponse>({
+ key: "error-events-infinite",
+ path: "errors/events",
+ params: { errorMessage, limit: PAGE_SIZE },
initialPageParam: 1,
- getNextPageParam: (lastPage: { data: ErrorEventsPaginatedResponse }, allPages) => {
- const currentPage = allPages.length;
- const totalItems = lastPage?.data?.totalCount || 0;
- const itemsPerPage = 20;
- const totalPages = Math.ceil(totalItems / itemsPerPage);
-
- return currentPage < totalPages ? currentPage + 1 : undefined;
- },
- enabled: enabled && !!errorMessage && !!site,
+ pageParams: page => ({ page }),
+ getNextPageParam: (lastPage, allPages) =>
+ allPages.length < Math.ceil((lastPage?.totalCount || 0) / PAGE_SIZE) ? allPages.length + 1 : undefined,
+ enabled: enabled && !!errorMessage,
staleTime: Infinity,
});
}
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorNames.ts b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
index 6d0504afe..9344099cb 100644
--- a/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
@@ -1,5 +1,5 @@
import { UseQueryResult } from "@tanstack/react-query";
-import { ErrorNamesParams, ErrorNamesPaginatedResponse, fetchErrorNames } from "../../endpoints";
+import { ErrorNamesPaginatedResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
type UseGetErrorNamesOptions = {
@@ -13,13 +13,13 @@ export function useGetErrorNamesPaginated({
limit = 10,
page = 1,
useFilters = true,
-}: UseGetErrorNamesOptions): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
- return useAnalyticsQuery<{ data: ErrorNamesPaginatedResponse }, ErrorNamesParams>({
+}: UseGetErrorNamesOptions): UseQueryResult<ErrorNamesPaginatedResponse> {
+ return useAnalyticsQuery<ErrorNamesPaginatedResponse>({
key: "error-names",
+ path: "errors/names",
useFilters,
- extraParams: { limit, page },
+ params: { limit, page },
staleTime: Infinity,
- fetch: (site, params) => fetchErrorNames(site, params).then(data => ({ data })),
});
}
@@ -27,12 +27,12 @@ export function useGetErrorNamesPaginated({
export function useGetErrorNames({
limit = 10,
useFilters = true,
-}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
- return useAnalyticsQuery<{ data: ErrorNamesPaginatedResponse }, ErrorNamesParams>({
+}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<ErrorNamesPaginatedResponse> {
+ return useAnalyticsQuery<ErrorNamesPaginatedResponse>({
key: "error-names",
+ path: "errors/names",
useFilters,
- extraParams: { limit },
+ params: { limit },
staleTime: Infinity,
- fetch: (site, params) => fetchErrorNames(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/events/useAutocaptureValues.ts b/client/src/api/analytics/hooks/events/useAutocaptureValues.ts
index d8fb75cfc..5cbb106d3 100644
--- a/client/src/api/analytics/hooks/events/useAutocaptureValues.ts
+++ b/client/src/api/analytics/hooks/events/useAutocaptureValues.ts
@@ -1,21 +1,24 @@
-import { useQueries, useQuery } from "@tanstack/react-query";
+import { useQueries } from "@tanstack/react-query";
import { useMemo } from "react";
import { AUTOCAPTURE_TARGET_TYPES, AutocaptureTargetType } from "../../../../lib/events";
-import { useStore } from "../../../../lib/store";
-import { buildApiParams } from "../../../utils";
-import { AutocaptureValue, fetchAutocaptureValues } from "../../endpoints";
+import { buildAnalyticsRequest, fetchAnalytics } from "../../analyticsRequest";
+import { AutocaptureValue } from "../../endpoints";
+import { useAnalyticsContext, useAnalyticsQuery } from "../../useAnalyticsQuery";
+
+const DESCRIPTOR = (type: string) => ({ path: "events/autocapture-values", params: { type } });
// Suggestions for goal/funnel-step value patterns: the most common values of
// an autocapture type's primary props (urls, button texts, form names, ...)
export function useAutocaptureValues(type: string, enabled: boolean = true) {
- const { site, time, timezone } = useStore();
-
- const params = buildApiParams(time);
-
- return useQuery({
- queryKey: ["autocapture-values", site, type, time, timezone],
- enabled: enabled && !!site,
- queryFn: () => fetchAutocaptureValues(site, { ...params, type }),
+ return useAnalyticsQuery<AutocaptureValue[]>({
+ key: "autocapture-values",
+ ...DESCRIPTOR(type),
+ useFilters: false,
+ enabled,
+ // Suggestion lists were a plain useQuery before the seam: always refetch on
+ // mount, and never show the previous type's values while a new type loads.
+ staleTime: 0,
+ placeholder: false,
});
}
@@ -25,15 +28,17 @@ export function useAutocaptureValues(type: string, enabled: boolean = true) {
export function useAutocaptureValuesByType(
enabledTypes: ReadonlySet<AutocaptureTargetType>
): Record<AutocaptureTargetType, AutocaptureValue[] | undefined> {
- const { site, time, timezone } = useStore();
- const params = buildApiParams(time);
+ const { site, context } = useAnalyticsContext({ useFilters: false });
const results = useQueries({
- queries: AUTOCAPTURE_TARGET_TYPES.map(type => ({
- queryKey: ["autocapture-values", site, type, time, timezone],
- enabled: enabledTypes.has(type) && !!site,
- queryFn: () => fetchAutocaptureValues(site, { ...params, type }),
- })),
+ queries: AUTOCAPTURE_TARGET_TYPES.map(type => {
+ const request = buildAnalyticsRequest(DESCRIPTOR(type), context);
+ return {
+ queryKey: ["autocapture-values", site, request.path, request.params],
+ enabled: enabledTypes.has(type) && !!site,
+ queryFn: () => fetchAnalytics<AutocaptureValue[]>(site, request),
+ };
+ }),
});
// eslint-disable-next-line react-hooks/exhaustive-deps
diff --git a/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts b/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts
index 5ae8e4e79..112d28b6c 100644
--- a/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts
+++ b/client/src/api/analytics/hooks/events/useGetAutocaptureEvents.ts
@@ -1,19 +1,18 @@
import { AutocaptureTargetType } from "../../../../lib/events";
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters } from "../../../../lib/store";
-import { type AutocaptureEvent, fetchAutocaptureEvents } from "../../endpoints";
-import { CommonApiParams } from "../../endpoints/types";
+import { type AutocaptureEvent } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetAutocaptureEvents(type: AutocaptureTargetType) {
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- return useAnalyticsQuery<AutocaptureEvent[], CommonApiParams & { type: string }>({
+ return useAnalyticsQuery<AutocaptureEvent[]>({
key: "autocapture-events",
+ path: "events/autocapture",
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { type },
- fetch: (site, params) => fetchAutocaptureEvents(site, params),
+ params: { type },
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetEventBucketed.ts b/client/src/api/analytics/hooks/events/useGetEventBucketed.ts
index 10d30bd25..f6b119dae 100644
--- a/client/src/api/analytics/hooks/events/useGetEventBucketed.ts
+++ b/client/src/api/analytics/hooks/events/useGetEventBucketed.ts
@@ -1,18 +1,18 @@
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../../lib/store";
-import { type EventBucketedParams, type EventBucketedPoint, fetchEventBucketed } from "../../endpoints";
+import { type EventBucketedPoint } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetEventBucketed({ limit = 5 }: { limit?: number } = {}) {
- const { bucket } = useStore();
+ const bucket = useStore(state => state.bucket);
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- return useAnalyticsQuery<EventBucketedPoint[], EventBucketedParams>({
+ return useAnalyticsQuery<EventBucketedPoint[]>({
key: "event-bucketed",
+ path: "events/time-series",
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { bucket, limit },
- fetch: (site, params) => fetchEventBucketed(site, params),
+ params: { bucket, limit },
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetEventNames.ts b/client/src/api/analytics/hooks/events/useGetEventNames.ts
index 8c94eff5e..07804d3f8 100644
--- a/client/src/api/analytics/hooks/events/useGetEventNames.ts
+++ b/client/src/api/analytics/hooks/events/useGetEventNames.ts
@@ -1,16 +1,16 @@
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters } from "../../../../lib/store";
-import { fetchEventNames } from "../../endpoints";
+import { EventName } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetEventNames() {
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- return useAnalyticsQuery({
+ return useAnalyticsQuery<EventName[]>({
key: "event-names",
+ path: "events/names",
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- fetch: (site, params) => fetchEventNames(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetEventProperties.ts b/client/src/api/analytics/hooks/events/useGetEventProperties.ts
index 414c9fac1..7b42543b8 100644
--- a/client/src/api/analytics/hooks/events/useGetEventProperties.ts
+++ b/client/src/api/analytics/hooks/events/useGetEventProperties.ts
@@ -1,26 +1,22 @@
-import { useQuery } from "@tanstack/react-query";
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
-import { getFilteredFilters, getTimezone, useStore } from "../../../../lib/store";
-import { getStartAndEndDate } from "../../../utils";
-import { fetchEventProperties } from "../../endpoints";
+import { getFilteredFilters } from "../../../../lib/store";
+import { EventProperty } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetEventProperties(eventName: string | null) {
- const { site, time, timezone } = useStore();
-
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- const { startDate, endDate } = getStartAndEndDate(time);
- return useQuery({
- queryKey: ["event-properties", site, eventName, time, filteredFilters, timezone],
- enabled: !!site && !!eventName,
- queryFn: () => {
- return fetchEventProperties(site, {
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone: getTimezone(),
- filters: filteredFilters.length > 0 ? filteredFilters : undefined,
- eventName: eventName!,
- });
- },
+ return useAnalyticsQuery<EventProperty[]>({
+ key: "event-properties",
+ path: "events/properties",
+ // Only event-relevant filters go on the wire; when none apply, send no filters.
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: { event_name: eventName },
+ enabled: !!eventName,
+ // Keyed by event name: never show the previously selected event's
+ // properties while the new one loads.
+ staleTime: 0,
+ placeholder: false,
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetEvents.ts b/client/src/api/analytics/hooks/events/useGetEvents.ts
index 50d159781..0af25f1d0 100644
--- a/client/src/api/analytics/hooks/events/useGetEvents.ts
+++ b/client/src/api/analytics/hooks/events/useGetEvents.ts
@@ -1,33 +1,25 @@
-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { getTimezone, useStore } from "../../../../lib/store";
-import { buildApiParams } from "../../../utils";
-import {
- CursorEventsResponse,
- fetchEventsCursor,
- fetchNewEvents,
-} from "../../endpoints";
+import { useQuery } from "@tanstack/react-query";
+import { buildAnalyticsRequest, fetchAnalytics } from "../../analyticsRequest";
+import { CursorEventsResponse, NewEventsResponse } from "../../endpoints";
+import { useAnalyticsContext, useAnalyticsInfiniteQuery } from "../../useAnalyticsQuery";
/**
* Polls for new events since a given timestamp (Realtime mode).
* The sinceTimestamp is read from a callback at query time so the query key
* stays stable and doesn't cause refetch storms.
*/
-export function useNewEventsPoll(options: {
- getSinceTimestamp: () => string | null;
- enabled: boolean;
-}) {
- const { site, filters, timezone } = useStore();
- const tz = getTimezone();
+export function useNewEventsPoll(options: { getSinceTimestamp: () => string | null; enabled: boolean }) {
+ const { site, context } = useAnalyticsContext({ useTime: false });
+ const request = buildAnalyticsRequest({ path: "events", unwrap: false }, context);
return useQuery({
- queryKey: ["events-poll", site, filters, timezone],
+ queryKey: ["events-poll", site, request.params],
queryFn: () => {
const since = options.getSinceTimestamp();
- if (!since) return { data: [] };
- return fetchNewEvents(site, {
- sinceTimestamp: since,
- filters: filters?.length ? filters : undefined,
- timeZone: tz,
+ if (!since) return { data: [] } as NewEventsResponse;
+ return fetchAnalytics<NewEventsResponse>(site, {
+ ...request,
+ params: { ...request.params, since_timestamp: since },
});
},
refetchInterval: 2000,
@@ -40,49 +32,19 @@ export function useNewEventsPoll(options: {
* In Realtime mode: no time range, just filters.
* In Historical mode: uses global time + filters from store.
*/
-export function useGetEventsCursor(options: {
- isRealtime: boolean;
- pageSize?: number;
-}) {
- const { site, time, filters, timezone } = useStore();
+export function useGetEventsCursor(options: { isRealtime: boolean; pageSize?: number }) {
const pageSize = options.pageSize ?? 50;
- // In realtime mode we skip time params; in historical mode use global time
- const params = options.isRealtime
- ? {
- startDate: "",
- endDate: "",
- timeZone: getTimezone(),
- filters: filters?.length ? filters : undefined,
- }
- : buildApiParams(time, {
- filters: filters?.length ? filters : undefined,
- });
-
- return useInfiniteQuery<CursorEventsResponse, Error>({
- queryKey: [
- "events-cursor",
- site,
- options.isRealtime,
- options.isRealtime ? null : time,
- filters,
- pageSize,
- timezone,
- ],
- initialPageParam: null as string | null,
- queryFn: async ({ pageParam }) => {
- return fetchEventsCursor(site, {
- ...params,
- beforeTimestamp: (pageParam as string) ?? undefined,
- pageSize,
- });
- },
- getNextPageParam: (lastPage: CursorEventsResponse) => {
- if (lastPage.cursor?.hasMore && lastPage.cursor.oldestTimestamp) {
- return lastPage.cursor.oldestTimestamp;
- }
- return undefined;
- },
- enabled: !!site,
+ return useAnalyticsInfiniteQuery<CursorEventsResponse, string | null>({
+ key: "events-cursor",
+ path: "events",
+ unwrap: false,
+ useTime: !options.isRealtime,
+ params: { page_size: pageSize },
+ initialPageParam: null,
+ staleTime: 0,
+ pageParams: cursor => ({ before_timestamp: cursor ?? undefined }),
+ getNextPageParam: lastPage =>
+ lastPage.cursor?.hasMore && lastPage.cursor.oldestTimestamp ? lastPage.cursor.oldestTimestamp : undefined,
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts b/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts
index 3594a12f9..eb2e8da5e 100644
--- a/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts
+++ b/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts
@@ -1,16 +1,16 @@
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters } from "../../../../lib/store";
-import { fetchOutboundLinks } from "../../endpoints";
+import { OutboundLink } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetOutboundLinks() {
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- return useAnalyticsQuery({
+ return useAnalyticsQuery<OutboundLink[]>({
key: "outbound-links",
+ path: "events/outbound",
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- fetch: (site, params) => fetchOutboundLinks(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts b/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
index 264a75651..9048c2c1a 100644
--- a/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
+++ b/client/src/api/analytics/hooks/events/useGetSiteEventCount.ts
@@ -1,18 +1,18 @@
import { EVENT_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../../lib/store";
-import { fetchSiteEventCount, type SiteEventCountParams, type SiteEventCountPoint } from "../../endpoints";
+import { type SiteEventCountPoint } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetSiteEventCount() {
- const { bucket } = useStore();
+ const bucket = useStore(state => state.bucket);
const filteredFilters = getFilteredFilters(EVENT_FILTERS);
- return useAnalyticsQuery<SiteEventCountPoint[], SiteEventCountParams>({
+ return useAnalyticsQuery<SiteEventCountPoint[]>({
key: "site-event-count",
+ path: "events/count",
// Only event-relevant filters go on the wire; when none apply, send no filters.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { bucket },
- fetch: (site, params) => fetchSiteEventCount(site, params),
+ params: { bucket },
});
}
diff --git a/client/src/api/analytics/hooks/experiments/useExperiments.ts b/client/src/api/analytics/hooks/experiments/useExperiments.ts
index 84175c16e..2cd80fc60 100644
--- a/client/src/api/analytics/hooks/experiments/useExperiments.ts
+++ b/client/src/api/analytics/hooks/experiments/useExperiments.ts
@@ -3,14 +3,14 @@ import {
createExperiment,
deleteExperiment,
ExperimentPayload,
+ ExperimentResults,
ExperimentUpdatePayload,
- fetchExperimentResults,
fetchExperiments,
updateExperiment,
} from "../../endpoints";
-import { buildApiParams } from "../../../utils";
import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useExperiments() {
const { site } = useStore();
@@ -23,14 +23,17 @@ export function useExperiments() {
}
export function useExperimentResults(experimentId: number, enabled = true) {
- const { site, time, timezone } = useStore();
const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
- const params = buildApiParams(time, { filters: filteredFilters });
- return useQuery({
- queryKey: ["experiment-results", site, experimentId, time, filteredFilters, timezone],
- queryFn: () => fetchExperimentResults(site, experimentId, params),
- enabled: !!site && !!experimentId && enabled,
+ return useAnalyticsQuery<ExperimentResults>({
+ key: ["experiment-results", experimentId],
+ path: `experiments/${experimentId}/results`,
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ enabled: !!experimentId && enabled,
+ // Keyed by experiment: never show another experiment's results.
+ staleTime: 0,
+ placeholder: false,
});
}
@@ -55,7 +58,7 @@ export function useUpdateExperiment() {
updateExperiment(site, experimentId, payload),
onSuccess: (_data, variables) => {
queryClient.invalidateQueries({ queryKey: ["experiments", site] });
- queryClient.invalidateQueries({ queryKey: ["experiment-results", site, variables.experimentId] });
+ queryClient.invalidateQueries({ queryKey: ["experiment-results", variables.experimentId] });
},
});
}
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnel.ts b/client/src/api/analytics/hooks/funnels/useGetFunnel.ts
index 3f5143ee2..74e58310f 100644
--- a/client/src/api/analytics/hooks/funnels/useGetFunnel.ts
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnel.ts
@@ -2,14 +2,7 @@ import { useMutation, useQueryClient } from "@tanstack/react-query";
import { useDebounce } from "@uidotdev/usehooks";
import { FUNNEL_PAGE_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../../lib/store";
-import {
- analyzeFunnel,
- AnalyzeFunnelParams,
- FunnelRequest,
- FunnelResponse,
- saveFunnel,
- SaveFunnelRequest,
-} from "../../endpoints";
+import { FunnelRequest, FunnelResponse, saveFunnel, SaveFunnelRequest } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
/**
@@ -22,13 +15,13 @@ export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {
// filters at all (not the store's full filter list).
const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
- return useAnalyticsQuery<FunnelResponse[], AnalyzeFunnelParams>({
+ return useAnalyticsQuery<FunnelResponse[]>({
key: "funnel",
+ path: "funnels/analyze",
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { steps: configToUse?.steps ?? [], name: configToUse?.name },
+ body: () => ({ steps: configToUse?.steps ?? [], name: configToUse?.name }),
enabled: !!configToUse,
- fetch: (site, params) => analyzeFunnel(site, params),
});
}
@@ -36,7 +29,7 @@ export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {
* Hook for saving funnel configurations without analyzing them
*/
export function useSaveFunnel() {
- const { site } = useStore();
+ const site = useStore(state => state.site);
const queryClient = useQueryClient();
return useMutation<{ success: boolean; funnelId: number }, Error, SaveFunnelRequest>({
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
index e1fa0cef9..b037059a5 100644
--- a/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
@@ -1,12 +1,7 @@
import { Time } from "../../../../components/DateSelector/types";
import { FUNNEL_PAGE_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters } from "../../../../lib/store";
-import {
- fetchFunnelStepSessions,
- FunnelStep,
- FunnelStepSessionsParams,
- GetSessionsResponse,
-} from "../../endpoints";
+import { FunnelStep, GetSessionsResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetFunnelStepSessions({
@@ -32,14 +27,15 @@ export function useGetFunnelStepSessions({
// filters at all (not the store's full filter list).
const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
- return useAnalyticsQuery<{ data: GetSessionsResponse }, FunnelStepSessionsParams>({
- key: "funnel-step-sessions",
+ return useAnalyticsQuery<GetSessionsResponse>({
+ key: ["funnel-step-sessions", stepNumber],
+ path: `funnels/${stepNumber}/sessions`,
site: siteId,
overrideTime: time,
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { steps, stepNumber, mode, page, limit },
+ params: { mode, page, limit },
+ body: () => ({ steps }),
enabled: !!steps && steps.length >= 2 && enabled,
- fetch: (site, params) => fetchFunnelStepSessions(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnels.ts b/client/src/api/analytics/hooks/funnels/useGetFunnels.ts
index 714f2d547..90ece0760 100644
--- a/client/src/api/analytics/hooks/funnels/useGetFunnels.ts
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnels.ts
@@ -1,15 +1,15 @@
-import { useQuery } from "@tanstack/react-query";
-import { fetchFunnels, SavedFunnel } from "../../endpoints";
+import { SavedFunnel } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetFunnels(siteId?: string | number) {
- return useQuery<SavedFunnel[]>({
- queryKey: ["funnels", siteId],
- queryFn: async () => {
- if (!siteId) {
- return [];
- }
- return fetchFunnels(siteId);
- },
- enabled: !!siteId,
+ return useAnalyticsQuery<SavedFunnel[]>({
+ key: "funnels",
+ path: "funnels",
+ site: siteId,
+ // The saved funnel list is not scoped to the selected period.
+ useTime: false,
+ useFilters: false,
+ staleTime: 0,
+ placeholder: false,
});
}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts b/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts
index d96d23c5d..94c75d1c2 100644
--- a/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts
+++ b/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts
@@ -1,5 +1,5 @@
import { Time } from "../../../../components/DateSelector/types";
-import { fetchGoalSessions, GetSessionsResponse, GoalSessionsParams } from "../../endpoints";
+import { GetSessionsResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetGoalSessions({
@@ -17,13 +17,13 @@ export function useGetGoalSessions({
limit?: number;
enabled?: boolean;
}) {
- return useAnalyticsQuery<{ data: GetSessionsResponse }, GoalSessionsParams>({
- key: "goal-sessions",
+ return useAnalyticsQuery<GetSessionsResponse>({
+ key: ["goal-sessions", goalId],
+ path: `goals/${goalId}/sessions`,
site: siteId,
overrideTime: time,
useFilters: false,
- extraParams: { goalId, page, limit },
+ params: { page, limit },
enabled: !!goalId && enabled,
- fetch: (site, params) => fetchGoalSessions(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
index 2f8113d49..1fc9c6330 100644
--- a/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
+++ b/client/src/api/analytics/hooks/goals/useGetGoalTimeSeries.ts
@@ -1,22 +1,21 @@
import { TimeBucket } from "@rybbit/shared";
import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters, useStore } from "../../../../lib/store";
-import { fetchGoalTimeSeries, GoalTimeSeriesParams, GoalTimeSeriesPoint } from "../../endpoints";
+import { GoalTimeSeriesPoint } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetGoalTimeSeries({ goalIds, bucket }: { goalIds: number[]; bucket?: TimeBucket }) {
- const { bucket: storeBucket } = useStore();
- const bucketToUse = bucket || storeBucket;
+ const storeBucket = useStore(state => state.bucket);
// Only the goals page's filter parameters apply; an empty subset means no
// filters at all (not the store's full filter list).
const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
- return useAnalyticsQuery<GoalTimeSeriesPoint[], GoalTimeSeriesParams>({
+ return useAnalyticsQuery<GoalTimeSeriesPoint[]>({
key: "goal-time-series",
+ path: "goals/time-series",
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { bucket: bucketToUse, goalIds },
+ params: { bucket: bucket || storeBucket, goal_ids: goalIds },
enabled: goalIds.length > 0,
- fetch: (site, params) => fetchGoalTimeSeries(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoals.ts b/client/src/api/analytics/hooks/goals/useGetGoals.ts
index 2f521787f..db6947a22 100644
--- a/client/src/api/analytics/hooks/goals/useGetGoals.ts
+++ b/client/src/api/analytics/hooks/goals/useGetGoals.ts
@@ -1,6 +1,6 @@
import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
import { getFilteredFilters } from "../../../../lib/store";
-import { fetchGoals, GoalsParams, GoalsResponse } from "../../endpoints";
+import { GoalsResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetGoals({
@@ -18,11 +18,12 @@ export function useGetGoals({
// filters at all (not the store's full filter list).
const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
- return useAnalyticsQuery<GoalsResponse, GoalsParams>({
+ return useAnalyticsQuery<GoalsResponse>({
key: "goals",
+ path: "goals",
+ unwrap: false,
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { page, pageSize, sort, order },
- fetch: (site, params) => fetchGoals(site, params),
+ params: { page, page_size: pageSize, sort, order },
});
}
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
index 367ee4ad7..e5767f07c 100644
--- a/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
@@ -1,12 +1,7 @@
import { Filter } from "@rybbit/shared";
import { UseQueryResult } from "@tanstack/react-query";
import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
-import {
- fetchPerformanceByDimension,
- PaginatedPerformanceResponse,
- PerformanceByDimensionItem,
- PerformanceByDimensionParams,
-} from "../../endpoints";
+import { PaginatedPerformanceResponse, PerformanceByDimensionItem } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
// Keep the old type for backward compatibility
@@ -37,13 +32,20 @@ export function useGetPerformanceByDimension({
}: UseGetPerformanceByDimensionOptions): UseQueryResult<PaginatedPerformanceResponse> {
const { selectedPercentile } = usePerformanceStore();
- return useAnalyticsQuery<PaginatedPerformanceResponse, PerformanceByDimensionParams>({
+ return useAnalyticsQuery<PaginatedPerformanceResponse>({
key: "performance-by-dimension",
+ path: "performance/by-dimension",
site,
useFilters,
additionalFilters,
- extraParams: { dimension, limit, page, percentile: selectedPercentile, sortBy, sortOrder },
+ params: {
+ dimension,
+ limit,
+ page,
+ percentile: selectedPercentile,
+ sort_by: sortBy,
+ sort_order: sortOrder,
+ },
staleTime: Infinity,
- fetch: (site, params) => fetchPerformanceByDimension(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
index 85d100b0d..771baeb97 100644
--- a/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
@@ -1,5 +1,5 @@
import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
-import { fetchPerformanceOverview, GetPerformanceOverviewResponse, PerformanceOverviewParams } from "../../endpoints";
+import { GetPerformanceOverviewResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
@@ -7,12 +7,12 @@ type PeriodTime = "current" | "previous";
export function useGetPerformanceOverview({ periodTime, site }: { periodTime?: PeriodTime; site?: number | string }) {
const { selectedPercentile } = usePerformanceStore();
- return useAnalyticsQuery<{ data: GetPerformanceOverviewResponse }, PerformanceOverviewParams>({
+ return useAnalyticsQuery<GetPerformanceOverviewResponse>({
key: "performance-overview",
+ path: "performance/overview",
site,
periodTime,
- extraParams: { percentile: selectedPercentile },
+ params: { percentile: selectedPercentile },
staleTime: Infinity,
- fetch: (site, params) => fetchPerformanceOverview(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
index 70a716e0d..9988d1ef0 100644
--- a/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
@@ -1,12 +1,7 @@
import { Filter, TimeBucket } from "@rybbit/shared";
import { UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import { useStore } from "../../../../lib/store";
-import { APIResponse } from "../../../types";
-import {
- fetchPerformanceTimeSeries,
- GetPerformanceTimeSeriesResponse,
- PerformanceTimeSeriesParams,
-} from "../../endpoints";
+import { GetPerformanceTimeSeriesResponse } from "../../endpoints";
import { useAnalyticsQuery } from "../../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
@@ -22,19 +17,18 @@ export function useGetPerformanceTimeSeries({
site: number | string;
bucket?: TimeBucket;
dynamicFilters?: Filter[];
- props?: Partial<UseQueryOptions<APIResponse<GetPerformanceTimeSeriesResponse>>>;
-}): UseQueryResult<APIResponse<GetPerformanceTimeSeriesResponse>> {
- const { bucket: storeBucket } = useStore();
- const bucketToUse = bucket || storeBucket;
+ props?: Partial<UseQueryOptions<GetPerformanceTimeSeriesResponse, Error>>;
+}): UseQueryResult<GetPerformanceTimeSeriesResponse> {
+ const storeBucket = useStore(state => state.bucket);
- return useAnalyticsQuery<APIResponse<GetPerformanceTimeSeriesResponse>, PerformanceTimeSeriesParams>({
+ return useAnalyticsQuery<GetPerformanceTimeSeriesResponse>({
key: "performance-time-series",
+ path: "performance/time-series",
site,
periodTime,
additionalFilters: dynamicFilters,
- extraParams: { bucket: bucketToUse },
+ params: { bucket: bucket || storeBucket },
staleTime: Infinity,
props,
- fetch: (site, params) => fetchPerformanceTimeSeries(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts
index e11c5bbc8..f0c5e9e0e 100644
--- a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts
+++ b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts
@@ -1,11 +1,17 @@
-import { useQuery } from "@tanstack/react-query";
-import { fetchSessionReplayEvents } from "../../endpoints";
+import { GetSessionReplayEventsResponse } from "../../endpoints";
+import { useAnalyticsQuery } from "../../useAnalyticsQuery";
export function useGetSessionReplayEvents(siteId: number, sessionId: string) {
- return useQuery({
- queryKey: ["session-replay-events", siteId, sessionId],
- queryFn: () => fetchSessionReplayEvents(siteId, sessionId),
- enabled: !!siteId && !!sessionId,
+ return useAnalyticsQuery<GetSessionReplayEventsResponse>({
+ key: ["session-replay-events", sessionId],
+ path: `session-replay/${sessionId}`,
+ unwrap: false,
+ site: siteId,
+ useTime: false,
+ useFilters: false,
+ enabled: !!sessionId,
+ // Keyed by session: never play the previous replay's events.
+ placeholder: false,
staleTime: 1000 * 60 * 10, // 10 minutes
});
}
diff --git a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts
index 1560e2cfe..e904a096f 100644
--- a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts
+++ b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts
@@ -1,7 +1,5 @@
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { useStore } from "../../../../lib/store";
-import { buildApiParams } from "../../../utils";
-import { fetchSessionReplays } from "../../endpoints";
+import { SessionReplayListResponse } from "../../endpoints";
+import { useAnalyticsInfiniteQuery } from "../../useAnalyticsQuery";
type UseGetSessionReplaysOptions = {
limit?: number;
@@ -9,26 +7,16 @@ type UseGetSessionReplaysOptions = {
};
export function useGetSessionReplays({ limit = 20, minDuration = 30 }: UseGetSessionReplaysOptions = {}) {
- const { time, site, filters, timezone } = useStore();
- const params = buildApiParams(time, { filters });
-
- return useInfiniteQuery({
- queryKey: ["session-replays", site, time, filters, limit, minDuration, timezone],
- queryFn: async ({ pageParam = 0 }) => {
- return fetchSessionReplays(site, {
- ...params,
- limit,
- offset: pageParam,
- minDuration,
- });
- },
+ return useAnalyticsInfiniteQuery<SessionReplayListResponse>({
+ key: "session-replays",
+ path: "session-replay/list",
+ unwrap: false,
+ params: { limit, minDuration },
initialPageParam: 0,
- getNextPageParam: (lastPage, allPages) => {
- const totalFetched = allPages.reduce((acc, page) => acc + (page.data?.length || 0), 0);
- return lastPage.data?.length === limit ? totalFetched : undefined;
- },
+ pageParams: offset => ({ offset }),
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.data?.length === limit ? allPages.reduce((total, page) => total + (page.data?.length || 0), 0) : undefined,
staleTime: 1000 * 60 * 5, // 5 minutes
refetchOnWindowFocus: false,
- enabled: !!site,
});
}
diff --git a/client/src/api/analytics/hooks/useDashboardCard.ts b/client/src/api/analytics/hooks/useDashboardCard.ts
index 2b7101c17..7b2262b82 100644
--- a/client/src/api/analytics/hooks/useDashboardCard.ts
+++ b/client/src/api/analytics/hooks/useDashboardCard.ts
@@ -1,6 +1,5 @@
import { useStore } from "../../../lib/store";
import { RunCustomQueryResponse } from "../endpoints/customQuery";
-import { runDashboardCard, RunDashboardCardBody } from "../endpoints/dashboards";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
/**
@@ -11,21 +10,19 @@ import { useAnalyticsQuery } from "../useAnalyticsQuery";
* changes. Pass the (possibly unsaved) SQL directly so the card editor preview
* can reuse the same hook.
*/
-export function useDashboardCard(
- siteId: string | number | undefined,
- cardId: string,
- sql: string,
- enabled = true
-) {
+export function useDashboardCard(siteId: string | number | undefined, cardId: string, sql: string, enabled = true) {
const bucket = useStore(state => state.bucket);
- return useAnalyticsQuery<RunCustomQueryResponse, RunDashboardCardBody>({
+ return useAnalyticsQuery<RunCustomQueryResponse>({
key: ["dashboard-card", cardId],
+ path: "dashboards/run-card",
+ unwrap: false,
site: siteId,
useFilters: false,
- extraParams: { query: sql, bucket },
+ // The window is sent as camelCase JSON in the body (the server schema
+ // matches); filters aren't used by card execution.
+ body: ({ filters: _filters, ...window }) => ({ ...window, query: sql, bucket }),
enabled: enabled && !!siteId && !!sql.trim(),
props: { retry: false },
- fetch: (site, params) => runDashboardCard(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/useGetJourneys.ts b/client/src/api/analytics/hooks/useGetJourneys.ts
index b14e834e4..cdee30238 100644
--- a/client/src/api/analytics/hooks/useGetJourneys.ts
+++ b/client/src/api/analytics/hooks/useGetJourneys.ts
@@ -2,7 +2,7 @@ import { Filter } from "@rybbit/shared";
import { Time } from "../../../components/DateSelector/types";
import { JOURNEY_PAGE_FILTERS } from "../../../lib/filterGroups";
import { getFilteredFilters } from "../../../lib/store";
-import { fetchJourneys, JourneysParams as JourneysApiParams, JourneysResponse } from "../endpoints";
+import { JourneysResponse } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
export interface JourneyParams {
@@ -20,16 +20,21 @@ export const useJourneys = ({ siteId, steps = 3, time, limit = 100, stepFilters,
const filteredFilters = getFilteredFilters(JOURNEY_PAGE_FILTERS);
const combinedFilters = additionalFilters?.length ? [...filteredFilters, ...additionalFilters] : filteredFilters;
- return useAnalyticsQuery<JourneysResponse, JourneysApiParams>({
+ return useAnalyticsQuery<JourneysResponse>({
key: "journeys",
+ path: "journeys",
+ unwrap: false,
site: siteId,
overrideTime: time,
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so an empty page-filter set stays unfiltered.
useFilters: combinedFilters.length > 0,
customFilters: combinedFilters,
- extraParams: { steps, limit, stepFilters },
+ params: {
+ steps,
+ limit,
+ stepFilters: stepFilters && Object.keys(stepFilters).length > 0 ? JSON.stringify(stepFilters) : undefined,
+ },
enabled: siteId !== undefined,
- fetch: (site, params) => fetchJourneys(site, params),
});
};
diff --git a/client/src/api/analytics/hooks/useGetLiveUserCount.ts b/client/src/api/analytics/hooks/useGetLiveUserCount.ts
index 4ed6bc25f..a256b53f5 100644
--- a/client/src/api/analytics/hooks/useGetLiveUserCount.ts
+++ b/client/src/api/analytics/hooks/useGetLiveUserCount.ts
@@ -1,13 +1,16 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { fetchLiveUserCount, LiveUserCountResponse } from "../endpoints";
+import { LiveUserCountResponse } from "../endpoints";
+import { useAnalyticsQuery } from "../useAnalyticsQuery";
export function useGetLiveUserCount(minutes = 5) {
- const { site } = useStore();
- return useQuery<LiveUserCountResponse>({
- queryKey: ["live-user-count", site, minutes],
+ return useAnalyticsQuery<LiveUserCountResponse>({
+ key: "live-user-count",
+ path: "live-user-count",
+ unwrap: false,
+ useTime: false,
+ useFilters: false,
+ params: { minutes },
refetchInterval: 10000,
- queryFn: () => fetchLiveUserCount(site, minutes),
- enabled: !!site,
+ staleTime: 0,
+ placeholder: false,
});
}
diff --git a/client/src/api/analytics/hooks/useGetMetric.ts b/client/src/api/analytics/hooks/useGetMetric.ts
index 702e98d54..53cd61c35 100644
--- a/client/src/api/analytics/hooks/useGetMetric.ts
+++ b/client/src/api/analytics/hooks/useGetMetric.ts
@@ -1,13 +1,20 @@
import { Filter, FilterParameter } from "@rybbit/shared";
import { InfiniteData, UseInfiniteQueryResult, UseQueryResult } from "@tanstack/react-query";
import { Time } from "../../../components/DateSelector/types";
-import { APIResponse } from "../../types";
-import { fetchMetric, fetchMetricLite, MetricResponse } from "../endpoints";
-import { MetricParams } from "../endpoints/types";
-import { useAnalyticsQuery, useAnalyticsInfiniteQuery } from "../useAnalyticsQuery";
+import { MetricResponse } from "../endpoints";
+import { nextPageByTotalCount, useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
+type PaginatedResponse = {
+ data: MetricResponse[];
+ totalCount: number;
+};
+
+// Lite endpoints forward filters too β€” the server falls back to raw events
+// when a filter is active. `lite` only selects the endpoint, not the filters.
+const metricPath = (lite: boolean) => (lite ? "metric-lite" : "metric");
+
export function useMetric({
parameter,
limit = 1000,
@@ -18,22 +25,17 @@ export function useMetric({
limit?: number;
periodTime?: PeriodTime;
useFilters?: boolean;
-}): UseQueryResult<APIResponse<MetricResponse[]>> {
- return useAnalyticsQuery<APIResponse<MetricResponse[]>, MetricParams>({
+}): UseQueryResult<PaginatedResponse> {
+ return useAnalyticsQuery<PaginatedResponse>({
key: parameter,
+ path: metricPath(false),
periodTime,
doublePastMinutesForPrevious: true,
useFilters,
- extraParams: { parameter, limit },
- fetch: (site, params) => fetchMetric(site, params).then(result => ({ data: result.data })),
+ params: { parameter, limit },
});
}
-type PaginatedResponse = {
- data: MetricResponse[];
- totalCount: number;
-};
-
export function usePaginatedMetric({
parameter,
limit = 10,
@@ -54,17 +56,14 @@ export function usePaginatedMetric({
customTime?: Time;
lite?: boolean;
}): UseQueryResult<PaginatedResponse> {
- // Lite endpoints forward filters too β€” the server falls back to raw events
- // when a filter is active. `lite` only selects the fetcher, not the filters.
- return useAnalyticsQuery<PaginatedResponse, MetricParams>({
+ return useAnalyticsQuery<PaginatedResponse>({
key: parameter,
+ path: metricPath(lite),
overrideTime: customTime,
useFilters,
additionalFilters,
customFilters,
- extraParams: { parameter, limit, page },
- keyExtras: [lite],
- fetch: (site, params) => (lite ? fetchMetricLite : fetchMetric)(site, params),
+ params: { parameter, limit, page },
});
}
@@ -85,16 +84,16 @@ export function useInfiniteMetric({
customTime?: Time;
lite?: boolean;
}): UseInfiniteQueryResult<InfiniteData<PaginatedResponse>> {
- // Lite endpoints forward filters too β€” the server falls back to raw events
- // when a filter is active. `lite` only selects the fetcher, not the filters.
- return useAnalyticsInfiniteQuery<PaginatedResponse, MetricParams>({
+ return useAnalyticsInfiniteQuery<PaginatedResponse>({
key: parameter,
+ path: metricPath(lite),
overrideTime: customTime,
useFilters,
additionalFilters,
customFilters,
- extraParams: { parameter, limit },
- keyExtras: [lite],
- fetchPage: (site, params, page) => (lite ? fetchMetricLite : fetchMetric)(site, { ...params, page }),
+ params: { parameter, limit },
+ initialPageParam: 1,
+ pageParams: page => ({ page }),
+ getNextPageParam: nextPageByTotalCount,
});
}
diff --git a/client/src/api/analytics/hooks/useGetOverview.ts b/client/src/api/analytics/hooks/useGetOverview.ts
index df31aeccb..27c300ca2 100644
--- a/client/src/api/analytics/hooks/useGetOverview.ts
+++ b/client/src/api/analytics/hooks/useGetOverview.ts
@@ -1,5 +1,5 @@
import { Time } from "../../../components/DateSelector/types";
-import { fetchOverview, fetchOverviewLite } from "../endpoints";
+import { GetOverviewResponse } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
@@ -13,14 +13,19 @@ type UseGetOverviewOptions = {
lite?: boolean;
};
-export function useGetOverview({ periodTime, site, overrideTime, useFilters = true, lite = false }: UseGetOverviewOptions) {
- return useAnalyticsQuery({
+export function useGetOverview({
+ periodTime,
+ site,
+ overrideTime,
+ useFilters = true,
+ lite = false,
+}: UseGetOverviewOptions) {
+ return useAnalyticsQuery<GetOverviewResponse>({
key: "overview",
+ path: lite ? "overview-lite" : "overview",
site,
periodTime,
overrideTime,
useFilters,
- keyExtras: [lite],
- fetch: (site, params) => (lite ? fetchOverviewLite : fetchOverview)(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/useGetOverviewBucketed.ts b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
index 7b3fd5eea..efd88a4d4 100644
--- a/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
@@ -1,9 +1,7 @@
import { Filter, TimeBucket } from "@rybbit/shared";
import { UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
import { Time } from "../../../components/DateSelector/types";
-import { APIResponse } from "../../types";
-import { fetchOverviewBucketed, fetchOverviewBucketedLite, GetOverviewBucketedResponse } from "../endpoints";
-import { BucketedParams } from "../endpoints/types";
+import { GetOverviewBucketedResponse } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
@@ -25,22 +23,21 @@ export function useGetOverviewBucketed({
dynamicFilters?: Filter[];
refetchInterval?: number;
overrideTime?: Time;
- props?: Partial<UseQueryOptions<APIResponse<GetOverviewBucketedResponse>, Error>>;
+ props?: Partial<UseQueryOptions<GetOverviewBucketedResponse, Error>>;
useFilters?: boolean;
// Read the MV-backed lite endpoint instead of the raw-events one.
lite?: boolean;
-}): UseQueryResult<APIResponse<GetOverviewBucketedResponse>> {
- return useAnalyticsQuery<APIResponse<GetOverviewBucketedResponse>, BucketedParams>({
+}): UseQueryResult<GetOverviewBucketedResponse> {
+ return useAnalyticsQuery<GetOverviewBucketedResponse>({
key: "overview-bucketed",
+ path: lite ? "overview-bucketed-lite" : "overview/time-series",
site,
periodTime,
overrideTime,
useFilters,
additionalFilters: dynamicFilters,
- extraParams: { bucket },
- keyExtras: [lite],
+ params: { bucket },
refetchInterval,
props,
- fetch: (site, params) => (lite ? fetchOverviewBucketedLite : fetchOverviewBucketed)(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/useGetPageTitles.ts b/client/src/api/analytics/hooks/useGetPageTitles.ts
index 289d02b78..2ce7fd9bc 100644
--- a/client/src/api/analytics/hooks/useGetPageTitles.ts
+++ b/client/src/api/analytics/hooks/useGetPageTitles.ts
@@ -1,5 +1,5 @@
import { UseQueryResult } from "@tanstack/react-query";
-import { fetchPageTitles, PageTitlesParams, PageTitlesPaginatedResponse } from "../endpoints";
+import { PageTitlesPaginatedResponse } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
type PeriodTime = "current" | "previous";
@@ -17,13 +17,13 @@ export function useGetPageTitlesPaginated({
page = 1,
useFilters = true,
periodTime = "current",
-}: UseGetPageTitlesOptions): UseQueryResult<{ data: PageTitlesPaginatedResponse }> {
- return useAnalyticsQuery<{ data: PageTitlesPaginatedResponse }, PageTitlesParams>({
+}: UseGetPageTitlesOptions): UseQueryResult<PageTitlesPaginatedResponse> {
+ return useAnalyticsQuery<PageTitlesPaginatedResponse>({
key: "page-titles",
+ path: "page-titles",
periodTime,
useFilters,
- extraParams: { limit, page },
+ params: { limit, page },
staleTime: Infinity,
- fetch: (site, params) => fetchPageTitles(site, params).then(data => ({ data })),
});
}
diff --git a/client/src/api/analytics/hooks/useGetRetention.ts b/client/src/api/analytics/hooks/useGetRetention.ts
index cab01b0d3..a0f1c1fff 100644
--- a/client/src/api/analytics/hooks/useGetRetention.ts
+++ b/client/src/api/analytics/hooks/useGetRetention.ts
@@ -1,12 +1,17 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { fetchRetention, ProcessedRetentionData, RetentionMode } from "../endpoints";
+import { ProcessedRetentionData, RetentionMode } from "../endpoints";
+import { useAnalyticsQuery } from "../useAnalyticsQuery";
export function useGetRetention(mode: RetentionMode = "week", range: number = 90) {
- const { site } = useStore();
- return useQuery<ProcessedRetentionData>({
- queryKey: ["retention", site, mode, range],
- queryFn: () => fetchRetention(site, { mode, range }),
- enabled: !!site,
+ return useAnalyticsQuery<ProcessedRetentionData>({
+ key: "retention",
+ path: "retention",
+ // Retention spans its own cohort range, not the selected period.
+ useTime: false,
+ useFilters: false,
+ params: { mode, range },
+ // Keyed by mode/range: refetch on mount and don't show the previous
+ // cohort grid while the new one loads.
+ staleTime: 0,
+ placeholder: false,
});
}
diff --git a/client/src/api/analytics/hooks/useGetSessionLocations.ts b/client/src/api/analytics/hooks/useGetSessionLocations.ts
index 2c09b0b93..3a65d0611 100644
--- a/client/src/api/analytics/hooks/useGetSessionLocations.ts
+++ b/client/src/api/analytics/hooks/useGetSessionLocations.ts
@@ -1,9 +1,9 @@
import { useStore } from "../../../lib/store";
-import { fetchSessionLocations, LiveSessionLocation } from "../endpoints";
+import { LiveSessionLocation } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
export function useGetSessionLocations() {
- const { filters } = useStore();
+ const filters = useStore(state => state.filters);
// Filter out location-related filters to avoid circular dependencies
const locationExcludedFilters = filters.filter(
@@ -17,10 +17,10 @@ export function useGetSessionLocations() {
return useAnalyticsQuery<LiveSessionLocation[]>({
key: "session-locations",
+ path: "sessions/locations",
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so the excluded location filters stay excluded.
useFilters: locationExcludedFilters.length > 0,
customFilters: locationExcludedFilters,
- fetch: (site, params) => fetchSessionLocations(site, params),
});
}
diff --git a/client/src/api/analytics/hooks/useGetSiteEventCount.ts b/client/src/api/analytics/hooks/useGetSiteEventCountRange.ts
similarity index 54%
rename from client/src/api/analytics/hooks/useGetSiteEventCount.ts
rename to client/src/api/analytics/hooks/useGetSiteEventCountRange.ts
index c9c89d885..375a400a7 100644
--- a/client/src/api/analytics/hooks/useGetSiteEventCount.ts
+++ b/client/src/api/analytics/hooks/useGetSiteEventCountRange.ts
@@ -1,7 +1,14 @@
import { useQuery } from "@tanstack/react-query";
import { fetchSiteEventCount } from "../endpoints";
-export function useGetSiteEventCount({
+/**
+ * Site event counts over an explicit date range, for the settings usage chart.
+ *
+ * Distinct from the dashboard's `useGetSiteEventCount`, which reads the global
+ * analytics context: this one is driven by the period picker in Site Settings
+ * and must not react to the dashboard's time range or filters.
+ */
+export function useGetSiteEventCountRange({
siteId,
startDate,
endDate,
@@ -13,7 +20,7 @@ export function useGetSiteEventCount({
timeZone?: string;
}) {
return useQuery({
- queryKey: ["site-event-count", siteId, startDate, endDate, timeZone],
+ queryKey: ["site-event-count-range", siteId, startDate, endDate, timeZone],
queryFn: () =>
fetchSiteEventCount(siteId!, {
startDate: startDate ?? "",
diff --git a/client/src/api/analytics/hooks/useGetUserSessions.ts b/client/src/api/analytics/hooks/useGetUserSessions.ts
index 5b88d7eb9..8d85d63fa 100644
--- a/client/src/api/analytics/hooks/useGetUserSessions.ts
+++ b/client/src/api/analytics/hooks/useGetUserSessions.ts
@@ -1,18 +1,8 @@
-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { SESSION_PAGE_FILTERS, USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters, getTimezone, useStore } from "../../../lib/store";
-import { buildApiParams } from "../../utils";
-import {
- fetchSession,
- fetchSessions,
- fetchUserSessionCount,
- GetSessionsResponse,
- SessionPageviewsAndEvents,
- SessionsParams,
- UserSessionCountResponse,
-} from "../endpoints";
import { Time } from "../../../components/DateSelector/types";
-import { useAnalyticsQuery } from "../useAnalyticsQuery";
+import { SESSION_PAGE_FILTERS, USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../lib/store";
+import { GetSessionsResponse, SessionPageviewsAndEvents, UserSessionCountResponse } from "../endpoints";
+import { useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
export function useGetSessions({
userId,
@@ -35,16 +25,24 @@ export function useGetSessions({
}) {
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
- return useAnalyticsQuery<{ data: GetSessionsResponse }, SessionsParams>({
+ return useAnalyticsQuery<GetSessionsResponse>({
key: "sessions",
+ path: "sessions",
overrideTime: timeOverride,
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so an empty page-filter set stays unfiltered.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: { page, limit, userId, identifiedOnly, minPageviews, minEvents, minDuration },
+ params: {
+ page,
+ limit,
+ user_id: userId,
+ identified_only: identifiedOnly,
+ min_pageviews: minPageviews,
+ min_events: minEvents,
+ min_duration: minDuration,
+ },
staleTime: Infinity,
- fetch: (site, params) => fetchSessions(site, params),
});
}
@@ -59,93 +57,63 @@ export function useGetSessionsInfinite({
limit?: number;
refetchInterval?: number;
}) {
- const { time, site, timezone } = useStore();
-
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
- // When filtering by userId, we fetch all sessions for that user (no time filter)
- // Otherwise use buildApiParams which handles past-minutes mode
- const params = userId
- ? { startDate: "", endDate: "", timeZone: getTimezone(), filters: filteredFilters }
- : buildApiParams(timeOverride || time, { filters: filteredFilters });
-
- return useInfiniteQuery<{ data: GetSessionsResponse }>({
- queryKey: ["sessions-infinite", timeOverride || time, site, filteredFilters, userId, timezone],
- queryFn: ({ pageParam = 1 }) => {
- return fetchSessions(site, {
- ...params,
- page: pageParam as number,
- userId,
- limit,
- });
- },
+ return useAnalyticsInfiniteQuery<GetSessionsResponse>({
+ key: "sessions-infinite",
+ path: "sessions",
+ overrideTime: timeOverride,
+ // Scoping to a user means every session that user ever had, not just the
+ // ones inside the selected period.
+ useTime: !userId,
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: { limit, user_id: userId },
initialPageParam: 1,
- getNextPageParam: (lastPage: { data: GetSessionsResponse }, allPages) => {
- // If we have data and it's a full page (100 items), there might be more
- if (lastPage?.data && lastPage.data.length === limit) {
- return allPages.length + 1;
- }
- return undefined;
- },
+ pageParams: page => ({ page }),
+ // A full page might have more behind it; a short one is the last.
+ getNextPageParam: (lastPage, allPages) => (lastPage.length === limit ? allPages.length + 1 : undefined),
staleTime: Infinity,
refetchInterval,
- // Without this the hook fires while the store's site is still empty, requesting
- // /api/sites//sessions (400). LiveUserCount renders on every [site] page, so
- // this ran on every page load.
- enabled: !!site,
});
}
export function useGetSessionDetailsInfinite(sessionId: string | null) {
- const { site, time } = useStore();
- const pastMinutesMode = time.mode === "past-minutes";
-
- // Get minutes based on the time mode
- let minutes: number | undefined;
- if (pastMinutesMode && time.mode === "past-minutes") {
- minutes = time.pastMinutesStart;
- }
+ const time = useStore(state => state.time);
+ // In past-minutes mode the session detail endpoint takes the window as a
+ // minute count rather than a date range.
+ const minutes = time.mode === "past-minutes" ? time.pastMinutesStart : undefined;
- return useInfiniteQuery<{ data: SessionPageviewsAndEvents }>({
- queryKey: ["session-details-infinite", sessionId, site, minutes],
- queryFn: ({ pageParam = 0 }) => {
- if (!sessionId) throw new Error("Session ID is required");
-
- return fetchSession(site, {
- sessionId,
- limit: 100,
- offset: pageParam as number,
- minutes: pastMinutesMode ? minutes : undefined,
- });
- },
+ return useAnalyticsInfiniteQuery<SessionPageviewsAndEvents>({
+ key: ["session-details-infinite", sessionId],
+ path: `sessions/${sessionId}`,
+ useTime: false,
+ useFilters: false,
+ params: { limit: 100, minutes },
initialPageParam: 0,
- getNextPageParam: lastPage => {
- if (lastPage?.data?.pagination?.hasMore) {
- return lastPage.data.pagination.offset + lastPage.data.pagination.limit;
- }
- return undefined;
- },
- enabled: !!sessionId && !!site,
+ pageParams: offset => ({ offset }),
+ getNextPageParam: lastPage =>
+ lastPage?.pagination?.hasMore ? lastPage.pagination.offset + lastPage.pagination.limit : undefined,
+ enabled: !!sessionId,
staleTime: Infinity,
});
}
export function useGetUserSessionCount(userId: string) {
- const { site, timezone } = useStore();
// The calendar always spans the user's full history, so it only takes the
// dimension filters, not the selected time range.
const filteredFilters = getFilteredFilters(USER_DETAIL_PAGE_FILTERS);
- return useQuery<{ data: UserSessionCountResponse[] }>({
- queryKey: ["user-session-count", userId, site, timezone, filteredFilters],
- queryFn: () => {
- return fetchUserSessionCount(site, {
- userId,
- timeZone: getTimezone(),
- filters: filteredFilters,
- });
- },
+ return useAnalyticsQuery<UserSessionCountResponse[]>({
+ key: ["user-session-count", userId],
+ path: "users/session-count",
+ useTime: false,
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ params: { user_id: userId },
staleTime: Infinity,
- enabled: !!site && !!userId,
+ // Keyed by user: never show the previous user's session calendar.
+ placeholder: false,
+ enabled: !!userId,
});
}
diff --git a/client/src/api/analytics/hooks/useGetUserTraits.ts b/client/src/api/analytics/hooks/useGetUserTraits.ts
index a02413e5d..8362e19d5 100644
--- a/client/src/api/analytics/hooks/useGetUserTraits.ts
+++ b/client/src/api/analytics/hooks/useGetUserTraits.ts
@@ -1,65 +1,51 @@
-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import {
- fetchUserTraitKeys,
- fetchUserTraitValues,
- fetchUserTraitValueUsers,
- TraitKeysResponse,
- TraitValuesResponse,
- TraitValueUsersResponse,
-} from "../endpoints";
+import { TraitKeysResponse, TraitValuesResponse, TraitValueUsersResponse } from "../endpoints";
+import { useAnalyticsInfiniteQuery, useAnalyticsQuery } from "../useAnalyticsQuery";
-export function useGetUserTraitKeys() {
- const { site } = useStore();
+const VALUES_LIMIT = 1000;
+const USERS_LIMIT = 250;
+
+// Trait keys and values describe the whole site, not the selected period.
+const TRAIT_CONTEXT = { useTime: false, useFilters: false } as const;
- return useQuery<TraitKeysResponse>({
- queryKey: ["user-trait-keys", site],
- queryFn: () => fetchUserTraitKeys(site),
- enabled: !!site,
+export function useGetUserTraitKeys() {
+ return useAnalyticsQuery<TraitKeysResponse>({
+ key: "user-trait-keys",
+ path: "user-traits/keys",
+ unwrap: false,
+ ...TRAIT_CONTEXT,
+ staleTime: 0,
+ placeholder: false,
});
}
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,
- });
- },
+ return useAnalyticsInfiniteQuery<TraitValuesResponse>({
+ key: ["user-trait-values", key],
+ path: "user-traits/values",
+ unwrap: false,
+ ...TRAIT_CONTEXT,
+ params: { key, limit: VALUES_LIMIT },
+ staleTime: 0,
initialPageParam: 0,
- getNextPageParam: (lastPage, allPages) => {
- const totalFetched = allPages.reduce((acc, page) => acc + page.values.length, 0);
- return lastPage.hasMore ? totalFetched : undefined;
- },
- enabled: !!site && !!key,
+ pageParams: offset => ({ offset }),
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.hasMore ? allPages.reduce((total, page) => total + page.values.length, 0) : undefined,
+ enabled: !!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,
- });
- },
+ return useAnalyticsInfiniteQuery<TraitValueUsersResponse>({
+ key: ["user-trait-value-users", key, value],
+ path: "user-traits/users",
+ unwrap: false,
+ ...TRAIT_CONTEXT,
+ params: { key, value, limit: USERS_LIMIT },
+ staleTime: 0,
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,
+ pageParams: offset => ({ offset }),
+ getNextPageParam: (lastPage, allPages) =>
+ lastPage.hasMore ? allPages.reduce((total, page) => total + page.users.length, 0) : undefined,
+ enabled: !!key && value !== null,
});
}
diff --git a/client/src/api/analytics/hooks/useGetUsers.ts b/client/src/api/analytics/hooks/useGetUsers.ts
index e991c3321..f948b4ef2 100644
--- a/client/src/api/analytics/hooks/useGetUsers.ts
+++ b/client/src/api/analytics/hooks/useGetUsers.ts
@@ -1,8 +1,7 @@
import { Filter } from "@rybbit/shared";
-import { getFilteredFilters } from "../../../lib/store";
import { USER_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { APIResponse } from "../../types";
-import { fetchUsers, UsersParams, UsersResponse } from "../endpoints";
+import { getFilteredFilters } from "../../../lib/store";
+import { UsersListResponse } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
export interface GetUsersOptions {
@@ -20,40 +19,26 @@ export function useGetUsers(options: GetUsersOptions) {
const { page, pageSize, sortBy, sortOrder, identifiedOnly = false, search, searchField } = options;
const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
- return useAnalyticsQuery<
- APIResponse<UsersResponse[]> & {
- totalCount: number;
- page: number;
- pageSize: number;
- },
- UsersParams
- >({
+ return useAnalyticsQuery<UsersListResponse>({
key: "users",
+ path: "users",
+ unwrap: false,
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so an empty page-filter set stays unfiltered.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
- extraParams: {
+ params: {
page,
- pageSize,
- sortBy,
- sortOrder: sortOrder as "asc" | "desc",
- identifiedOnly,
- search,
- searchField,
+ page_size: pageSize,
+ sort_by: sortBy,
+ sort_order: sortOrder,
+ identified_only: identifiedOnly,
+ search: search || undefined,
+ search_field: searchField || undefined,
},
// Use default staleTime (0) for real-time data
staleTime: 0,
// Enable refetching when the window regains focus
props: { refetchOnWindowFocus: true },
- fetch: async (site, params) => {
- const result = await fetchUsers(site, params);
- return {
- data: result.data as UsersResponse[],
- totalCount: result.totalCount,
- page: result.page,
- pageSize: result.pageSize,
- };
- },
});
}
diff --git a/client/src/api/analytics/hooks/userGetInfo.ts b/client/src/api/analytics/hooks/userGetInfo.ts
index 3cc92b87f..9b0e6988a 100644
--- a/client/src/api/analytics/hooks/userGetInfo.ts
+++ b/client/src/api/analytics/hooks/userGetInfo.ts
@@ -1,6 +1,6 @@
import { USER_DETAIL_PAGE_FILTERS } from "../../../lib/filterGroups";
import { getFilteredFilters } from "../../../lib/store";
-import { fetchUserInfo, UserInfo } from "../endpoints";
+import { UserInfo } from "../endpoints";
import { useAnalyticsQuery } from "../useAnalyticsQuery";
export function useUserInfo(siteId: number, userId: string) {
@@ -9,12 +9,12 @@ export function useUserInfo(siteId: number, userId: string) {
return useAnalyticsQuery<UserInfo>({
// userId must stay at index 1 β€” useDeleteUser removes ["user-info", userId].
key: ["user-info", userId],
+ path: `users/${encodeURIComponent(userId)}`,
site: siteId,
// customFilters fall back to the store filters when empty; disable filters
// entirely instead so an empty page-filter set stays unfiltered.
useFilters: filteredFilters.length > 0,
customFilters: filteredFilters,
enabled: !!siteId && !!userId,
- fetch: (site, params) => fetchUserInfo(site, userId, params),
});
}
diff --git a/client/src/api/analytics/useAnalyticsQuery.ts b/client/src/api/analytics/useAnalyticsQuery.ts
index 564f579f3..7398ac359 100644
--- a/client/src/api/analytics/useAnalyticsQuery.ts
+++ b/client/src/api/analytics/useAnalyticsQuery.ts
@@ -8,9 +8,14 @@ import {
UseQueryResult,
} from "@tanstack/react-query";
import { Time } from "../../components/DateSelector/types";
-import { useStore } from "../../lib/store";
-import { buildApiParams } from "../utils";
-import { CommonApiParams } from "./endpoints/types";
+import { useStore, useTimezone } from "../../lib/store";
+import {
+ AnalyticsContext,
+ AnalyticsDescriptor,
+ AnalyticsRequest,
+ buildAnalyticsRequest,
+ fetchAnalytics,
+} from "./analyticsRequest";
type PeriodTime = "current" | "previous";
@@ -23,6 +28,9 @@ export interface AnalyticsContextOptions {
overrideTime?: Time;
// Previous period in past-minutes mode means [2x .. 1x] minutes ago.
doublePastMinutesForPrevious?: boolean;
+ // Endpoints that are not scoped to the selected period (trait keys, saved
+ // funnels) send no window and do not refetch when the date selector moves.
+ useTime?: boolean;
useFilters?: boolean;
// Appended to the store filters.
additionalFilters?: Filter[];
@@ -32,13 +40,24 @@ export interface AnalyticsContextOptions {
/**
* Resolves the analytics request context (site, time period, filters) from the
- * store once and derives the wire params from it. The queryKey is built from
- * the same params object that is sent to the endpoint, so it is in sync with
- * the request by construction β€” a hook can no longer forget to list an input
- * and silently serve stale data.
+ * store once and derives the request from it β€” path plus the exact params that
+ * go on the wire. The queryKey is built from that same request, so it is in
+ * sync with what is sent by construction: a hook can no longer forget to list
+ * an input and silently serve stale data.
+ *
+ * The store is read through selectors so a `selectedStat` or `bucket` change
+ * does not re-render every analytics hook on the page.
*/
-function useAnalyticsParams(options: AnalyticsContextOptions & { extraParams?: Record<string, unknown> }) {
- const { time, previousTime, site: storeSite, filters } = useStore();
+export function useAnalyticsContext(options: AnalyticsContextOptions = {}): {
+ site: number | string;
+ context: AnalyticsContext;
+} {
+ const storeSite = useStore(state => state.site);
+ const time = useStore(state => state.time);
+ const previousTime = useStore(state => state.previousTime);
+ const filters = useStore(state => state.filters);
+ const timeZone = useTimezone();
+
const site = options.site ?? storeSite;
const baseTime = options.overrideTime ?? time;
@@ -61,22 +80,25 @@ function useAnalyticsParams(options: AnalyticsContextOptions & { extraParams?: R
? [...filters, ...options.additionalFilters]
: filters;
- const params = { ...buildApiParams(timeToUse, { filters: combinedFilters }), ...options.extraParams };
- return { site, params };
+ return {
+ site,
+ context: {
+ time: (options.useTime ?? true) ? timeToUse : null,
+ timeZone,
+ filters: combinedFilters,
+ },
+ };
+}
+
+function useAnalyticsRequest(options: AnalyticsContextOptions & AnalyticsDescriptor) {
+ const { site, context } = useAnalyticsContext(options);
+ return { site, request: buildAnalyticsRequest(options, context) };
}
-export interface AnalyticsQueryOptions<TData, TParams extends CommonApiParams = CommonApiParams>
- extends AnalyticsContextOptions {
+export interface AnalyticsQueryOptions<TData> extends AnalyticsContextOptions, AnalyticsDescriptor {
// First element(s) of the queryKey. Keep the historical name β€” mutations
// invalidate by this prefix (e.g. ["users"], ["user-info", userId]).
key: string | readonly unknown[];
- fetch: (site: number | string, params: TParams) => Promise<TData>;
- // Endpoint params beyond the shared time/filter context (bucket, parameter,
- // limit, page, ...). Spread into the wire params AND the queryKey.
- extraParams?: Omit<TParams, keyof CommonApiParams>;
- // ONLY for values that change the fetcher itself rather than its params
- // (e.g. the `lite` flag). Everything else is already in the key via params.
- keyExtras?: readonly unknown[];
staleTime?: number;
refetchInterval?: number;
enabled?: boolean;
@@ -89,19 +111,15 @@ export interface AnalyticsQueryOptions<TData, TParams extends CommonApiParams =
const buildQueryKey = (
key: string | readonly unknown[],
site: number | string | undefined,
- params: unknown,
- keyExtras?: readonly unknown[]
-) => [...(Array.isArray(key) ? key : [key]), site, params, ...(keyExtras ?? [])];
+ request: AnalyticsRequest
+) => [...(Array.isArray(key) ? key : [key]), site, request.path, request.params, request.body];
-export function useAnalyticsQuery<TData, TParams extends CommonApiParams = CommonApiParams>(
- options: AnalyticsQueryOptions<TData, TParams>
-): UseQueryResult<TData> {
- const { site, params } = useAnalyticsParams(options);
- const queryKey = buildQueryKey(options.key, site, params, options.keyExtras);
+export function useAnalyticsQuery<TData>(options: AnalyticsQueryOptions<TData>): UseQueryResult<TData> {
+ const { site, request } = useAnalyticsRequest(options);
return useQuery<TData, Error>({
- queryKey,
- queryFn: () => options.fetch(site!, params as TParams),
+ queryKey: buildQueryKey(options.key, site, request),
+ queryFn: () => fetchAnalytics<TData>(site!, request),
staleTime: options.staleTime ?? 60_000,
refetchInterval: options.refetchInterval,
placeholderData:
@@ -114,34 +132,45 @@ export function useAnalyticsQuery<TData, TParams extends CommonApiParams = Commo
});
}
-export interface AnalyticsInfiniteQueryOptions<
- TPage extends { data: unknown[]; totalCount: number },
- TParams extends CommonApiParams = CommonApiParams,
-> extends AnalyticsContextOptions {
+export interface AnalyticsInfiniteQueryOptions<TPage, TCursor> extends AnalyticsContextOptions, AnalyticsDescriptor {
key: string | readonly unknown[];
- fetchPage: (site: number | string, params: TParams, page: number) => Promise<TPage>;
- extraParams?: Omit<TParams, keyof CommonApiParams>;
- keyExtras?: readonly unknown[];
+ initialPageParam: TCursor;
+ // Params that position the request at `cursor` (a page number, an offset, a
+ // timestamp) β€” merged into the descriptor params for that page.
+ pageParams: (cursor: TCursor) => Record<string, unknown>;
+ getNextPageParam: (lastPage: TPage, allPages: TPage[]) => TCursor | undefined;
staleTime?: number;
+ refetchInterval?: number;
enabled?: boolean;
+ refetchOnWindowFocus?: boolean;
}
-export function useAnalyticsInfiniteQuery<
- TPage extends { data: unknown[]; totalCount: number },
- TParams extends CommonApiParams = CommonApiParams,
->(options: AnalyticsInfiniteQueryOptions<TPage, TParams>): UseInfiniteQueryResult<InfiniteData<TPage>> {
- const { site, params } = useAnalyticsParams(options);
- const queryKey = [...buildQueryKey(options.key, site, params, options.keyExtras), "infinite"];
-
- return useInfiniteQuery({
- queryKey,
- queryFn: ({ pageParam }) => options.fetchPage(site!, params as TParams, pageParam as number),
- initialPageParam: 1,
- getNextPageParam: (lastPage, allPages) => {
- const fetchedItemCount = allPages.reduce((acc, page) => acc + page.data.length, 0);
- return fetchedItemCount >= lastPage.totalCount ? undefined : allPages.length + 1;
- },
+export function useAnalyticsInfiniteQuery<TPage, TCursor = number>(
+ options: AnalyticsInfiniteQueryOptions<TPage, TCursor>
+): UseInfiniteQueryResult<InfiniteData<TPage>> {
+ const { site, request } = useAnalyticsRequest(options);
+
+ return useInfiniteQuery<TPage, Error, InfiniteData<TPage>, readonly unknown[], TCursor>({
+ queryKey: [...buildQueryKey(options.key, site, request), "infinite"],
+ queryFn: ({ pageParam }) =>
+ fetchAnalytics<TPage>(site!, {
+ ...request,
+ params: { ...request.params, ...options.pageParams(pageParam as TCursor) },
+ }),
+ initialPageParam: options.initialPageParam,
+ getNextPageParam: options.getNextPageParam,
staleTime: options.staleTime ?? 60_000,
+ refetchInterval: options.refetchInterval,
+ refetchOnWindowFocus: options.refetchOnWindowFocus,
enabled: (options.enabled ?? true) && !!site,
});
}
+
+/** Page-numbered pagination over an endpoint that reports a `totalCount`. */
+export const nextPageByTotalCount = <TPage extends { data: unknown[]; totalCount: number }>(
+ lastPage: TPage,
+ allPages: TPage[]
+): number | undefined => {
+ const fetched = allPages.reduce((total, page) => total + page.data.length, 0);
+ return fetched >= lastPage.totalCount ? undefined : allPages.length + 1;
+};
diff --git a/client/src/api/gsc/gscDateRange.ts b/client/src/api/gsc/gscDateRange.ts
new file mode 100644
index 000000000..e71266318
--- /dev/null
+++ b/client/src/api/gsc/gscDateRange.ts
@@ -0,0 +1,24 @@
+import { DateTime } from "luxon";
+import { Time } from "../../components/DateSelector/types";
+import { getStartAndEndDate } from "../utils";
+
+// The GSC API only accepts whole-day date ranges and keeps ~16 months of
+// history, so sub-day dashboard ranges are widened to whole days and
+// all-time is clamped to Google's maximum lookback.
+export function getGSCDateRange(time: Time, timeZone: string): { startDate: string; endDate: string } {
+ const today = DateTime.now().setZone(timeZone);
+ if (time.mode === "past-minutes") {
+ return {
+ startDate: today.minus({ minutes: time.pastMinutesStart }).toISODate() ?? "",
+ endDate: today.toISODate() ?? "",
+ };
+ }
+ if (time.mode === "all-time") {
+ return {
+ startDate: today.minus({ months: 16 }).toISODate() ?? "",
+ endDate: today.toISODate() ?? "",
+ };
+ }
+ const { startDate, endDate } = getStartAndEndDate(time, timeZone);
+ return { startDate: startDate ?? "", endDate: endDate ?? "" };
+}
diff --git a/client/src/api/gsc/hooks/useGetGSCData.ts b/client/src/api/gsc/hooks/useGetGSCData.ts
index 231f87381..84e2f330b 100644
--- a/client/src/api/gsc/hooks/useGetGSCData.ts
+++ b/client/src/api/gsc/hooks/useGetGSCData.ts
@@ -1,49 +1,21 @@
import { useQuery } from "@tanstack/react-query";
-import { DateTime } from "luxon";
-import { Time } from "../../../components/DateSelector/types";
-import { getTimezone, useStore } from "../../../lib/store";
-import { getStartAndEndDate } from "../../utils";
+import { useStore, useTimezone } from "../../../lib/store";
import { fetchGSCData, GSCDimension } from "../endpoints";
-
-// The GSC API only accepts whole-day date ranges and keeps ~16 months of
-// history, so sub-day dashboard ranges are widened to whole days and
-// all-time is clamped to Google's maximum lookback.
-function getGSCDateRange(time: Time): { startDate: string; endDate: string } {
- const today = DateTime.now().setZone(getTimezone());
- if (time.mode === "past-minutes") {
- return {
- startDate: today.minus({ minutes: time.pastMinutesStart }).toISODate() ?? "",
- endDate: today.toISODate() ?? "",
- };
- }
- if (time.mode === "all-time") {
- return {
- startDate: today.minus({ months: 16 }).toISODate() ?? "",
- endDate: today.toISODate() ?? "",
- };
- }
- const { startDate, endDate } = getStartAndEndDate(time);
- return { startDate: startDate ?? "", endDate: endDate ?? "" };
-}
+import { getGSCDateRange } from "../gscDateRange";
/**
* Hook to fetch data from Google Search Console for a specific dimension
*/
export function useGetGSCData(dimension: GSCDimension) {
- const { site, time, timezone } = useStore();
- const { startDate, endDate } = getGSCDateRange(time);
+ const site = useStore(state => state.site);
+ const time = useStore(state => state.time);
+ // Resolved zone, never the "system" sentinel β€” the API needs a real IANA zone
+ const timeZone = useTimezone();
+ const { startDate, endDate } = getGSCDateRange(time, timeZone);
return useQuery({
- queryKey: ["gsc-data", dimension, site, startDate, endDate, timezone],
- queryFn: () => {
- return fetchGSCData(site!, {
- dimension,
- startDate,
- endDate,
- // Resolve the "system" sentinel β€” the API needs a real IANA zone
- timeZone: getTimezone(),
- });
- },
+ queryKey: ["gsc-data", dimension, site, startDate, endDate, timeZone],
+ queryFn: () => fetchGSCData(site!, { dimension, startDate, endDate, timeZone }),
enabled: !!site,
// Refetch less frequently since GSC data updates slowly
staleTime: 5 * 60 * 1000, // 5 minutes
diff --git a/client/src/api/installRequestContext.ts b/client/src/api/installRequestContext.ts
new file mode 100644
index 000000000..bfb3e3ddb
--- /dev/null
+++ b/client/src/api/installRequestContext.ts
@@ -0,0 +1,12 @@
+import { getSiteRouteContext } from "../lib/siteRoute";
+import { useStore } from "../lib/store";
+import { setPrivateKeyResolver } from "./requestContext";
+
+// Imported once from the client provider tree. On the client the URL is the
+// authority (a shared dashboard is /[site]/[privateKey]/...); on the server
+// there is no URL to read, so fall back to whatever the store was seeded with.
+setPrivateKeyResolver(() =>
+ typeof window !== "undefined"
+ ? getSiteRouteContext(globalThis.location.pathname).privateKey
+ : useStore.getState().privateKey
+);
diff --git a/client/src/api/requestContext.ts b/client/src/api/requestContext.ts
new file mode 100644
index 000000000..905586178
--- /dev/null
+++ b/client/src/api/requestContext.ts
@@ -0,0 +1,18 @@
+/**
+ * Where `authedFetch` gets the private key for shared-dashboard requests.
+ *
+ * The resolver is injected at app boot (see `installRequestContext`) so the
+ * HTTP primitive itself does not reach into routing or the Zustand store β€” the
+ * fetch path stays substitutable in tests.
+ */
+type PrivateKeyResolver = () => string | null;
+
+let resolvePrivateKey: PrivateKeyResolver = () => null;
+
+export function setPrivateKeyResolver(resolver: PrivateKeyResolver) {
+ resolvePrivateKey = resolver;
+}
+
+export function getRequestPrivateKey(): string | null {
+ return resolvePrivateKey();
+}
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index b9f06b64d..3b498d16e 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -3,14 +3,12 @@ import { DateTime } from "luxon";
import { Time } from "../components/DateSelector/types";
import axios, { AxiosRequestConfig } from "axios";
import { BACKEND_URL } from "../lib/const";
-import { getSiteRouteContext } from "../lib/siteRoute";
-import { getTimezone, useStore } from "../lib/store";
+import { getRequestPrivateKey } from "./requestContext";
import { CommonApiParams } from "./analytics/endpoints/types";
-export function getStartAndEndDate(time: Time): { startDate: string | null; endDate: string | null } {
+export function getStartAndEndDate(time: Time, timeZone: string): { startDate: string | null; endDate: string | null } {
if (time.mode === "range") {
if (time.startTime && time.endTime) {
- const timeZone = getTimezone();
const end = DateTime.fromISO(`${time.endDate}T${time.endTime}`, { zone: timeZone });
return {
startDate: time.startDate,
@@ -43,10 +41,6 @@ export function getStartAndEndDate(time: Time): { startDate: string | null; endD
return { startDate: time.day, endDate: time.day };
}
-/**
- * Build CommonApiParams from a Time object, handling all time modes including past-minutes.
- * This centralizes the logic for converting Time to API params across all hooks.
- */
function sanitizeFilters(filters?: Filter[]): Filter[] | undefined {
if (!filters) return undefined;
const cleaned = filters.filter(f => {
@@ -56,8 +50,14 @@ function sanitizeFilters(filters?: Filter[]): Filter[] | undefined {
return cleaned.length > 0 ? cleaned : undefined;
}
-export function buildApiParams(time: Time, options: { filters?: Filter[] } = {}): CommonApiParams {
- const timeZone = getTimezone();
+/**
+ * Build CommonApiParams from a Time object, handling every time mode
+ * (date range, exact datetime range, past-minutes). The timezone is injected
+ * rather than read from the store, so the whole time-window serialisation is a
+ * pure function of its arguments.
+ */
+export function buildApiParams(time: Time, options: { timeZone: string; filters?: Filter[] }): CommonApiParams {
+ const { timeZone } = options;
const filters = sanitizeFilters(options.filters);
if (time.mode === "past-minutes") {
@@ -84,7 +84,7 @@ export function buildApiParams(time: Time, options: { filters?: Filter[] } = {})
};
}
- const { startDate, endDate } = getStartAndEndDate(time);
+ const { startDate, endDate } = getStartAndEndDate(time, timeZone);
return {
startDate: startDate ?? "",
endDate: endDate ?? "",
@@ -112,11 +112,7 @@ export async function authedFetch<T>(
});
}
- // Get private key from store and add to headers if present
- const privateKey =
- typeof window !== "undefined"
- ? getSiteRouteContext(globalThis.location.pathname).privateKey
- : useStore.getState().privateKey;
+ const privateKey = getRequestPrivateKey();
const headers = {
...config.headers,
...(privateKey ? { "x-private-key": privateKey } : {}),
diff --git a/client/src/app/(home)/SiteCard.tsx b/client/src/app/(home)/SiteCard.tsx
index a0bdec57a..f623dc977 100644
--- a/client/src/app/(home)/SiteCard.tsx
+++ b/client/src/app/(home)/SiteCard.tsx
@@ -84,7 +84,7 @@ export function SiteCard({
hasLoadedData.current = true;
}
- const hasData = (overviewData?.data?.sessions || 0) > 0;
+ const hasData = (overviewData?.sessions || 0) > 0;
// Show skeleton when loading or not yet in view, but not if we've already loaded data previously
const showSkeleton = (isLoading || isOverviewLoading || !isInView) && !hasLoadedData.current;
@@ -176,7 +176,7 @@ export function SiteCard({
</div>
<div className="flex flex-col sm:flex-row gap-2 sm:gap-4 items-start sm:items-center justify-between">
<div className="relative rounded-md w-40 h-12.5">
- <SiteSessionChart data={data?.data ?? []} />
+ <SiteSessionChart data={data ?? []} />
{!hasData && (
<div className="absolute inset-0 flex items-center justify-center bg-white/70 dark:bg-neutral-900/70 backdrop-blur-sm">
<span className="text-sm text-neutral-500 dark:text-neutral-400">{t("No data available")}</span>
@@ -188,11 +188,11 @@ export function SiteCard({
<div className="flex flex-col items-start gap-1 rounded-md p-2 transition-colors">
<div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Sessions")}</div>
<div className="font-semibold text-xl flex gap-2">
- {formatter(overviewData?.data?.sessions ?? 0)}{" "}
- {overviewData?.data?.sessions && overviewDataPrevious?.data?.sessions ? (
+ {formatter(overviewData?.sessions ?? 0)}{" "}
+ {overviewData?.sessions && overviewDataPrevious?.sessions ? (
<ChangePercentage
- current={overviewData?.data?.sessions}
- previous={overviewDataPrevious?.data?.sessions}
+ current={overviewData?.sessions}
+ previous={overviewDataPrevious?.sessions}
/>
) : null}
</div>
@@ -201,11 +201,11 @@ export function SiteCard({
<div className="flex flex-col items-start gap-1 rounded-md p-2 transition-colors">
<div className="text-xs text-neutral-500 dark:text-neutral-400">{t("Users")}</div>
<div className="font-semibold text-xl flex gap-2">
- {formatter(overviewData?.data?.users ?? 0)}{" "}
- {overviewData?.data?.users && overviewDataPrevious?.data?.users ? (
+ {formatter(overviewData?.users ?? 0)}{" "}
+ {overviewData?.users && overviewDataPrevious?.users ? (
<ChangePercentage
- current={overviewData?.data?.users}
- previous={overviewDataPrevious?.data?.users}
+ current={overviewData?.users}
+ previous={overviewDataPrevious?.users}
/>
) : null}
</div>
diff --git a/client/src/app/Providers.tsx b/client/src/app/Providers.tsx
index 8da6a6572..3a735d3c0 100644
--- a/client/src/app/Providers.tsx
+++ b/client/src/app/Providers.tsx
@@ -1,5 +1,8 @@
"use client";
+// Side-effect import: teaches authedFetch where to find the private key so the
+// HTTP layer itself doesn't have to know about routing or the store.
+import "@/api/installRequestContext";
import { useAppEnv } from "@/hooks/useIsProduction";
import { useStopImpersonation } from "@/hooks/useStopImpersonation";
import { IS_CLOUD } from "@/lib/const";
diff --git a/client/src/app/[site]/bots/components/BotChart.tsx b/client/src/app/[site]/bots/components/BotChart.tsx
index 43e3fb0a3..66da5a7f4 100644
--- a/client/src/app/[site]/bots/components/BotChart.tsx
+++ b/client/src/app/[site]/bots/components/BotChart.tsx
@@ -38,7 +38,7 @@ export function BotChart() {
const upperBoundMs = (boundsMax ?? now.toJSDate()).getTime();
const points: BotPoint[] = [];
- timeSeriesData?.data?.forEach(item => {
+ timeSeriesData?.forEach(item => {
const timestamp = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
if (timestamp > now) return;
const timestampMs = timestamp.toMillis();
diff --git a/client/src/app/[site]/bots/components/BotSection.tsx b/client/src/app/[site]/bots/components/BotSection.tsx
index 07debbce1..de4ea6d6c 100644
--- a/client/src/app/[site]/bots/components/BotSection.tsx
+++ b/client/src/app/[site]/bots/components/BotSection.tsx
@@ -143,7 +143,7 @@ function useBotSectionData(dimension: BotDimensionKey) {
});
const items =
- data?.data?.data.map(item => ({
+ data?.data.map(item => ({
...item,
value: item.value == null ? "" : String(item.value),
hostname: item.hostname == null ? undefined : String(item.hostname),
diff --git a/client/src/app/[site]/bots/components/BotsOverview.tsx b/client/src/app/[site]/bots/components/BotsOverview.tsx
index 4eb0dbc4e..4df01e1a3 100644
--- a/client/src/app/[site]/bots/components/BotsOverview.tsx
+++ b/client/src/app/[site]/bots/components/BotsOverview.tsx
@@ -116,7 +116,7 @@ export function BotsOverview() {
const { site } = useStore();
const { selectedLayer, setSelectedLayer } = useBotsStore();
const { data, isLoading, isFetching } = useGetBotOverview({ site });
- const overview = data?.data;
+ const overview = data;
return (
<Card>
diff --git a/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts b/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
index c9c216ec4..0f077e51d 100644
--- a/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
+++ b/client/src/app/[site]/components/SubHeader/Export/exportCsv.ts
@@ -1,18 +1,13 @@
-import { FilterParameter } from "@rybbit/shared";
-import {
- fetchEventNames,
- fetchMetric,
- fetchOutboundLinks,
- fetchOverviewBucketed,
-} from "../../../../../api/analytics/endpoints";
-import { getStartAndEndDate } from "../../../../../api/utils";
+import { Filter, FilterParameter } from "@rybbit/shared";
+import { buildAnalyticsRequest, fetchAnalytics } from "../../../../../api/analytics/analyticsRequest";
import { fetchGSCConnectionStatus, fetchGSCData, GSCDimension } from "../../../../../api/gsc/endpoints";
-import { CSVFile, downloadZip, formatDateForFilename } from "../../../../../lib/export";
+import { getGSCDateRange } from "../../../../../api/gsc/gscDateRange";
import { Time } from "../../../../../components/DateSelector/types";
-import { Filter } from "@rybbit/shared";
+import { CSVFile, downloadZip, formatDateForFilename } from "../../../../../lib/export";
-// Metric parameters for each section
-const REFERRER_METRICS: { param: FilterParameter; filename: string }[] = [
+// One row per exported file: the analytics read that produces it.
+const METRIC_FILES: { param: FilterParameter; filename: string }[] = [
+ // Referrers
{ param: "referrer", filename: "referrers.csv" },
{ param: "channel", filename: "channels.csv" },
{ param: "utm_source", filename: "utm-source.csv" },
@@ -20,24 +15,18 @@ const REFERRER_METRICS: { param: FilterParameter; filename: string }[] = [
{ param: "utm_campaign", filename: "utm-campaign.csv" },
{ param: "utm_term", filename: "utm-term.csv" },
{ param: "utm_content", filename: "utm-content.csv" },
-];
-
-const PAGE_METRICS: { param: FilterParameter; filename: string }[] = [
+ // Pages
{ param: "pathname", filename: "pages.csv" },
{ param: "page_title", filename: "page-titles.csv" },
{ param: "entry_page", filename: "entry-pages.csv" },
{ param: "exit_page", filename: "exit-pages.csv" },
{ param: "hostname", filename: "hostnames.csv" },
-];
-
-const DEVICE_METRICS: { param: FilterParameter; filename: string }[] = [
+ // Devices
{ param: "browser", filename: "browsers.csv" },
{ param: "device_type", filename: "devices.csv" },
{ param: "operating_system", filename: "operating-systems.csv" },
{ param: "dimensions", filename: "screen-dimensions.csv" },
-];
-
-const COUNTRY_METRICS: { param: FilterParameter; filename: string }[] = [
+ // Locations
{ param: "country", filename: "countries.csv" },
{ param: "region", filename: "regions.csv" },
{ param: "city", filename: "cities.csv" },
@@ -45,6 +34,27 @@ const COUNTRY_METRICS: { param: FilterParameter; filename: string }[] = [
{ param: "timezone", filename: "timezones.csv" },
];
+type ExportDescriptor = {
+ filename: string;
+ path: string;
+ params?: Record<string, unknown>;
+ // Metric responses are `{ data, totalCount }`; the rest are plain rows.
+ rows?: (payload: any) => Record<string, unknown>[];
+};
+
+const EXPORTS: ExportDescriptor[] = [
+ ...METRIC_FILES.map(({ param, filename }) => ({
+ filename,
+ path: "metric",
+ params: { parameter: param },
+ rows: (payload: { data: Record<string, unknown>[] }) => payload.data,
+ })),
+ { filename: "overview-timeseries.csv", path: "overview/time-series", params: { bucket: "day" } },
+ { filename: "weekdays-heatmap.csv", path: "overview/time-series", params: { bucket: "hour" } },
+ { filename: "events.csv", path: "events/names" },
+ { filename: "outbound-links.csv", path: "events/outbound" },
+];
+
const GSC_DIMENSIONS: { dimension: GSCDimension; filename: string }[] = [
{ dimension: "query", filename: "gsc-queries.csv" },
{ dimension: "page", filename: "gsc-pages.csv" },
@@ -60,156 +70,58 @@ interface ExportCsvParams {
}
export async function exportCsv({ site, time, filters, timeZone }: ExportCsvParams): Promise<number> {
- const csvFiles: CSVFile[] = [];
-
- // Convert time to API params
- const { startDate, endDate } = getStartAndEndDate(time);
- const commonParams = {
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone,
- filters,
- };
-
- // Fetch all metrics in parallel
- const allMetrics = [
- ...REFERRER_METRICS,
- ...PAGE_METRICS,
- ...DEVICE_METRICS,
- ...COUNTRY_METRICS,
- ];
+ // Same request builder the dashboard uses, so the export covers every time
+ // mode β€” including past-minutes and exact-datetime ranges.
+ const context = { time, timeZone, filters };
- const metricPromises = allMetrics.map(async ({ param, filename }) => {
+ const analyticsFiles = EXPORTS.map(async ({ filename, path, params, rows }) => {
try {
- const result = await fetchMetric(site, { ...commonParams, parameter: param });
- return { filename, data: result.data as Record<string, unknown>[] };
+ const payload = await fetchAnalytics<unknown>(site, buildAnalyticsRequest({ path, params }, context));
+ return { filename, data: rows ? rows(payload) : (payload as Record<string, unknown>[]) };
} catch {
- console.warn(`Failed to fetch ${param}`);
+ console.warn(`Failed to fetch ${filename}`);
return { filename, data: [] };
}
});
- // Fetch overview bucketed data
- const overviewPromise = (async () => {
- try {
- const data = await fetchOverviewBucketed(site, { ...commonParams, bucket: "day" });
- return {
- filename: "overview-timeseries.csv",
- data: data as unknown as Record<string, unknown>[],
- };
- } catch {
- console.warn("Failed to fetch overview bucketed");
- return { filename: "overview-timeseries.csv", data: [] };
- }
- })();
-
- // Fetch weekdays heatmap data (hourly bucketed)
- const weekdaysPromise = (async () => {
- try {
- const data = await fetchOverviewBucketed(site, { ...commonParams, bucket: "hour" });
- return {
- filename: "weekdays-heatmap.csv",
- data: data as unknown as Record<string, unknown>[],
- };
- } catch {
- console.warn("Failed to fetch weekdays data");
- return { filename: "weekdays-heatmap.csv", data: [] };
- }
- })();
-
- // Fetch events data
- const eventsPromise = (async () => {
- try {
- const data = await fetchEventNames(site, commonParams);
- return {
- filename: "events.csv",
- data: data as unknown as Record<string, unknown>[],
- };
- } catch {
- console.warn("Failed to fetch events");
- return { filename: "events.csv", data: [] };
- }
- })();
-
- // Fetch outbound links
- const outboundPromise = (async () => {
- try {
- const data = await fetchOutboundLinks(site, commonParams);
- return {
- filename: "outbound-links.csv",
- data: data as unknown as Record<string, unknown>[],
- };
- } catch {
- console.warn("Failed to fetch outbound links");
- return { filename: "outbound-links.csv", data: [] };
- }
- })();
-
- // Check GSC connection and fetch if connected
- const gscPromises = (async () => {
+ const gscFiles = (async (): Promise<CSVFile[]> => {
try {
const status = await fetchGSCConnectionStatus(site);
if (!status.connected) {
return [];
}
- const gscResults = await Promise.all(
+ // GSC only serves whole-day ranges, so the dashboard window is widened
+ // the same way the GSC dashboard section widens it.
+ const { startDate, endDate } = getGSCDateRange(time, timeZone);
+
+ return await Promise.all(
GSC_DIMENSIONS.map(async ({ dimension, filename }) => {
try {
- const { startDate, endDate } = getStartAndEndDate(time);
- const data = await fetchGSCData(site, {
- dimension,
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone,
- });
- return {
- filename,
- data: data as unknown as Record<string, unknown>[],
- };
+ const data = await fetchGSCData(site, { dimension, startDate, endDate, timeZone });
+ return { filename, data: data as unknown as Record<string, unknown>[] };
} catch {
console.warn(`Failed to fetch GSC ${dimension}`);
return { filename, data: [] };
}
})
);
- return gscResults;
} catch {
console.warn("Failed to check GSC connection");
return [];
}
})();
- // Wait for all fetches to complete
- const [metricResults, overview, weekdays, events, outbound, gscResults] = await Promise.all([
- Promise.all(metricPromises),
- overviewPromise,
- weekdaysPromise,
- eventsPromise,
- outboundPromise,
- gscPromises,
- ]);
+ const [analyticsResults, gscResults] = await Promise.all([Promise.all(analyticsFiles), gscFiles]);
- // Collect all CSV files
- csvFiles.push(...metricResults);
- csvFiles.push(overview);
- csvFiles.push(weekdays);
- csvFiles.push(events);
- csvFiles.push(outbound);
- csvFiles.push(...gscResults);
-
- // Filter out empty files
+ const csvFiles: CSVFile[] = [...analyticsResults, ...gscResults];
const nonEmptyFiles = csvFiles.filter(f => f.data.length > 0);
if (nonEmptyFiles.length === 0) {
throw new Error("No data to export");
}
- // Generate ZIP filename
- const dateStr = formatDateForFilename();
- const zipFilename = `rybbit-export-${site}-${dateStr}.zip`;
-
- // Download the ZIP
+ const zipFilename = `rybbit-export-${site}-${formatDateForFilename()}.zip`;
await downloadZip(nonEmptyFiles, zipFilename);
return nonEmptyFiles.length;
diff --git a/client/src/app/[site]/components/SubHeader/Export/exportPdf.ts b/client/src/app/[site]/components/SubHeader/Export/exportPdf.ts
index 08d6c754c..0d00f0765 100644
--- a/client/src/app/[site]/components/SubHeader/Export/exportPdf.ts
+++ b/client/src/app/[site]/components/SubHeader/Export/exportPdf.ts
@@ -32,7 +32,7 @@ export function getPdfDateRange(time: Time, timeZone: string): { startDate: stri
return { startDate: time.startDate, endDate: time.endDate };
}
- const { startDate, endDate } = getStartAndEndDate(time);
+ const { startDate, endDate } = getStartAndEndDate(time, timeZone);
return {
startDate: startDate ?? today.toISODate() ?? "",
endDate: endDate ?? today.toISODate() ?? "",
diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
index dd080eee5..d72ad3fff 100644
--- a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
@@ -42,7 +42,7 @@ export function LiveUserCount() {
const sessions = useMemo(() => {
if (!sessionsData) return [];
- return sessionsData.pages.flatMap(page => page.data || []);
+ return sessionsData.pages.flatMap(page => page || []);
}, [sessionsData]);
// Fetch next page when intersection observer detects the target is visible
diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsx
index 1fc95af5a..8f8342d38 100644
--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx
+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx
@@ -198,11 +198,11 @@ export function ErrorDetails({ errorMessage }: ErrorDetailsProps) {
// Flatten all error events into a single array
const allErrorEvents = useMemo(() => {
if (!errorEventsData?.pages) return [];
- return errorEventsData.pages.flatMap(page => page.data?.data || []);
+ return errorEventsData.pages.flatMap(page => page.data || []);
}, [errorEventsData?.pages]);
// Get total count from the first page
- const totalCount = errorEventsData?.pages?.[0]?.data?.totalCount || 0;
+ const totalCount = errorEventsData?.pages?.[0]?.totalCount || 0;
if (isLoading) {
return (
diff --git a/client/src/app/[site]/errors/page.tsx b/client/src/app/[site]/errors/page.tsx
index 86a99d604..1cd2a9864 100644
--- a/client/src/app/[site]/errors/page.tsx
+++ b/client/src/app/[site]/errors/page.tsx
@@ -44,8 +44,8 @@ export default function Errors() {
page: pageNumber,
});
- const errorsDataArray: ErrorNameItem[] | undefined = apiResponse?.data?.data;
- const totalCount: number | undefined = apiResponse?.data?.totalCount;
+ const errorsDataArray: ErrorNameItem[] | undefined = apiResponse?.data;
+ const totalCount: number | undefined = apiResponse?.totalCount;
const isLoading = isLoadingErrors || isFetching;
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index 422c52cc8..8d9b6fa4a 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -91,12 +91,12 @@ function FunnelStepComponent({ step, index, steps, chartData, firstStep, siteId
enabled: isExpanded && currentTab === "dropped" && !isFirstStep,
});
- const allReachedSessions = reachedData?.data || [];
+ const allReachedSessions = reachedData || [];
const hasNextReached = allReachedSessions.length > LIMIT;
const reachedSessions = allReachedSessions.slice(0, LIMIT);
const hasPrevReached = reachedPage > 1;
- const allDroppedSessions = droppedData?.data || [];
+ const allDroppedSessions = droppedData || [];
const hasNextDropped = allDroppedSessions.length > LIMIT;
const droppedSessions = allDroppedSessions.slice(0, LIMIT);
const hasPrevDropped = droppedPage > 1;
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
index b59ec8291..b01af9b2d 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
@@ -1,10 +1,10 @@
import { useQuery } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useEffect, useMemo } from "react";
-import { fetchSessions, GetSessionsResponse, SessionsParams } from "../../../../../../api/analytics/endpoints";
-import { APIResponse } from "../../../../../../api/types";
-import { authedFetch, buildApiParams } from "../../../../../../api/utils";
-import { getFilteredFilters, useStore } from "../../../../../../lib/store";
+import { buildAnalyticsRequest, fetchAnalytics } from "../../../../../../api/analytics/analyticsRequest";
+import { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
+import { useAnalyticsContext } from "../../../../../../api/analytics/useAnalyticsQuery";
+import { getFilteredFilters } from "../../../../../../lib/store";
import { SESSION_PAGE_FILTERS } from "../../../../../../lib/filterGroups";
import { useShallow } from "zustand/react/shallow";
import { useTimelineStore } from "../../../timelineStore";
@@ -12,7 +12,6 @@ import { calculateWindowSize } from "../../../timelineUtils";
import { MAX_PAGES, PAGE_SIZE } from "./timelineLayerConstants";
export function useTimelineSessions() {
- const { time, site, timezone: storeTimezone } = useStore();
const { manualWindowSize, setTimeRange, setWindowSize, setAllSessions, setLoading, setError } = useTimelineStore(
useShallow(s => ({
manualWindowSize: s.manualWindowSize,
@@ -23,50 +22,39 @@ export function useTimelineSessions() {
setError: s.setError,
}))
);
- // Resolve "system" to actual timezone, but keep reactivity from useStore
- const timezone = storeTimezone === "system" ? Intl.DateTimeFormat().resolvedOptions().timeZone : storeTimezone;
-
const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+ const { site, context } = useAnalyticsContext({
+ useFilters: filteredFilters.length > 0,
+ customFilters: filteredFilters,
+ });
+ const timezone = context.timeZone;
+ const request = buildAnalyticsRequest({ path: "sessions", params: { limit: PAGE_SIZE } }, context);
// Fetch all sessions with pagination (up to 5 pages, 50k sessions total)
- const { data, isLoading, isError } = useQuery<APIResponse<GetSessionsResponse> & { hasMoreData?: boolean }>({
- queryKey: ["timeline-sessions", time, site, filteredFilters, timezone],
+ const { data, isLoading, isError } = useQuery({
+ queryKey: ["timeline-sessions", site, request.path, request.params],
queryFn: async () => {
- const allSessions = [];
+ const allSessions: GetSessionsResponse = [];
let reachedMaxPages = false;
for (let page = 1; page <= MAX_PAGES; page++) {
- const requestParams: SessionsParams = {
- ...buildApiParams(time, { filters: filteredFilters }),
- page,
- limit: PAGE_SIZE,
- };
-
- const response = await fetchSessions(site, requestParams);
-
- if (response?.data) {
- allSessions.push(...response.data);
-
- // If we got fewer results than the limit, we've reached the end
- if (response.data.length < PAGE_SIZE) {
- break;
- }
-
- // If we're on the last page and got a full page, there might be more
- if (page === MAX_PAGES && response.data.length === PAGE_SIZE) {
- reachedMaxPages = true;
- }
- } else {
- break;
- }
+ const sessions = await fetchAnalytics<GetSessionsResponse>(site, {
+ ...request,
+ params: { ...request.params, page },
+ });
+
+ if (!sessions?.length) break;
+ allSessions.push(...sessions);
+
+ // A short page is the last one; a full page on the last allowed page
+ // means there is more data than the timeline will load.
+ if (sessions.length < PAGE_SIZE) break;
+ if (page === MAX_PAGES) reachedMaxPages = true;
}
- // Return in the same format as the original API response
- return {
- data: allSessions,
- hasMoreData: reachedMaxPages,
- } as APIResponse<GetSessionsResponse> & { hasMoreData: boolean };
+ return { data: allSessions, hasMoreData: reachedMaxPages };
},
+ enabled: !!site,
staleTime: Infinity,
});
@@ -119,5 +107,5 @@ export function useTimelineSessions() {
}
setTimeRange(earliest, latest);
}
- }, [allSessions, setTimeRange, setWindowSize, manualWindowSize, time, timezone]);
+ }, [allSessions, setTimeRange, setWindowSize, manualWindowSize, timezone]);
}
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index 286a944e4..e8a228712 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -169,7 +169,7 @@ export function GlobeSessions() {
// Combine all pages of data
const flattenedData = useMemo(() => {
if (!data) return [];
- return data.pages.flatMap(page => page.data || []);
+ return data.pages.flatMap(page => page || []);
}, [data]);
return (
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
index 9373f88b5..4d5026780 100644
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ b/client/src/app/[site]/goals/components/GoalCard.tsx
@@ -185,7 +185,7 @@ export default function GoalCard({ goal, siteId, timeSeries, isLoadingTimeSeries
const propertyFilters = resolvePropertyFilters(goal.config);
- const allSessions = sessionsData?.data || [];
+ const allSessions = sessionsData || [];
const hasNextPage = allSessions.length > LIMIT;
const sessions = allSessions.slice(0, LIMIT);
const hasPrevPage = page > 1;
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 811449b9a..0d6d99984 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -4,7 +4,6 @@ import { DateTime } from "luxon";
import { useMemo } from "react";
import type { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
-import type { APIResponse } from "../../../../../api/types";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
import { TimeSeriesChart } from "../../../../../components/charts/TimeSeriesChart";
import type { TimeSeriesChartPoint } from "../../../../../components/charts/TimeSeriesChart";
@@ -34,8 +33,8 @@ export function Chart({
max,
chartXMax,
}: {
- data: APIResponse<GetOverviewBucketedResponse> | undefined;
- previousData: APIResponse<GetOverviewBucketedResponse> | undefined;
+ data: GetOverviewBucketedResponse | undefined;
+ previousData: GetOverviewBucketedResponse | undefined;
max: number;
chartXMax: Date | undefined;
}) {
@@ -53,7 +52,7 @@ export function Chart({
// Filter against strict period bounds so stale transition data does not
// bleed onto the new x-axis during goBack/goForward.
const currentPoints: Point[] = [];
- data?.data?.forEach(e => {
+ data?.forEach(e => {
const ts = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
if (ts > now) return;
const tsMs = ts.toMillis();
@@ -86,7 +85,7 @@ export function Chart({
const { min: prevMin } = getChartTimeBounds(previousTime, bucket, timezone);
const offsetMs = cMin && prevMin ? cMin.getTime() - prevMin.getTime() : 0;
const previousPoints: PrevPoint[] = [];
- previousData?.data?.forEach(e => {
+ previousData?.forEach(e => {
const prevTs = DateTime.fromSQL(e.time, { zone: timezone }).toUTC();
const mappedMs = prevTs.toMillis() + offsetMs;
if (lowerBoundMs !== undefined && mappedMs < lowerBoundMs) return;
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 3d80809e1..31cfd2ab8 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -64,8 +64,8 @@ export function MainSection() {
});
const maxOfDataAndPreviousData = Math.max(
- Math.max(...(data?.data?.map((d: any) => d[selectedStat]) ?? [])),
- Math.max(...(previousData?.data?.map((d: any) => d[selectedStat]) ?? []))
+ Math.max(...(data?.map((d: any) => d[selectedStat]) ?? [])),
+ Math.max(...(previousData?.map((d: any) => d[selectedStat]) ?? []))
);
// For range mode (Last 7 / 14 / 30 Days, custom range) anchor both charts'
@@ -77,7 +77,7 @@ export function MainSection() {
const chartXMax = (() => {
if (isPlaceholderData) return undefined;
if (time.mode !== "range") return undefined;
- const points = data?.data;
+ const points = data;
if (!points?.length) return undefined;
const now = DateTime.now();
for (let i = points.length - 1; i >= 0; i--) {
diff --git a/client/src/app/[site]/main/components/MainSection/MainSectionLite.tsx b/client/src/app/[site]/main/components/MainSection/MainSectionLite.tsx
index fae734c0f..075c89835 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSectionLite.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSectionLite.tsx
@@ -34,7 +34,7 @@ export function MainSectionLite() {
const { data, isFetching } = useGetOverviewBucketed({ site, bucket, lite: true });
- const max = Math.max(...(data?.data?.map((d: any) => d[selectedStat]) ?? []));
+ const max = Math.max(...(data?.map((d: any) => d[selectedStat]) ?? []));
return (
<>
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index 013345700..107fdbbab 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -79,7 +79,7 @@ const Stat = ({
// Filter and format sparklines data
const sparklinesData =
- data?.data
+ data
?.filter(d => {
// For past-minutes mode, ensure we only show data within the specified time range
if (time.mode === "past-minutes") {
@@ -175,23 +175,23 @@ export function Overview() {
const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
- const currentUsers = overviewData?.data?.users ?? 0;
- const previousUsers = overviewDataPrevious?.data?.users ?? 0;
+ const currentUsers = overviewData?.users ?? 0;
+ const previousUsers = overviewDataPrevious?.users ?? 0;
- const currentSessions = overviewData?.data?.sessions ?? 0;
- const previousSessions = overviewDataPrevious?.data?.sessions ?? 0;
+ const currentSessions = overviewData?.sessions ?? 0;
+ const previousSessions = overviewDataPrevious?.sessions ?? 0;
- const currentPageviews = overviewData?.data?.pageviews ?? 0;
- const previousPageviews = overviewDataPrevious?.data?.pageviews ?? 0;
+ const currentPageviews = overviewData?.pageviews ?? 0;
+ const previousPageviews = overviewDataPrevious?.pageviews ?? 0;
- const currentPagesPerSession = overviewData?.data?.pages_per_session ?? 0;
- const previousPagesPerSession = overviewDataPrevious?.data?.pages_per_session ?? 0;
+ const currentPagesPerSession = overviewData?.pages_per_session ?? 0;
+ const previousPagesPerSession = overviewDataPrevious?.pages_per_session ?? 0;
- const currentBounceRate = overviewData?.data?.bounce_rate ?? 0;
- const previousBounceRate = overviewDataPrevious?.data?.bounce_rate ?? 0;
+ const currentBounceRate = overviewData?.bounce_rate ?? 0;
+ const previousBounceRate = overviewDataPrevious?.bounce_rate ?? 0;
- const currentSessionDuration = overviewData?.data?.session_duration ?? 0;
- const previousSessionDuration = overviewDataPrevious?.data?.session_duration ?? 0;
+ const currentSessionDuration = overviewData?.session_duration ?? 0;
+ const previousSessionDuration = overviewDataPrevious?.session_duration ?? 0;
return (
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-0 items-center">
diff --git a/client/src/app/[site]/main/components/MainSection/OverviewLite.tsx b/client/src/app/[site]/main/components/MainSection/OverviewLite.tsx
index 46c8a5149..02cf5831e 100644
--- a/client/src/app/[site]/main/components/MainSection/OverviewLite.tsx
+++ b/client/src/app/[site]/main/components/MainSection/OverviewLite.tsx
@@ -53,7 +53,7 @@ const Stat = ({
const { data } = useGetOverviewBucketed({ site, bucket, lite: true });
const sparklinesData =
- data?.data
+ data
?.filter(d => {
if (time.mode === "past-minutes") {
const timestamp = new Date(d.time);
@@ -129,12 +129,12 @@ export function OverviewLite() {
const { data: overviewData, isLoading } = useGetOverview({ site, lite: true });
- const users = overviewData?.data?.users ?? 0;
- const sessions = overviewData?.data?.sessions ?? 0;
- const pageviews = overviewData?.data?.pageviews ?? 0;
- const pagesPerSession = overviewData?.data?.pages_per_session ?? 0;
- const bounceRate = overviewData?.data?.bounce_rate ?? 0;
- const sessionDuration = overviewData?.data?.session_duration ?? 0;
+ const users = overviewData?.users ?? 0;
+ const sessions = overviewData?.sessions ?? 0;
+ const pageviews = overviewData?.pageviews ?? 0;
+ const pagesPerSession = overviewData?.pages_per_session ?? 0;
+ const bounceRate = overviewData?.bounce_rate ?? 0;
+ const sessionDuration = overviewData?.session_duration ?? 0;
const totalTimeSpent = sessionDuration * sessions;
return (
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index 185c8c8e5..556c4652c 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -25,7 +25,7 @@ export function Weekdays() {
// Generate aggregated data for the heatmap
const heatmapData = useMemo(() => {
- if (!data?.data) return [];
+ if (!data) return [];
// Initialize a 2D array for days (0-6) and hours (0-23)
const aggregated: number[][] = Array(7)
@@ -38,7 +38,7 @@ export function Weekdays() {
.map(() => Array(24).fill(0));
// Process each data point
- data.data.forEach(item => {
+ data.forEach(item => {
if (!item || !item.time) return;
// Parse the timestamp in the selected timezone
diff --git a/client/src/app/[site]/pages/components/PageSparklineChart.tsx b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
index 37d04e938..74fa274c3 100644
--- a/client/src/app/[site]/pages/components/PageSparklineChart.tsx
+++ b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
@@ -1,7 +1,6 @@
"use client";
import { GetOverviewBucketedResponse } from "@/api/analytics/endpoints";
-import { APIResponse } from "@/api/types";
import { ChartTooltip } from "@/components/charts/ChartTooltip";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
import { useNivoTheme } from "@/lib/nivo";
@@ -10,7 +9,7 @@ import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
interface PageSparklineChartProps {
- data: APIResponse<GetOverviewBucketedResponse> | undefined;
+ data: GetOverviewBucketedResponse | undefined;
isHovering: boolean;
pageTitle: string;
isLoading: boolean;
@@ -29,7 +28,7 @@ export function PageSparklineChart({ data, isHovering, pageTitle, isLoading }: P
}
// Format the chart data
- const sparklineData = data?.data
+ const sparklineData = data
?.filter(e => {
// Filter out dates from the future
return DateTime.fromSQL(e.time, { zone: timezone }).toUTC() <= DateTime.now();
diff --git a/client/src/app/[site]/pages/components/PagesTable.tsx b/client/src/app/[site]/pages/components/PagesTable.tsx
index 08bc4b9b8..3d62031a9 100644
--- a/client/src/app/[site]/pages/components/PagesTable.tsx
+++ b/client/src/app/[site]/pages/components/PagesTable.tsx
@@ -109,12 +109,12 @@ export function PagesTable() {
periodTime: "previous",
});
- const currentItems = currentResp?.data?.data ?? [];
- const totalCount = currentResp?.data?.totalCount ?? 0;
+ const currentItems = currentResp?.data ?? [];
+ const totalCount = currentResp?.totalCount ?? 0;
const previousByValue = useMemo(() => {
const map = new Map<string, PageTitleItem>();
- for (const item of previousResp?.data?.data ?? []) {
+ for (const item of previousResp?.data ?? []) {
map.set(item.value, item);
}
return map;
diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsx
index b2b0d93c2..6c1d187af 100644
--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx
@@ -109,7 +109,7 @@ export function PerformanceChart() {
PERCENTILES.map(percentile => [percentile, []])
);
- timeSeriesData?.data?.forEach(item => {
+ timeSeriesData?.forEach(item => {
const timestamp = DateTime.fromSQL(item.time, { zone: timezone }).toUTC();
if (timestamp > now) return;
const timestampMs = timestamp.toMillis();
diff --git a/client/src/app/[site]/performance/components/PerformanceOverview.tsx b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
index 3fc85ec31..bfedf7111 100644
--- a/client/src/app/[site]/performance/components/PerformanceOverview.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
@@ -103,8 +103,8 @@ export function PerformanceOverview() {
const isLoading = isOverviewLoading || isOverviewLoadingPrevious;
- const currentData = overviewData?.data ?? {};
- const previousData = overviewDataPrevious?.data ?? {};
+ const currentData = overviewData ?? {};
+ const previousData = overviewDataPrevious ?? {};
// Helper function to get metric value for selected percentile
const getMetricValue = (data: any, metric: PerformanceMetric): number => {
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index 3ef590d57..b67448c07 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -34,7 +34,7 @@ export default function SessionsPage() {
minEvents,
minDuration,
});
- const allSessions = data?.data || [];
+ const allSessions = data || [];
const hasNextPage = allSessions.length > LIMIT;
const sessions = allSessions.slice(0, LIMIT);
const hasPrevPage = page > 1;
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index c5bad992f..16b243f0a 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -68,7 +68,7 @@ export default function UserPage() {
limit: LIMIT + 1,
});
- const allSessions = sessionsData?.data || [];
+ const allSessions = sessionsData || [];
const hasNextPage = allSessions.length > LIMIT;
const sessions = allSessions.slice(0, LIMIT);
const hasPrevPage = page > 1;
@@ -184,7 +184,7 @@ export default function UserPage() {
<UserSidebar
data={data}
isLoading={isLoading}
- sessionCount={sessionCount?.data ?? []}
+ sessionCount={sessionCount ?? []}
isLoadingCalendar={isLoadingCalendar}
getRegionName={getRegionName}
/>
diff --git a/client/src/app/rollup/hooks/useRollupBucketed.ts b/client/src/app/rollup/hooks/useRollupBucketed.ts
index 59fafa3bf..c592e9bfa 100644
--- a/client/src/app/rollup/hooks/useRollupBucketed.ts
+++ b/client/src/app/rollup/hooks/useRollupBucketed.ts
@@ -1,12 +1,8 @@
import { TimeBucket } from "@rybbit/shared";
import { useQueries } from "@tanstack/react-query";
-import {
- fetchOverviewBucketed,
- fetchOverviewBucketedLite,
- GetOverviewBucketedResponse,
-} from "@/api/analytics/endpoints";
-import { buildApiParams } from "@/api/utils";
-import { useStore } from "@/lib/store";
+import { buildAnalyticsRequest, fetchAnalytics } from "@/api/analytics/analyticsRequest";
+import { GetOverviewBucketedResponse } from "@/api/analytics/endpoints";
+import { useAnalyticsContext } from "@/api/analytics/useAnalyticsQuery";
export type RollupSeries = {
siteId: number;
@@ -29,26 +25,18 @@ export function useRollupBucketed({
bucket: TimeBucket;
lite?: boolean;
}): UseRollupBucketedResult {
- const { time, filters, timezone } = useStore();
// Lite endpoints don't accept filters; drop them so the request and the
// query key stay clean.
- const effectiveFilters = lite ? undefined : filters;
- const params = buildApiParams(time, { filters: effectiveFilters });
+ const { context } = useAnalyticsContext({ useFilters: !lite });
+ const request = buildAnalyticsRequest(
+ { path: lite ? "overview-bucketed-lite" : "overview/time-series", params: { bucket } },
+ context
+ );
const queries = useQueries({
queries: siteIds.map((siteId) => ({
- queryKey: [
- lite ? "rollup-overview-bucketed-lite" : "rollup-overview-bucketed",
- siteId,
- time,
- bucket,
- effectiveFilters,
- timezone,
- ],
- queryFn: () => {
- const fetcher = lite ? fetchOverviewBucketedLite : fetchOverviewBucketed;
- return fetcher(siteId, { ...params, bucket });
- },
+ queryKey: ["rollup-overview-bucketed", siteId, request.path, request.params],
+ queryFn: () => fetchAnalytics<GetOverviewBucketedResponse>(siteId, request),
staleTime: 60_000,
})),
});
diff --git a/client/src/app/rollup/hooks/useRollupMetric.ts b/client/src/app/rollup/hooks/useRollupMetric.ts
index 35568947f..13cb214ec 100644
--- a/client/src/app/rollup/hooks/useRollupMetric.ts
+++ b/client/src/app/rollup/hooks/useRollupMetric.ts
@@ -1,13 +1,9 @@
import { FilterParameter } from "@rybbit/shared";
import { useQueries } from "@tanstack/react-query";
import { useMemo } from "react";
-import {
- fetchMetric,
- fetchMetricLite,
- MetricResponse,
-} from "@/api/analytics/endpoints";
-import { buildApiParams } from "@/api/utils";
-import { useStore } from "@/lib/store";
+import { buildAnalyticsRequest, fetchAnalytics } from "@/api/analytics/analyticsRequest";
+import { MetricResponse } from "@/api/analytics/endpoints";
+import { useAnalyticsContext } from "@/api/analytics/useAnalyticsQuery";
export type RollupMetricRow = MetricResponse;
@@ -29,25 +25,16 @@ export function useRollupMetric({
limit?: number;
lite?: boolean;
}): UseRollupMetricResult {
- const { time, filters, timezone } = useStore();
- const effectiveFilters = lite ? undefined : filters;
- const params = buildApiParams(time, { filters: effectiveFilters });
+ const { context } = useAnalyticsContext({ useFilters: !lite });
+ const request = buildAnalyticsRequest(
+ { path: lite ? "metric-lite" : "metric", params: { parameter, limit, page: 1 } },
+ context
+ );
const queries = useQueries({
queries: siteIds.map((siteId) => ({
- queryKey: [
- lite ? "rollup-metric-lite" : "rollup-metric",
- parameter,
- siteId,
- time,
- effectiveFilters,
- limit,
- timezone,
- ],
- queryFn: () => {
- const fetcher = lite ? fetchMetricLite : fetchMetric;
- return fetcher(siteId, { ...params, parameter, limit, page: 1 });
- },
+ queryKey: ["rollup-metric", siteId, request.path, request.params],
+ queryFn: () => fetchAnalytics<{ data: MetricResponse[]; totalCount: number }>(siteId, request),
staleTime: 60_000,
})),
});
diff --git a/client/src/app/rollup/hooks/useRollupOverview.ts b/client/src/app/rollup/hooks/useRollupOverview.ts
index 6d2d0eaf4..ab9509f53 100644
--- a/client/src/app/rollup/hooks/useRollupOverview.ts
+++ b/client/src/app/rollup/hooks/useRollupOverview.ts
@@ -1,11 +1,7 @@
import { useQueries } from "@tanstack/react-query";
-import {
- fetchOverview,
- fetchOverviewLite,
- GetOverviewResponse,
-} from "@/api/analytics/endpoints";
-import { buildApiParams } from "@/api/utils";
-import { useStore } from "@/lib/store";
+import { buildAnalyticsRequest, fetchAnalytics } from "@/api/analytics/analyticsRequest";
+import { GetOverviewResponse } from "@/api/analytics/endpoints";
+import { useAnalyticsContext } from "@/api/analytics/useAnalyticsQuery";
export type RollupOverview = {
siteId: number;
@@ -36,25 +32,15 @@ export function useRollupOverview({
siteIds: number[];
lite?: boolean;
}): UseRollupOverviewResult {
- const { time, filters, timezone } = useStore();
// Lite endpoints don't accept filters; drop them so the request and the
// query key stay clean.
- const effectiveFilters = lite ? undefined : filters;
- const params = buildApiParams(time, { filters: effectiveFilters });
+ const { context } = useAnalyticsContext({ useFilters: !lite });
+ const request = buildAnalyticsRequest({ path: lite ? "overview-lite" : "overview" }, context);
const queries = useQueries({
queries: siteIds.map((siteId) => ({
- queryKey: [
- lite ? "rollup-overview-lite" : "rollup-overview",
- siteId,
- time,
- effectiveFilters,
- timezone,
- ],
- queryFn: () => {
- const fetcher = lite ? fetchOverviewLite : fetchOverview;
- return fetcher(siteId, params);
- },
+ queryKey: ["rollup-overview", siteId, request.path, request.params],
+ queryFn: () => fetchAnalytics<GetOverviewResponse>(siteId, request),
staleTime: 60_000,
})),
});
diff --git a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
index 5d9a1439b..4b01fc43e 100644
--- a/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails/SessionDetails.tsx
@@ -34,11 +34,11 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
// Flatten all events into a single array
const allEvents = useMemo(() => {
if (!sessionDetailsData?.pages) return [];
- return sessionDetailsData.pages.flatMap((page) => page.data?.events || []);
+ return sessionDetailsData.pages.flatMap((page) => page?.events || []);
}, [sessionDetailsData?.pages]);
// Get session details from the first page
- const sessionDetails = sessionDetailsData?.pages[0]?.data?.session;
+ const sessionDetails = sessionDetailsData?.pages[0]?.session;
// Event type filter state
const [visibleEventTypes, setVisibleEventTypes] = useState<Set<string>>(
@@ -86,7 +86,7 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
{t("Error loading session details. Please try again.")}
</AlertDescription>
</Alert>
- ) : sessionDetailsData?.pages[0]?.data ? (
+ ) : sessionDetailsData?.pages[0] ? (
<Tabs defaultValue="timeline" className="mt-4">
<div className="flex justify-between items-center mb-6">
<TabsList>
@@ -117,7 +117,7 @@ export function SessionDetails({ session, userId, highlightedEventTimestamp }: S
hasNextPage={hasNextPage ?? false}
isFetchingNextPage={isFetchingNextPage}
fetchNextPage={fetchNextPage}
- totalEvents={sessionDetailsData.pages[0]?.data?.pagination?.total ?? 0}
+ totalEvents={sessionDetailsData.pages[0]?.pagination?.total ?? 0}
/>
</TabsContent>
diff --git a/client/src/components/SiteSettings/UsageTab.tsx b/client/src/components/SiteSettings/UsageTab.tsx
index a2622acbe..3be815c61 100644
--- a/client/src/components/SiteSettings/UsageTab.tsx
+++ b/client/src/components/SiteSettings/UsageTab.tsx
@@ -7,7 +7,7 @@ import { ReactNode, useState } from "react";
import { EventCountRow } from "@/api/admin/endpoints/adminServiceEventCount";
import { useGetSiteUsage } from "@/api/admin/hooks/useSites";
import { SiteEventCountPoint } from "@/api/analytics/endpoints";
-import { useGetSiteEventCount } from "@/api/analytics/hooks/useGetSiteEventCount";
+import { useGetSiteEventCountRange } from "@/api/analytics/hooks/useGetSiteEventCountRange";
import { EventUsageChart } from "@/components/EventUsageChart";
import { Skeleton } from "@/components/ui/skeleton";
import { Tabs, TabsList, TabsTrigger } from "@/components/ui/tabs";
@@ -126,7 +126,7 @@ export function UsageTab({ siteId }: UsageTabProps) {
data: eventCounts,
isLoading: chartLoading,
error: chartError,
- } = useGetSiteEventCount({ siteId, startDate, endDate });
+ } = useGetSiteEventCountRange({ siteId, startDate, endDate });
const dayOfMonth = usage ? Math.min(Math.floor(usage.daysElapsed) + 1, usage.daysInMonth) : null;
diff --git a/client/src/lib/store.ts b/client/src/lib/store.ts
index e9d05ffc2..79dbab6e7 100644
--- a/client/src/lib/store.ts
+++ b/client/src/lib/store.ts
@@ -141,6 +141,12 @@ export const getTimezone = () => {
return timezone === "system" ? getSystemTimezone() : timezone;
};
+// Reactive form of getTimezone: re-renders when the user switches timezone.
+export const useTimezone = () => {
+ const timezone = useStore(state => state.timezone);
+ return timezone === "system" ? getSystemTimezone() : timezone;
+};
+
// Helper to convert a DateTime to the user's selected timezone
export const toUserTimezone = (dt: DateTime): DateTime => {
return dt.setZone(getTimezone());