Skip to content

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

Refactor error event and name hooks to utilize buildApiParams for cleaner API parameter handling

Bill Yang206a1f66da97
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
index 0d96e48bd..4c4d49ed7 100644
--- a/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
@@ -1,22 +1,17 @@
-import { getTimezone, useStore } from "@/lib/store";
+import { useStore } from "@/lib/store";
import { useInfiniteQuery } from "@tanstack/react-query";
-import { getStartAndEndDate } from "../../../utils";
+import { buildApiParams } from "../../../utils";
import { ErrorEventsPaginatedResponse, fetchErrorEvents } from "../../endpoints";
// Hook for infinite scrolling
export function useGetErrorEventsInfinite(errorMessage: string, enabled: boolean = true) {
const { time, site, filters, timezone } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
-
return useInfiniteQuery({
queryKey: ["error-events-infinite", time, site, filters, errorMessage, timezone],
queryFn: async ({ pageParam = 1 }) => {
const data = await fetchErrorEvents(site, {
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone: getTimezone(),
- filters,
+ ...buildApiParams(time, { filters }),
errorMessage,
limit: 20,
page: pageParam,
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorNames.ts b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
index 63f604d32..cddb6cc0a 100644
--- a/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
@@ -1,12 +1,7 @@
-import { getTimezone, useStore } from "@/lib/store";
+import { useStore } from "@/lib/store";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { getStartAndEndDate } from "../../../utils";
-import {
- fetchErrorNames,
- ErrorNameItem,
- ErrorNamesPaginatedResponse,
- ErrorNamesStandardResponse,
-} from "../../endpoints";
+import { buildApiParams } from "../../../utils";
+import { fetchErrorNames, ErrorNamesPaginatedResponse } from "../../endpoints";
type UseGetErrorNamesOptions = {
limit?: number;
@@ -22,16 +17,11 @@ export function useGetErrorNamesPaginated({
}: UseGetErrorNamesOptions): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
const { time, site, filters, timezone } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
-
return useQuery({
queryKey: ["error-names", time, site, filters, limit, page, useFilters, timezone],
queryFn: async () => {
const data = await fetchErrorNames(site, {
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone: getTimezone(),
- filters: useFilters ? filters : undefined,
+ ...buildApiParams(time, { filters: useFilters ? filters : undefined }),
limit,
page,
});
@@ -48,16 +38,11 @@ export function useGetErrorNames({
}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
const { time, site, filters, timezone } = useStore();
- const { startDate, endDate } = getStartAndEndDate(time);
-
return useQuery({
queryKey: ["error-names", time, site, filters, limit, timezone],
queryFn: async () => {
const data = await fetchErrorNames(site, {
- startDate: startDate ?? "",
- endDate: endDate ?? "",
- timeZone: getTimezone(),
- filters: useFilters ? filters : undefined,
+ ...buildApiParams(time, { filters: useFilters ? filters : undefined }),
limit,
});
return { data };
diff --git a/client/src/api/gsc/hooks/useGetGSCData.ts b/client/src/api/gsc/hooks/useGetGSCData.ts
index 5967dfa53..cfe79e0d5 100644
--- a/client/src/api/gsc/hooks/useGetGSCData.ts
+++ b/client/src/api/gsc/hooks/useGetGSCData.ts
@@ -1,23 +1,45 @@
import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { buildApiParams } from "../../utils";
-import { toQueryParams } from "../../analytics/endpoints/types";
+import { DateTime } from "luxon";
+import { Time } from "../../../components/DateSelector/types";
+import { getTimezone, useStore } from "../../../lib/store";
+import { getStartAndEndDate } from "../../utils";
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 ?? "" };
+}
+
/**
* Hook to fetch data from Google Search Console for a specific dimension
*/
export function useGetGSCData(dimension: GSCDimension) {
const { site, time, timezone } = useStore();
- const timeParams = toQueryParams(buildApiParams(time));
+ const { startDate, endDate } = getGSCDateRange(time);
return useQuery({
- queryKey: ["gsc-data", dimension, site, timeParams, timezone],
+ queryKey: ["gsc-data", dimension, site, startDate, endDate, timezone],
queryFn: () => {
return fetchGSCData(site!, {
dimension,
- startDate: timeParams.start_date,
- endDate: timeParams.end_date,
+ startDate,
+ endDate,
timeZone: timezone,
});
},
diff --git a/server/src/api/analytics/sessions/getSessions.ts b/server/src/api/analytics/sessions/getSessions.ts
index e53a8d0bb..bd078fffb 100644
--- a/server/src/api/analytics/sessions/getSessions.ts
+++ b/server/src/api/analytics/sessions/getSessions.ts
@@ -97,10 +97,12 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:
const timeStatement = getTimeStatement(req.query);
// Use composable filter options:
- // - sessionLevelParams: pathname and page_title filter at session level (finds sessions that visited a page)
+ // - sessionLevelParams: per-event fields filter at session level (finds sessions
+ // containing a matching event) — required for any parameter the aggregated CTE
+ // below doesn't project, otherwise the outer WHERE hits an unknown identifier
// - fieldMappings: CTE extracts UTM params as separate columns, so we need to map the field names
const filterStatement = getFilterStatement(filters, Number(site), timeStatement, {
- sessionLevelParams: ["event_name", "pathname", "page_title", "channel"],
+ sessionLevelParams: ["event_name", "pathname", "page_title", "querystring", "channel"],
fieldMappings: SESSION_FIELD_MAPPINGS,
});
@@ -145,7 +147,8 @@ export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res:
argMax(ip, timestamp) AS ip,
argMax(lat, timestamp) AS lat,
argMax(lon, timestamp) AS lon,
- argMax(tag, timestamp) AS tag
+ argMax(tag, timestamp) AS tag,
+ argMax(timezone, timestamp) AS timezone
FROM events
WHERE
site_id = {siteId:Int32}
diff --git a/server/src/api/analytics/users/getUsers.ts b/server/src/api/analytics/users/getUsers.ts
index 587b272e4..43360eb92 100644
--- a/server/src/api/analytics/users/getUsers.ts
+++ b/server/src/api/analytics/users/getUsers.ts
@@ -99,6 +99,10 @@ export async function getUsers(req: FastifyRequest<GetUsersRequest>, res: Fastif
// Generate filter statement and time statement
const timeStatement = getTimeStatement(req.query);
+ // Applied inside the CTE against raw events (same placement as the count
+ // queries): the aggregate doesn't project every filterable column
+ // (pathname, querystring, utm_*, …), and event-level placement keeps the
+ // returned rows consistent with totalCount.
const filterStatement = getFilterStatement(filters, Number(site), timeStatement);
const query = `
@@ -132,6 +136,7 @@ WITH AggregatedUsers AS (
WHERE
site_id = {siteId:Int32}
${timeStatement}
+ ${filterStatement}
${matchingUserIds ? "AND events.identified_user_id IN ({matchingUserIds:Array(String)})" : ""}
GROUP BY
effective_user_id
@@ -139,7 +144,7 @@ WITH AggregatedUsers AS (
SELECT
*
FROM AggregatedUsers
-WHERE 1 = 1 ${filterStatement}
+WHERE 1 = 1
${filterIdentified ? "AND identified_user_id != ''" : ""}
ORDER BY ${actualSortBy} ${actualSortOrder}
LIMIT {limit:Int32} OFFSET {offset:Int32}
diff --git a/server/src/api/analytics/utils/query-validation.ts b/server/src/api/analytics/utils/query-validation.ts
index 7e1f81d7c..13d4efcc6 100644
--- a/server/src/api/analytics/utils/query-validation.ts
+++ b/server/src/api/analytics/utils/query-validation.ts
@@ -415,10 +415,16 @@ const httpTimeParamsSchema = z
/**
* Returns an error message if the request's time query params are present but
- * invalid, or null if they are valid or absent.
+ * invalid, or null if they are valid or absent. Empty-string values count as
+ * absent: the dashboard sends `start_date=&end_date=` in all-time mode, and
+ * `?param=` in a query string has always meant "no value" to these endpoints.
*/
export function validateHttpTimeParams(query: unknown): string | null {
- const result = httpTimeParamsSchema.safeParse(query ?? {});
+ const withoutEmpty =
+ typeof query === "object" && query !== null
+ ? Object.fromEntries(Object.entries(query).filter(([, value]) => value !== ""))
+ : {};
+ const result = httpTimeParamsSchema.safeParse(withoutEmpty);
if (result.success) {
return null;
}
diff --git a/server/src/api/sites/getSitesFromOrg.ts b/server/src/api/sites/getSitesFromOrg.ts
index ef898123a..94c9c9521 100644
--- a/server/src/api/sites/getSitesFromOrg.ts
+++ b/server/src/api/sites/getSitesFromOrg.ts
@@ -111,8 +111,11 @@ export async function getSitesFromOrg(
siteTeamMap.set(mapping.siteId, existing);
}
- // Enhance sites data with session counts and subscription info
- const enhancedSitesData = sitesData.map(site => ({
+ // Enhance sites data with session counts and subscription info.
+ // apiKey and privateLinkKey are secrets (ingestion auth / private-link
+ // dashboard access) and must not be exposed to org members here — the
+ // client reads them from the admin-gated per-site endpoints instead.
+ const enhancedSitesData = sitesData.map(({ apiKey, privateLinkKey, ...site }) => ({
...site,
type: site.type || "web",
domain: site.domain || "",