🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Refactor API calls to utilize authedFetchWithError for enhanced error handling
Bill Yangb5dbfef69512
diff --git a/client/src/api/admin/auth.ts b/client/src/api/admin/auth.tsindex 0f0f32f1a..e996a82fb 100644--- a/client/src/api/admin/auth.ts+++ b/client/src/api/admin/auth.ts@@ -1,6 +1,6 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { authedFetchWithError } from "../utils";type GetOrganizationMembersResponse = {data: {@@ -21,9 +21,9 @@ export const useOrganizationMembers = (organizationId: string) => {return useQuery<GetOrganizationMembersResponse>({queryKey: ["organization-members", organizationId],queryFn: () =>- authedFetch(+ authedFetchWithError(`${BACKEND_URL}/list-organization-members/${organizationId}`- ).then((res) => res.json()),+ ),staleTime: Infinity,});};diff --git a/client/src/api/admin/organizations.ts b/client/src/api/admin/organizations.tsindex 934f1d076..66d73f946 100644--- a/client/src/api/admin/organizations.ts+++ b/client/src/api/admin/organizations.ts@@ -1,7 +1,6 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch, authedFetchWithError } from "../utils";-import { APIResponse } from "../types";+import { authedFetchWithError } from "../utils";export type UserOrganization = {id: string;diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.tsindex 4b44d222a..e5850e1ec 100644--- a/client/src/api/admin/sites.ts+++ b/client/src/api/admin/sites.ts@@ -1,7 +1,7 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";import { useStore } from "../../lib/store";-import { authedFetchWithError, genericQuery, useGenericQuery } from "../utils";+import { authedFetchWithError } from "../utils";export type SiteResponse = {siteId: number;@@ -31,11 +31,17 @@ export type GetSitesResponse = {}[];export function useGetSites() {- return useGenericQuery<GetSitesResponse>("get-sites");+ return useQuery<GetSitesResponse>({+ queryKey: ["get-sites"],+ queryFn: () => {+ return authedFetchWithError(`${BACKEND_URL}/get-sites`);+ },+ staleTime: Infinity,+ });}export async function getSites() {- return genericQuery<GetSitesResponse>("get-sites");+ return authedFetchWithError<GetSitesResponse>(`${BACKEND_URL}/get-sites`);}export function addSite(@@ -47,7 +53,7 @@ export function addSite(saltUserIds?: boolean;}) {- return authedFetchWithError(`${BACKEND_URL}/add-site`, {+ return authedFetchWithError<{ siteId: number }>(`${BACKEND_URL}/add-site`, {method: "POST",body: JSON.stringify({domain,@@ -101,9 +107,9 @@ export function useSiteHasData(siteId: string) {if (!siteId) {return Promise.resolve(false);}- return authedFetchWithError(+ return authedFetchWithError<{ hasData: boolean }>(`${BACKEND_URL}/site-has-data/${siteId}`- ).then((data) => data.hasData as Boolean);+ ).then((data) => data.hasData);},refetchInterval: 5000,staleTime: Infinity,@@ -123,18 +129,10 @@ export function useGetSite(siteId?: string | number) {}// Use regular fetch instead of authedFetch to support public sites- return await authedFetchWithError(+ const data = await authedFetchWithError<SiteResponse>(`${BACKEND_URL}/get-site/${siteIdToUse}`);-- // if (!response.ok) {- // if (response.status === 404) {- // return null;- // }- // throw new Error("Failed to fetch site");- // }-- // return response.json() as Promise<SiteResponse>;+ return data;},staleTime: 60000, // 1 minuteenabled: !!siteId,diff --git a/client/src/api/admin/subscription.ts b/client/src/api/admin/subscription.tsindex 2d8b754e5..9cfe0c44c 100644--- a/client/src/api/admin/subscription.ts+++ b/client/src/api/admin/subscription.ts@@ -1,6 +1,6 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { authedFetchWithError } from "../utils";export type Subscription = {id: string;@@ -36,8 +36,10 @@ export function useSubscriptionWithUsage() {return useQuery<SubscriptionWithUsage>({queryKey: ["subscriptionWithUsage"],queryFn: async () => {- const res = await authedFetch(`${BACKEND_URL}/user/subscription`);- return res.json();+ const res = await authedFetchWithError<SubscriptionWithUsage>(+ `${BACKEND_URL}/user/subscription`+ );+ return res;},});}diff --git a/client/src/api/analytics/useDeleteFunnel.ts b/client/src/api/analytics/useDeleteFunnel.tsindex 5412c5360..d1a3eaaf8 100644--- a/client/src/api/analytics/useDeleteFunnel.ts+++ b/client/src/api/analytics/useDeleteFunnel.ts@@ -1,6 +1,6 @@import { useMutation, useQueryClient } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { authedFetchWithError } from "../utils";/*** Hook for deleting a saved funnel report@@ -10,16 +10,17 @@ export function useDeleteFunnel() {return useMutation<{ success: boolean }, Error, number>({mutationFn: async (reportId) => {- const response = await authedFetch(`${BACKEND_URL}/report/${reportId}`, {- method: "DELETE",- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || "Failed to delete funnel");+ try {+ return await authedFetchWithError<{ success: boolean }>(+ `${BACKEND_URL}/report/${reportId}`,+ {+ method: "DELETE",+ }+ );+ } catch (error) {+ console.error(error);+ throw new Error("Failed to delete funnel");}-- return response.json();},onSuccess: () => {// Invalidate the funnels query to refresh the listdiff --git a/client/src/api/analytics/useGetEvents.ts b/client/src/api/analytics/useGetEvents.tsindex 03c844a09..ecc07ad82 100644--- a/client/src/api/analytics/useGetEvents.ts+++ b/client/src/api/analytics/useGetEvents.ts@@ -1,7 +1,7 @@import { useQuery } from "@tanstack/react-query";-import { useStore } from "../../lib/store";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { useStore } from "../../lib/store";+import { authedFetchWithError } from "../utils";export type Event = {timestamp: string;@@ -26,8 +26,8 @@ export function useGetEvents(count = 10) {queryKey: ["events", site, count],refetchInterval: 5000,queryFn: () =>- authedFetch(`${BACKEND_URL}/recent-events/${site}?count=${count}`).then(- (res) => res.json()- ),+ authedFetchWithError<{ data: Event[] }>(+ `${BACKEND_URL}/recent-events/${site}?count=${count}`+ ).then((res) => res.data),});}diff --git a/client/src/api/analytics/useGetFunnel.ts b/client/src/api/analytics/useGetFunnel.tsindex 6b2283a23..5edd4fddf 100644--- a/client/src/api/analytics/useGetFunnel.ts+++ b/client/src/api/analytics/useGetFunnel.ts@@ -1,6 +1,6 @@import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { authedFetch, authedFetchWithError } from "../utils";import { useStore, Filter } from "../../lib/store";import { useDebounce } from "@uidotdev/usehooks";@@ -45,7 +45,7 @@ export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {const configToUse = debounce ? debouncedConfig : config;- return useQuery<{ data: FunnelResponse[] }, Error>({+ return useQuery<FunnelResponse[], Error>({queryKey: ["funnel",site,@@ -66,21 +66,22 @@ export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {...configToUse,timezone,};-- const response = await authedFetch(`${BACKEND_URL}/funnel/${site}`, {- method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(fullConfig),- });-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || "Failed to analyze funnel");+ try {+ const response = await authedFetchWithError<{ data: FunnelResponse[] }>(+ `${BACKEND_URL}/funnel/${site}`,+ {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ },+ body: JSON.stringify(fullConfig),+ }+ );++ return response.data;+ } catch (error) {+ throw new Error("Failed to analyze funnel");}-- return response.json();},enabled: !!site && !!configToUse,});@@ -106,27 +107,26 @@ export function useSaveFunnel() {timezone,};- // Save the funnel configuration- const saveResponse = await authedFetch(- `${BACKEND_URL}/funnel/create/${site}`,- {+ try {+ // Save the funnel configuration+ const saveResponse = await authedFetchWithError<{+ success: boolean;+ funnelId: number;+ }>(`${BACKEND_URL}/funnel/create/${site}`, {method: "POST",headers: {"Content-Type": "application/json",},body: JSON.stringify(fullConfig),- }- );+ });- if (!saveResponse.ok) {- const errorData = await saveResponse.json();- throw new Error(errorData.error || "Failed to save funnel");- }-- // Invalidate the funnels query to refresh the list- queryClient.invalidateQueries({ queryKey: ["funnels", site] });+ // Invalidate the funnels query to refresh the list+ queryClient.invalidateQueries({ queryKey: ["funnels", site] });- return saveResponse.json();+ return saveResponse;+ } catch (error) {+ throw new Error("Failed to save funnel");+ }},});}diff --git a/client/src/api/analytics/useGetFunnels.ts b/client/src/api/analytics/useGetFunnels.tsindex 41b6ceb53..d9816c8b8 100644--- a/client/src/api/analytics/useGetFunnels.ts+++ b/client/src/api/analytics/useGetFunnels.ts@@ -1,8 +1,8 @@import { useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";-import { FunnelStep } from "./useGetFunnel";import { Filter } from "../../lib/store";+import { FunnelStep } from "./useGetFunnel";+import { authedFetchWithError } from "../utils";export interface SavedFunnel {id: number;@@ -22,16 +22,14 @@ export function useGetFunnels(siteId?: string | number) {if (!siteId) {return [];}-- const response = await authedFetch(`${BACKEND_URL}/funnels/${siteId}`);-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || "Failed to fetch funnels");+ try {+ const response = await authedFetchWithError<{ data: SavedFunnel[] }>(+ `${BACKEND_URL}/funnels/${siteId}`+ );+ return response.data;+ } catch (error) {+ throw new Error("Failed to fetch funnels");}-- const result = await response.json();- return result.data;},enabled: !!siteId,});diff --git a/client/src/api/analytics/useGetLiveSessionLocations.ts b/client/src/api/analytics/useGetLiveSessionLocations.tsindex 2b2a545ac..fc5f10f00 100644--- a/client/src/api/analytics/useGetLiveSessionLocations.ts+++ b/client/src/api/analytics/useGetLiveSessionLocations.ts@@ -1,7 +1,7 @@import { useQuery } from "@tanstack/react-query";import { useStore } from "../../lib/store";import { BACKEND_URL } from "../../lib/const";-import { authedFetch } from "../utils";+import { authedFetchWithError } from "../utils";export type LiveSessionLocation = {lat: number;@@ -15,10 +15,8 @@ export function useGetLiveSessionLocations(minutes = 5) {return useQuery<LiveSessionLocation[]>({queryKey: ["live-session-locations", site, minutes],queryFn: () =>- authedFetch(+ authedFetchWithError(`${BACKEND_URL}/live-session-locations/${site}?time=${minutes}`- )- .then((res) => res.json())- .then((data) => data.data),+ ).then((res: any) => res.data),});}diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.tsindex 0cea97c5c..9874f1925 100644--- a/client/src/api/analytics/userSessions.ts+++ b/client/src/api/analytics/userSessions.ts@@ -1,4 +1,4 @@-import { useQuery, useInfiniteQuery } from "@tanstack/react-query";+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { BACKEND_URL } from "../../lib/const";import {getFilteredFilters,@@ -6,7 +6,7 @@ import {useStore,} from "../../lib/store";import { APIResponse } from "../types";-import { getStartAndEndDate, authedFetch } from "../utils";+import { authedFetch, getStartAndEndDate } from "../utils";export type UserSessionsResponse = {session_id: string;@@ -144,27 +144,6 @@ export interface SessionPageviewsAndEvents {};}-export function useGetSessionDetails(- sessionId: string | null,- limit = 100,- offset = 0-) {- const { site } = useStore();-- return useQuery<APIResponse<SessionPageviewsAndEvents>>({- queryKey: ["session-details", sessionId, site, limit, offset],- queryFn: () => {- if (!sessionId) throw new Error("Session ID is required");-- return authedFetch(- `${BACKEND_URL}/session/${sessionId}/${site}?limit=${limit}&offset=${offset}`- ).then((res) => res.json());- },- enabled: !!sessionId && !!site,- staleTime: Infinity,- });-}-export function useGetSessionDetailsInfinite(sessionId: string | null) {const { site } = useStore();diff --git a/client/src/api/utils.ts b/client/src/api/utils.tsindex b90ab8851..f2aad6f24 100644--- a/client/src/api/utils.ts+++ b/client/src/api/utils.ts@@ -85,10 +85,10 @@ export async function authedFetch(});}-export async function authedFetchWithError(+export async function authedFetchWithError<T>(url: string,opts: RequestInit = {}-) {+): Promise<T> {const res = await fetch(url, {credentials: "include",...opts,@@ -98,19 +98,3 @@ export async function authedFetchWithError(}return res.json();}--export function useGenericQuery<T>(endpoint: string): UseQueryResult<T> {- return useQuery({- queryKey: [endpoint],- queryFn: () => {- return authedFetch(`${BACKEND_URL}/${endpoint}`).then((res) =>- res.json()- );- },- staleTime: Infinity,- });-}--export async function genericQuery<T>(endpoint: string): Promise<T> {- return authedFetch(`${BACKEND_URL}/${endpoint}`).then((res) => res.json());-}diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsxindex 60061e2f0..b2060e335 100644--- a/client/src/app/[site]/funnels/components/Funnel.tsx+++ b/client/src/app/[site]/funnels/components/Funnel.tsx@@ -14,7 +14,7 @@ export type FunnelChartData = {};interface FunnelProps {- data?: { data: FunnelResponse[] };+ data?: FunnelResponse[] | undefined;isError: boolean;error: unknown;isPending: boolean;@@ -32,7 +32,7 @@ export function Funnel({}: FunnelProps) {// Prepare chart dataconst chartData =- data?.data.map((step) => ({+ data?.map((step) => ({stepName: step.step_name,visitors: step.visitors,conversionRate: step.conversion_rate,@@ -62,7 +62,7 @@ export function Funnel({: "Failed to analyze funnel"}</div></div>- ) : data?.data && chartData.length > 0 ? (+ ) : data && chartData.length > 0 ? (<div className="space-y-4">{/* Chart grid and background */}<div className="relative h-[350px]">diff --git a/client/src/app/[site]/funnels/components/FunnelForm.tsx b/client/src/app/[site]/funnels/components/FunnelForm.tsxindex 9d689332d..c216527dd 100644--- a/client/src/app/[site]/funnels/components/FunnelForm.tsx+++ b/client/src/app/[site]/funnels/components/FunnelForm.tsx@@ -1,4 +1,4 @@-import { FunnelStep } from "@/api/analytics/useGetFunnel";+import { FunnelResponse, FunnelStep } from "@/api/analytics/useGetFunnel";import { Time } from "@/components/DateSelector/types";import { Button } from "@/components/ui/button";import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";@@ -16,6 +16,7 @@ import { ThreeDotLoader } from "../../../../components/Loaders";import { Filter } from "../../../../lib/store";import { FilterComponent } from "../../components/shared/Filters/FilterComponent";import { Funnel } from "./Funnel";+import { SavedFunnel } from "../../../../api/analytics/useGetFunnels";interface FunnelFormProps {name: string;@@ -35,7 +36,7 @@ interface FunnelFormProps {isPending: boolean;error: unknown;saveError: unknown;- funnelData: any;+ funnelData?: FunnelResponse[];}export function FunnelForm({@@ -118,7 +119,7 @@ export function FunnelForm({};let funnelArea = null;- if (funnelData?.data && funnelData.data.length) {+ if (funnelData && funnelData.length) {funnelArea = (<Funneldata={funnelData}diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsxindex 036586255..0ebcba88f 100644--- a/client/src/app/[site]/funnels/components/FunnelRow.tsx+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx@@ -230,7 +230,7 @@ export function FunnelRow({ funnel }: FunnelRowProps) {Error loading funnel:{" "}{error instanceof Error ? error.message : "Unknown error"}</div>- ) : data?.data && data.data.length > 0 ? (+ ) : data && data.length > 0 ? (<Funneldata={data}isError={isError}diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsxindex e18931216..464e91680 100644--- a/client/src/app/[site]/funnels/page.tsx+++ b/client/src/app/[site]/funnels/page.tsx@@ -1,14 +1,12 @@"use client";-import { CreateFunnelDialog } from "./components/CreateFunnel";-import { useState, useEffect } from "react";-import { Button } from "@/components/ui/button";-import { useGetFunnels, SavedFunnel } from "@/api/analytics/useGetFunnels";-import { PlusCircle } from "lucide-react";+import { SavedFunnel, useGetFunnels } from "@/api/analytics/useGetFunnels";import { Skeleton } from "@/components/ui/skeleton";import { useStore } from "@/lib/store";-import { FunnelRow } from "./components/FunnelRow";+import { PlusCircle } from "lucide-react";import { MobileSidebar } from "../../../components/MobileSidebar";+import { CreateFunnelDialog } from "./components/CreateFunnel";+import { FunnelRow } from "./components/FunnelRow";export default function FunnelsPage() {const { site } = useStore();diff --git a/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx b/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsxindex b8dc387d4..833bae77a 100644--- a/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx+++ b/client/src/app/[site]/realtime/RealtimeEvents/RealtimeEvents.tsx@@ -169,7 +169,7 @@ export function RealtimeEvents() {return <EventCardSkeleton />;}- if (!data?.data || data.data.length === 0) {+ if (!data || data.length === 0) {return (<div className="text-sm text-gray-400 p-4 text-center">No events recorded yet@@ -182,7 +182,7 @@ export function RealtimeEvents() {className="overflow-y-auto p-2"style={{ height: "calc(100vh - 50px)" }}>- {data.data.map((event: Event, index: number) => (+ {data.map((event: Event, index: number) => (<EventCard key={`${event.timestamp}-${index}`} event={event} />))}</div>diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsxindex cdfe3cf3c..43d8284ab 100644--- a/client/src/app/components/AddSite.tsx+++ b/client/src/app/components/AddSite.tsx@@ -82,15 +82,16 @@ export function AddSite({return;}- const response = await addSite(domain, domain, selectedOrganizationId, {- isPublic,- saltUserIds,- });- if (!response.ok) {- const errorData = await response.json();- setError(errorData.error || "Failed to add site");+ try {+ await addSite(domain, domain, selectedOrganizationId, {+ isPublic,+ saltUserIds,+ });+ } catch (error) {+ setError("Failed to add site");return;}+setOpen(false);refetch();};diff --git a/client/src/app/settings/organizations/components/AddUser.tsx b/client/src/app/settings/organizations/components/AddUser.tsxindex 70d74da4d..87584d303 100644--- a/client/src/app/settings/organizations/components/AddUser.tsx+++ b/client/src/app/settings/organizations/components/AddUser.tsx@@ -1,5 +1,4 @@-import { AlertCircle } from "lucide-react";-import { useState } from "react";+import { authedFetchWithError } from "@/api/utils";import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";import { Button } from "@/components/ui/button";import {@@ -13,8 +12,9 @@ import {import { Input } from "@/components/ui/input";import { Label } from "@/components/ui/label";import { Switch } from "@/components/ui/switch";-import { authedFetch } from "@/api/utils";import { BACKEND_URL } from "@/lib/const";+import { AlertCircle } from "lucide-react";+import { useState } from "react";export function AddUser({ refetch }: { refetch: () => void }) {const [open, setOpen] = useState(false);@@ -36,27 +36,22 @@ export function AddUser({ refetch }: { refetch: () => void }) {return;}try {- const response = await authedFetch(`${BACKEND_URL}/create-account`, {- method: "POST",- body: JSON.stringify({- email,- username,- name: username,- password,- isAdmin,- }),- headers: {- "Content-Type": "application/json",- },- });-- if (response.status !== 201) {- const data = await response.json();- console.info(data);- setError(data.error);- return;- }-+ await authedFetchWithError<{ success: boolean }>(+ `${BACKEND_URL}/create-account`,+ {+ method: "POST",+ body: JSON.stringify({+ email,+ username,+ name: username,+ password,+ isAdmin,+ }),+ headers: {+ "Content-Type": "application/json",+ },+ }+ );setOpen(false);refetch();} catch (error) {diff --git a/client/src/app/signup/page.tsx b/client/src/app/signup/page.tsxindex e3ce70177..45ae76a5a 100644--- a/client/src/app/signup/page.tsx+++ b/client/src/app/signup/page.tsx@@ -53,7 +53,7 @@ export default function SignupPage() {const [domain, setDomain] = useState("");// Step 4: Data for tracking code- const [siteId, setSiteId] = useState("");+ const [siteId, setSiteId] = useState<number>();// Handle organization name change and generate slugconst handleOrgNameChange = (value: string) => {@@ -153,16 +153,13 @@ export default function SignupPage() {return;}- const response = await addSite(domain, domain, organizationId);-- if (!response.ok) {- const errorData = await response.json();- throw new Error(errorData.error || "Failed to add site");+ try {+ const response = await addSite(domain, domain, organizationId);+ setSiteId(response.siteId);+ setCurrentStep(4);+ } catch (error) {+ setError(String(error));}-- const data = await response.json();- setSiteId(data.siteId);- setCurrentStep(4);} catch (error) {setError(String(error));} finally {