🐸 Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Enhance API utility functions to use axios for HTTP requests (#387)
Bill Yanga134d746aa7a
diff --git a/client/package-lock.json b/client/package-lock.jsonindex 4d5888fe7..250a7f31d 100644--- a/client/package-lock.json+++ b/client/package-lock.json@@ -40,6 +40,7 @@"@types/country-flag-icons": "1.2.2","@types/three": "0.176.0","@uidotdev/usehooks": "2.4.1",+ "axios": "^1.9.0","better-auth": "1.2.7","boring-avatars": "1.11.2","class-variance-authority": "0.7.1",@@ -5434,6 +5435,21 @@"node": ">=8"}},+ "node_modules/asynckit": {+ "version": "0.4.0",+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q=="+ },+ "node_modules/axios": {+ "version": "1.9.0",+ "resolved": "https://registry.npmjs.org/axios/-/axios-1.9.0.tgz",+ "integrity": "sha512-re4CqKTJaURpzbLHtIi6XpDv20/CnpXOtjRY5/CU32L8gU8ek9UIivcfvSWvmKEngmVbrUtPpdDwWDWL7DNHvg==",+ "dependencies": {+ "follow-redirects": "^1.15.6",+ "form-data": "^4.0.0",+ "proxy-from-env": "^1.1.0"+ }+ },"node_modules/babel-plugin-macros": {"version": "3.1.0","resolved": "https://registry.npmjs.org/babel-plugin-macros/-/babel-plugin-macros-3.1.0.tgz",@@ -5639,6 +5655,18 @@"node": ">=10.16.0"}},+ "node_modules/call-bind-apply-helpers": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",+ "integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",+ "dependencies": {+ "es-errors": "^1.3.0",+ "function-bind": "^1.1.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/callsites": {"version": "3.1.0","resolved": "https://registry.npmjs.org/callsites/-/callsites-3.1.0.tgz",@@ -5856,6 +5884,17 @@"simple-swizzle": "^0.2.2"}},+ "node_modules/combined-stream": {+ "version": "1.0.8",+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",+ "dependencies": {+ "delayed-stream": "~1.0.0"+ },+ "engines": {+ "node": ">= 0.8"+ }+ },"node_modules/commander": {"version": "7.2.0","resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",@@ -6511,6 +6550,14 @@"robust-predicates": "^3.0.2"}},+ "node_modules/delayed-stream": {+ "version": "1.0.0",+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",+ "engines": {+ "node": ">=0.4.0"+ }+ },"node_modules/deps": {"version": "1.0.0","resolved": "https://registry.npmjs.org/deps/-/deps-1.0.0.tgz",@@ -6615,6 +6662,19 @@"drizzle-kit": "bin.cjs"}},+ "node_modules/dunder-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",+ "integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.1",+ "es-errors": "^1.3.0",+ "gopd": "^1.2.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/earcut": {"version": "3.0.1","resolved": "https://registry.npmjs.org/earcut/-/earcut-3.0.1.tgz",@@ -6657,6 +6717,47 @@"is-arrayish": "^0.2.1"}},+ "node_modules/es-define-property": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/es-define-property/-/es-define-property-1.0.1.tgz",+ "integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-errors": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-object-atoms": {+ "version": "1.1.1",+ "resolved": "https://registry.npmjs.org/es-object-atoms/-/es-object-atoms-1.1.1.tgz",+ "integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",+ "dependencies": {+ "es-errors": "^1.3.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },+ "node_modules/es-set-tostringtag": {+ "version": "2.1.0",+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",+ "dependencies": {+ "es-errors": "^1.3.0",+ "get-intrinsic": "^1.2.6",+ "has-tostringtag": "^1.0.2",+ "hasown": "^2.0.2"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/esbuild": {"version": "0.25.4","resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.25.4.tgz",@@ -6830,6 +6931,25 @@"node": ">=12"}},+ "node_modules/follow-redirects": {+ "version": "1.15.9",+ "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.9.tgz",+ "integrity": "sha512-gew4GsXizNgdoRyqmyfMHyAmXsZDk6mHkSxZFCzW9gwlbtOW44CDtYavM+y+72qD/Vq2l550kMF52DT8fOLJqQ==",+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/RubenVerborgh"+ }+ ],+ "engines": {+ "node": ">=4.0"+ },+ "peerDependenciesMeta": {+ "debug": {+ "optional": true+ }+ }+ },"node_modules/foreground-child": {"version": "3.3.1","resolved": "https://registry.npmjs.org/foreground-child/-/foreground-child-3.3.1.tgz",@@ -6860,6 +6980,21 @@"url": "https://github.com/sponsors/isaacs"}},+ "node_modules/form-data": {+ "version": "4.0.3",+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.3.tgz",+ "integrity": "sha512-qsITQPfmvMOSAdeyZ+12I1c+CKSstAFAwu+97zrnWAbIr5u8wfsExUzCesVLC8NgHuRUqNN4Zy6UPWUTRGslcA==",+ "dependencies": {+ "asynckit": "^0.4.0",+ "combined-stream": "^1.0.8",+ "es-set-tostringtag": "^2.1.0",+ "hasown": "^2.0.2",+ "mime-types": "^2.1.12"+ },+ "engines": {+ "node": ">= 6"+ }+ },"node_modules/frame-ticker": {"version": "1.0.3","resolved": "https://registry.npmjs.org/frame-ticker/-/frame-ticker-1.0.3.tgz",@@ -6942,6 +7077,29 @@"node": ">= 0.10"}},+ "node_modules/get-intrinsic": {+ "version": "1.3.0",+ "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",+ "integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",+ "dependencies": {+ "call-bind-apply-helpers": "^1.0.2",+ "es-define-property": "^1.0.1",+ "es-errors": "^1.3.0",+ "es-object-atoms": "^1.1.1",+ "function-bind": "^1.1.2",+ "get-proto": "^1.0.1",+ "gopd": "^1.2.0",+ "has-symbols": "^1.1.0",+ "hasown": "^2.0.2",+ "math-intrinsics": "^1.1.0"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/get-nonce": {"version": "1.0.1","resolved": "https://registry.npmjs.org/get-nonce/-/get-nonce-1.0.1.tgz",@@ -6951,6 +7109,18 @@"node": ">=6"}},+ "node_modules/get-proto": {+ "version": "1.0.1",+ "resolved": "https://registry.npmjs.org/get-proto/-/get-proto-1.0.1.tgz",+ "integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",+ "dependencies": {+ "dunder-proto": "^1.0.1",+ "es-object-atoms": "^1.0.0"+ },+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/get-stream": {"version": "5.2.0","resolved": "https://registry.npmjs.org/get-stream/-/get-stream-5.2.0.tgz",@@ -7062,6 +7232,17 @@"integrity": "sha512-b/ZCF6amfAUb7dJM/MxRs7AetQEahYzJ8PtgfrmEdtw6uyGOr+ZSGtgjFm6mfsBkxJ4d2W7kg+Nlqzqvn3Bc0w==","license": "MIT"},+ "node_modules/gopd": {+ "version": "1.2.0",+ "resolved": "https://registry.npmjs.org/gopd/-/gopd-1.2.0.tgz",+ "integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/graceful-fs": {"version": "4.2.11","resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",@@ -7088,6 +7269,31 @@"node": ">=8"}},+ "node_modules/has-symbols": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/has-symbols/-/has-symbols-1.1.0.tgz",+ "integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },+ "node_modules/has-tostringtag": {+ "version": "1.0.2",+ "resolved": "https://registry.npmjs.org/has-tostringtag/-/has-tostringtag-1.0.2.tgz",+ "integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",+ "dependencies": {+ "has-symbols": "^1.0.3"+ },+ "engines": {+ "node": ">= 0.4"+ },+ "funding": {+ "url": "https://github.com/sponsors/ljharb"+ }+ },"node_modules/hasown": {"version": "2.0.2","resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.2.tgz",@@ -7607,6 +7813,14 @@"three": ">=0.134.0"}},+ "node_modules/math-intrinsics": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",+ "integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",+ "engines": {+ "node": ">= 0.4"+ }+ },"node_modules/memoize-one": {"version": "6.0.0","resolved": "https://registry.npmjs.org/memoize-one/-/memoize-one-6.0.0.tgz",@@ -7656,6 +7870,25 @@"node": ">=8.6"}},+ "node_modules/mime-db": {+ "version": "1.52.0",+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",+ "engines": {+ "node": ">= 0.6"+ }+ },+ "node_modules/mime-types": {+ "version": "2.1.35",+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",+ "dependencies": {+ "mime-db": "1.52.0"+ },+ "engines": {+ "node": ">= 0.6"+ }+ },"node_modules/mimic-fn": {"version": "2.1.0","resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz",@@ -8303,6 +8536,11 @@"react-is": "^16.13.1"}},+ "node_modules/proxy-from-env": {+ "version": "1.1.0",+ "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz",+ "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg=="+ },"node_modules/pump": {"version": "3.0.2","resolved": "https://registry.npmjs.org/pump/-/pump-3.0.2.tgz",diff --git a/client/package.json b/client/package.jsonindex 381c54bc5..f9bd73aad 100644--- a/client/package.json+++ b/client/package.json@@ -9,7 +9,6 @@"lint": "next lint"},"dependencies": {- "@rybbit/shared": "file:../shared","@better-auth/stripe": "1.2.7","@hookform/resolvers": "5.0.1","@nivo/bar": "0.96.0",@@ -35,12 +34,14 @@"@radix-ui/themes": "3.2.1","@react-three/drei": "10.0.7","@react-three/fiber": "9.1.2",+ "@rybbit/shared": "file:../shared","@tanstack/react-query": "5.76.0","@tanstack/react-query-devtools": "5.76.0","@tanstack/react-table": "8.21.3","@types/country-flag-icons": "1.2.2","@types/three": "0.176.0","@uidotdev/usehooks": "2.4.1",+ "axios": "^1.9.0","better-auth": "1.2.7","boring-avatars": "1.11.2","class-variance-authority": "0.7.1",@@ -50,6 +51,7 @@"country-flag-icons": "1.5.19","d3": "7.9.0","d3-geo": "3.1.1",+ "date-fns": "^4.1.0","deps": "1.0.0","framer-motion": "12.11.0","geojson": "0.5.0",@@ -65,7 +67,6 @@"react": "19.1.0","react-countup": "6.5.3","react-day-picker": "^8.10.1",- "date-fns": "^4.1.0","react-dom": "19.1.0","react-globe.gl": "2.33.2","react-hook-form": "7.56.3",diff --git a/client/src/api/admin/auth.ts b/client/src/api/admin/auth.tsindex e996a82fb..58e323823 100644--- a/client/src/api/admin/auth.ts+++ b/client/src/api/admin/auth.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";type GetOrganizationMembersResponse = {data: {@@ -20,10 +19,7 @@ type GetOrganizationMembersResponse = {export const useOrganizationMembers = (organizationId: string) => {return useQuery<GetOrganizationMembersResponse>({queryKey: ["organization-members", organizationId],- queryFn: () =>- authedFetchWithError(- `${BACKEND_URL}/list-organization-members/${organizationId}`- ),+ queryFn: () => authedFetch(`/list-organization-members/${organizationId}`),staleTime: Infinity,});};diff --git a/client/src/api/admin/getAdminOrganizations.ts b/client/src/api/admin/getAdminOrganizations.tsindex 2e2700d94..ef035d523 100644--- a/client/src/api/admin/getAdminOrganizations.ts+++ b/client/src/api/admin/getAdminOrganizations.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export interface AdminOrganizationData {id: string;@@ -34,9 +33,7 @@ export interface AdminOrganizationData {}export async function getAdminOrganizations() {- return authedFetchWithError<AdminOrganizationData[]>(- `${BACKEND_URL}/admin/organizations`- );+ return authedFetch<AdminOrganizationData[]>("/admin/organizations");}export function useAdminOrganizations() {diff --git a/client/src/api/admin/getAdminSites.ts b/client/src/api/admin/getAdminSites.tsindex 81c8557fa..fe65ddb4a 100644--- a/client/src/api/admin/getAdminSites.ts+++ b/client/src/api/admin/getAdminSites.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export interface AdminSiteData {siteId: number;@@ -12,7 +11,7 @@ export interface AdminSiteData {}export async function getAdminSites() {- return authedFetchWithError<AdminSiteData[]>(`${BACKEND_URL}/admin/sites`);+ return authedFetch<AdminSiteData[]>("/admin/sites");}export function useAdminSites() {diff --git a/client/src/api/admin/organizations.ts b/client/src/api/admin/organizations.tsindex 691d9c3ac..138dad14e 100644--- a/client/src/api/admin/organizations.ts+++ b/client/src/api/admin/organizations.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { authClient } from "../../lib/auth";export type UserOrganization = {@@ -14,7 +13,7 @@ export type UserOrganization = {};function getUserOrganizations(): Promise<UserOrganization[]> {- return authedFetchWithError(`${BACKEND_URL}/user/organizations`);+ return authedFetch("/user/organizations");}export function useUserOrganizations() {diff --git a/client/src/api/admin/sites.ts b/client/src/api/admin/sites.tsindex 238c9176c..229f25337 100644--- a/client/src/api/admin/sites.ts+++ b/client/src/api/admin/sites.ts@@ -1,7 +1,6 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { useStore } from "../../lib/store";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { usePathname } from "next/navigation";import { authClient } from "../../lib/auth";@@ -74,9 +73,7 @@ export function useGetSitesFromOrg(organizationId?: string) {return useQuery<GetSitesFromOrgResponse>({queryKey: ["get-sites-from-org", organizationId],queryFn: () => {- return authedFetchWithError(- `${BACKEND_URL}/get-sites-from-org/${organizationId}`- );+ return authedFetch(`/get-sites-from-org/${organizationId}`);},staleTime: 60000, // 1 minuteenabled: !!organizationId,@@ -93,16 +90,16 @@ export function addSite(blockBots?: boolean;}) {- return authedFetchWithError<{ siteId: number }>(`${BACKEND_URL}/add-site`, {+ return authedFetch<{ siteId: number }>("/add-site", undefined, {method: "POST",- body: JSON.stringify({+ data: {domain,name,organizationId,public: settings?.isPublic || false,saltUserIds: settings?.saltUserIds || false,blockBots: settings?.blockBots === undefined ? true : settings?.blockBots,- }),+ },headers: {"Content-Type": "application/json",},@@ -110,18 +107,18 @@ export function addSite(}export function deleteSite(siteId: number) {- return authedFetchWithError(`${BACKEND_URL}/delete-site/${siteId}`, {+ return authedFetch(`/delete-site/${siteId}`, undefined, {method: "POST",});}export function changeSiteDomain(siteId: number, newDomain: string) {- return authedFetchWithError(`${BACKEND_URL}/change-site-domain`, {+ return authedFetch("/change-site-domain", undefined, {method: "POST",- body: JSON.stringify({+ data: {siteId,newDomain,- }),+ },headers: {"Content-Type": "application/json",},@@ -129,12 +126,12 @@ export function changeSiteDomain(siteId: number, newDomain: string) {}export function changeSitePublic(siteId: number, isPublic: boolean) {- return authedFetchWithError(`${BACKEND_URL}/change-site-public`, {+ return authedFetch("/change-site-public", undefined, {method: "POST",- body: JSON.stringify({+ data: {siteId,isPublic,- }),+ },headers: {"Content-Type": "application/json",},@@ -148,9 +145,9 @@ export function useSiteHasData(siteId: string) {if (!siteId) {return Promise.resolve(false);}- return authedFetchWithError<{ hasData: boolean }>(- `${BACKEND_URL}/site-has-data/${siteId}`- ).then((data) => data.hasData);+ return authedFetch<{ hasData: boolean }>(`/site-has-data/${siteId}`).then(+ (data) => data.hasData+ );},refetchInterval: 5000,staleTime: Infinity,@@ -170,9 +167,7 @@ export function useGetSite(siteId?: string | number) {}// Use regular fetch instead of authedFetch to support public sites- const data = await authedFetchWithError<SiteResponse>(- `${BACKEND_URL}/get-site/${siteIdToUse}`- );+ const data = await authedFetch<SiteResponse>(`/get-site/${siteIdToUse}`);return data;},staleTime: 60000, // 1 minute@@ -181,12 +176,12 @@ export function useGetSite(siteId?: string | number) {}export function changeSiteSalt(siteId: number, saltUserIds: boolean) {- return authedFetchWithError(`${BACKEND_URL}/change-site-salt`, {+ return authedFetch("/change-site-salt", undefined, {method: "POST",- body: JSON.stringify({+ data: {siteId,saltUserIds,- }),+ },headers: {"Content-Type": "application/json",},@@ -194,12 +189,12 @@ export function changeSiteSalt(siteId: number, saltUserIds: boolean) {}export function changeSiteBlockBots(siteId: number, blockBots: boolean) {- return authedFetchWithError(`${BACKEND_URL}/change-site-block-bots`, {+ return authedFetch("/change-site-block-bots", undefined, {method: "POST",- body: JSON.stringify({+ data: {siteId,blockBots,- }),+ },headers: {"Content-Type": "application/json",},@@ -215,15 +210,14 @@ export function useGetSiteIsPublic(siteId?: string | number) {}try {- const response = await fetch(`${BACKEND_URL}/site-is-public/${siteId}`);- if (response.ok) {- const data = await response.json();- return !!data.isPublic;- }+ const data = await authedFetch<{ isPublic: boolean }>(+ `/site-is-public/${siteId}`+ );+ return !!data.isPublic;} catch (error) {console.error("Error checking if site is public:", error);+ return false;}- return false;},staleTime: 60000, // 1 minuteenabled: !!siteId,diff --git a/client/src/api/analytics/useCreateGoal.ts b/client/src/api/analytics/useCreateGoal.tsindex 096bf033a..ae9dfc31c 100644--- a/client/src/api/analytics/useCreateGoal.ts+++ b/client/src/api/analytics/useCreateGoal.ts@@ -1,6 +1,5 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export interface CreateGoalRequest {siteId: number;@@ -25,14 +24,12 @@ export function useCreateGoal() {return useMutation<CreateGoalResponse, Error, CreateGoalRequest>({mutationFn: async (goalData) => {try {- return await authedFetchWithError<CreateGoalResponse>(- `${BACKEND_URL}/goal/create`,+ return await authedFetch<CreateGoalResponse>(+ "/goal/create",+ undefined,{method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(goalData),+ data: goalData,});} catch (error) {diff --git a/client/src/api/analytics/useDeleteFunnel.ts b/client/src/api/analytics/useDeleteFunnel.tsindex 89226c329..2d49be246 100644--- a/client/src/api/analytics/useDeleteFunnel.ts+++ b/client/src/api/analytics/useDeleteFunnel.ts@@ -1,6 +1,5 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";/*** Hook for deleting a saved funnel report@@ -11,8 +10,9 @@ export function useDeleteFunnel() {return useMutation<{ success: boolean }, Error, number>({mutationFn: async (reportId) => {try {- return await authedFetchWithError<{ success: boolean }>(- `${BACKEND_URL}/funnel/${reportId}`,+ return await authedFetch<{ success: boolean }>(+ `/funnel/${reportId}`,+ undefined,{method: "DELETE",}diff --git a/client/src/api/analytics/useDeleteGoal.ts b/client/src/api/analytics/useDeleteGoal.tsindex 31f8f1e36..b45293072 100644--- a/client/src/api/analytics/useDeleteGoal.ts+++ b/client/src/api/analytics/useDeleteGoal.ts@@ -1,6 +1,5 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { useStore } from "../../lib/store";export function useDeleteGoal() {@@ -10,8 +9,9 @@ export function useDeleteGoal() {return useMutation<{ success: boolean }, Error, number>({mutationFn: async (goalId: number) => {try {- return await authedFetchWithError<{ success: boolean }>(- `${BACKEND_URL}/goal/${goalId}`,+ return await authedFetch<{ success: boolean }>(+ `/goal/${goalId}`,+ undefined,{method: "DELETE",}diff --git a/client/src/api/analytics/useGetEventNames.ts b/client/src/api/analytics/useGetEventNames.tsindex e628717e7..0a164dcae 100644--- a/client/src/api/analytics/useGetEventNames.ts+++ b/client/src/api/analytics/useGetEventNames.ts@@ -1,9 +1,7 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { useStore, getFilteredFilters, EVENT_FILTERS } from "../../lib/store";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { getQueryTimeParams } from "./utils";-import { buildUrl } from "../utils";export type EventName = {eventName: string;@@ -20,14 +18,15 @@ export function useGetEventNames() {queryKey: ["event-names", site, timeParams, filteredFilters],enabled: !!site,queryFn: () => {- const url = buildUrl(`${BACKEND_URL}/events/names/${site}`, {+ const params = {...Object.fromEntries(new URLSearchParams(timeParams)),filters: filteredFilters.length > 0 ? filteredFilters : undefined,- });+ };- return authedFetchWithError<{ data: EventName[] }>(url).then(- (res) => res.data- );+ return authedFetch<{ data: EventName[] }>(+ `/events/names/${site}`,+ params+ ).then((res) => res.data);},});}diff --git a/client/src/api/analytics/useGetEventProperties.ts b/client/src/api/analytics/useGetEventProperties.tsindex efa009a69..f55f62dc9 100644--- a/client/src/api/analytics/useGetEventProperties.ts+++ b/client/src/api/analytics/useGetEventProperties.ts@@ -1,9 +1,7 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { useStore, getFilteredFilters, EVENT_FILTERS } from "../../lib/store";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { getQueryTimeParams } from "./utils";-import { buildUrl } from "../utils";export type EventProperty = {propertyKey: string;@@ -27,15 +25,16 @@ export function useGetEventProperties(eventName: string | null) {],enabled: !!site && !!eventName,queryFn: () => {- const url = buildUrl(`${BACKEND_URL}/events/properties/${site}`, {+ const params = {...Object.fromEntries(new URLSearchParams(timeParams)),eventName,filters: filteredFilters.length > 0 ? filteredFilters : undefined,- });+ };- return authedFetchWithError<{ data: EventProperty[] }>(url).then(- (res) => res.data- );+ return authedFetch<{ data: EventProperty[] }>(+ `/events/properties/${site}`,+ params+ ).then((res) => res.data);},});}diff --git a/client/src/api/analytics/useGetEvents.ts b/client/src/api/analytics/useGetEvents.tsindex ff94b7fbb..1fda09461 100644--- a/client/src/api/analytics/useGetEvents.ts+++ b/client/src/api/analytics/useGetEvents.ts@@ -1,8 +1,7 @@import { useInfiniteQuery, useQuery } from "@tanstack/react-query";import { Time } from "../../components/DateSelector/types";-import { BACKEND_URL } from "../../lib/const";import { useStore } from "../../lib/store";-import { authedFetchWithError, buildUrl, getStartAndEndDate } from "../utils";+import { authedFetch, getStartAndEndDate } from "../utils";import { timeZone } from "../../lib/dateTimeUtils";export type Event = {@@ -46,9 +45,9 @@ export function useGetEvents(count = 10) {queryKey: ["events", site, count],refetchInterval: 5000,queryFn: () =>- authedFetchWithError<{ data: Event[] }>(- `${BACKEND_URL}/recent-events/${site}?count=${count}`- ).then((res) => res.data),+ authedFetch<{ data: Event[] }>(`/recent-events/${site}`, {+ count,+ }).then((res) => res.data),});}@@ -91,8 +90,10 @@ export function useGetEventsInfinite(options: GetEventsOptions = {}) {params.count = options.count;}- const url = buildUrl(`${BACKEND_URL}/events/${site}`, params);- const response = await authedFetchWithError<EventsResponse>(url);+ const response = await authedFetch<EventsResponse>(+ `/events/${site}`,+ params+ );return response;},getNextPageParam: (lastPage: EventsResponse) => {diff --git a/client/src/api/analytics/useGetFunnel.ts b/client/src/api/analytics/useGetFunnel.tsindex 428bdc210..79d223c0a 100644--- a/client/src/api/analytics/useGetFunnel.ts+++ b/client/src/api/analytics/useGetFunnel.ts@@ -1,10 +1,9 @@import { Filter } from "@rybbit/shared";import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";import { useDebounce } from "@uidotdev/usehooks";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";-import { authedFetch, authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export type FunnelStep = {value: string;@@ -70,14 +69,12 @@ export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {timeZone,};try {- const response = await authedFetchWithError<{ data: FunnelResponse[] }>(- `${BACKEND_URL}/funnel/${site}`,+ const response = await authedFetch<{ data: FunnelResponse[] }>(+ `/funnel/${site}`,+ undefined,{method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(fullConfig),+ data: fullConfig,});@@ -111,15 +108,12 @@ export function useSaveFunnel() {try {// Save the funnel configuration- const saveResponse = await authedFetchWithError<{+ const saveResponse = await authedFetch<{success: boolean;funnelId: number;- }>(`${BACKEND_URL}/funnel/create/${site}`, {+ }>(`/funnel/create/${site}`, undefined, {method: "POST",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(fullConfig),+ data: fullConfig,});// Invalidate the funnels query to refresh the listdiff --git a/client/src/api/analytics/useGetFunnels.ts b/client/src/api/analytics/useGetFunnels.tsindex fc9565656..d0390e09e 100644--- a/client/src/api/analytics/useGetFunnels.ts+++ b/client/src/api/analytics/useGetFunnels.ts@@ -1,8 +1,7 @@import { Filter } from "@rybbit/shared";import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { FunnelStep } from "./useGetFunnel";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export interface SavedFunnel {id: number;@@ -23,8 +22,8 @@ export function useGetFunnels(siteId?: string | number) {return [];}try {- const response = await authedFetchWithError<{ data: SavedFunnel[] }>(- `${BACKEND_URL}/funnels/${siteId}`+ const response = await authedFetch<{ data: SavedFunnel[] }>(+ `/funnels/${siteId}`);return response.data;} catch (error) {diff --git a/client/src/api/analytics/useGetGoal.ts b/client/src/api/analytics/useGetGoal.tsindex 1d9d8be55..97653f786 100644--- a/client/src/api/analytics/useGetGoal.ts+++ b/client/src/api/analytics/useGetGoal.ts@@ -1,6 +1,5 @@import { Filter } from "@rybbit/shared";import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { authedFetch } from "../utils";@@ -28,12 +27,12 @@ export function useGetGoal({return useQuery({queryKey: ["goal", site, goalId, startDate, endDate, timeZone, filters],queryFn: async () => {- return authedFetch(`${BACKEND_URL}/goal/${goalId}/${site}`, {+ return authedFetch<GetGoalResponse>(`/goal/${goalId}/${site}`, {startDate,endDate,timeZone,filters,- }).then((res) => res.json());+ });},enabled: !!site && !!goalId && enabled,});diff --git a/client/src/api/analytics/useGetGoals.ts b/client/src/api/analytics/useGetGoals.tsindex 1e48558e2..593fb3f24 100644--- a/client/src/api/analytics/useGetGoals.ts+++ b/client/src/api/analytics/useGetGoals.ts@@ -1,5 +1,4 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import {getFilteredFilters,@@ -93,14 +92,14 @@ export function useGetGoals({order,],queryFn: async () => {- return authedFetch(`${BACKEND_URL}/goals/${site}`, {+ return authedFetch<GoalsResponse>(`/goals/${site}`, {...timeParams,filteredFilters,page,pageSize,sort,order,- }).then((res) => res.json());+ });},enabled: !!site && enabled,});diff --git a/client/src/api/analytics/useGetLiveSessionLocations.ts b/client/src/api/analytics/useGetLiveSessionLocations.tsindex fc5f10f00..b87e93be4 100644--- a/client/src/api/analytics/useGetLiveSessionLocations.ts+++ b/client/src/api/analytics/useGetLiveSessionLocations.ts@@ -1,7 +1,6 @@import { useQuery } from "@tanstack/react-query";import { useStore } from "../../lib/store";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export type LiveSessionLocation = {lat: number;@@ -15,8 +14,8 @@ export function useGetLiveSessionLocations(minutes = 5) {return useQuery<LiveSessionLocation[]>({queryKey: ["live-session-locations", site, minutes],queryFn: () =>- authedFetchWithError(- `${BACKEND_URL}/live-session-locations/${site}?time=${minutes}`- ).then((res: any) => res.data),+ authedFetch(`/live-session-locations/${site}`, {+ time: minutes,+ }).then((res: any) => res.data),});}diff --git a/client/src/api/analytics/useGetOrgEventCount.ts b/client/src/api/analytics/useGetOrgEventCount.tsindex ecc20078c..2d0df5359 100644--- a/client/src/api/analytics/useGetOrgEventCount.ts+++ b/client/src/api/analytics/useGetOrgEventCount.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";export type OrgEventCountResponse = {event_date: string;@@ -27,8 +26,9 @@ async function getOrgEventCount({if (endDate) params.append("endDate", endDate);if (timeZone) params.append("timeZone", timeZone);- return authedFetchWithError(- `${BACKEND_URL}/org-event-count/${organizationId}?${params.toString()}`+ return authedFetch(+ `/org-event-count/${organizationId}`,+ Object.fromEntries(params));}diff --git a/client/src/api/analytics/useGetOverview.ts b/client/src/api/analytics/useGetOverview.tsindex 63b2933a8..85c9644e5 100644--- a/client/src/api/analytics/useGetOverview.ts+++ b/client/src/api/analytics/useGetOverview.ts@@ -1,7 +1,6 @@import { useQuery } from "@tanstack/react-query";import { useStore } from "../../lib/store";import { authedFetch, getStartAndEndDate } from "../utils";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";export type GetOverviewResponse = {@@ -29,12 +28,12 @@ export function useGetOverview({return useQuery({queryKey: ["overview", timeToUse, site, filters],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview/${site}`, {+ return authedFetch<{ data: GetOverviewResponse }>(`/overview/${site}`, {startDate,endDate,timeZone,filters,- }).then((res) => res.json());+ });},staleTime: Infinity,placeholderData: (_, query: any) => {@@ -62,11 +61,11 @@ export function useGetOverviewPastMinutes({return useQuery({queryKey: ["overview-past-minutes", pastMinutesStart, pastMinutesEnd, site],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview/${site}`, {+ return authedFetch<{ data: GetOverviewResponse }>(`/overview/${site}`, {timeZone,pastMinutesStart,pastMinutesEnd,- }).then((res) => res.json());+ });},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/useGetOverviewBucketed.tsindex 56dfe6cd6..bc7ef9d69 100644--- a/client/src/api/analytics/useGetOverviewBucketed.ts+++ b/client/src/api/analytics/useGetOverviewBucketed.ts@@ -4,7 +4,6 @@ import {UseQueryResult,useQuery,} from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { APIResponse } from "../types";@@ -46,13 +45,16 @@ export function useGetOverviewBucketed({return useQuery({queryKey: ["overview-bucketed", timeToUse, bucket, site, combinedFilters],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview-bucketed/${site}`, {- startDate,- endDate,- timeZone,- bucket,- filters: combinedFilters,- }).then((res) => res.json());+ return authedFetch<APIResponse<GetOverviewBucketedResponse>>(+ `/overview-bucketed/${site}`,+ {+ startDate,+ endDate,+ timeZone,+ bucket,+ filters: combinedFilters,+ }+ );},placeholderData: (_, query: any) => {if (!query?.queryKey) return undefined;@@ -105,13 +107,16 @@ export function useGetOverviewBucketedPastMinutes({combinedFilters,],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview-bucketed/${site}`, {- timeZone,- bucket,- pastMinutesStart,- pastMinutesEnd,- filters: combinedFilters,- }).then((res) => res.json());+ return authedFetch<APIResponse<GetOverviewBucketedResponse>>(+ `/overview-bucketed/${site}`,+ {+ timeZone,+ bucket,+ pastMinutesStart,+ pastMinutesEnd,+ filters: combinedFilters,+ }+ );},refetchInterval,placeholderData: (_, query: any) => {@@ -167,13 +172,16 @@ export function useGetOverviewBucketedPreviousPastMinutes({combinedFilters,],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview-bucketed/${site}`, {- timeZone,- bucket,- pastMinutesStart,- pastMinutesEnd,- filters: combinedFilters,- }).then((res) => res.json());+ return authedFetch<APIResponse<GetOverviewBucketedResponse>>(+ `/overview-bucketed/${site}`,+ {+ timeZone,+ bucket,+ pastMinutesStart,+ pastMinutesEnd,+ filters: combinedFilters,+ }+ );},refetchInterval,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useGetOverviewBucketedWithInView.ts b/client/src/api/analytics/useGetOverviewBucketedWithInView.tsindex 9482f287b..43cdf690d 100644--- a/client/src/api/analytics/useGetOverviewBucketedWithInView.ts+++ b/client/src/api/analytics/useGetOverviewBucketedWithInView.ts@@ -1,6 +1,5 @@import { TimeBucket } from "@rybbit/shared";import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { APIResponse } from "../types";import { authedFetch } from "../utils";@@ -26,11 +25,14 @@ export function useGetOverviewBucketedWithInView({return useQuery<APIResponse<GetOverviewBucketedResponse>>({queryKey: ["overview-bucketed-past-minutes", pastMinutes, site, bucket],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview-bucketed/${site}`, {- timeZone,- bucket,- pastMinutes,- }).then((res) => res.json());+ return authedFetch<APIResponse<GetOverviewBucketedResponse>>(+ `/overview-bucketed/${site}`,+ {+ timeZone,+ bucket,+ pastMinutes,+ }+ );},refetchInterval: isInView ? refetchInterval : 0,enabled: isInView,diff --git a/client/src/api/analytics/useGetOverviewWithInView.ts b/client/src/api/analytics/useGetOverviewWithInView.tsindex 80999ea2e..9f058806c 100644--- a/client/src/api/analytics/useGetOverviewWithInView.ts+++ b/client/src/api/analytics/useGetOverviewWithInView.ts@@ -1,6 +1,5 @@import { useGetOverviewPastMinutes } from "./useGetOverview";import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { authedFetch } from "../utils";@@ -21,10 +20,10 @@ export function useGetOverviewWithInView({return useQuery({queryKey: ["overview-past-minutes", pastMinutes, site],queryFn: () => {- return authedFetch(`${BACKEND_URL}/overview/${site}`, {+ return authedFetch(`/overview/${site}`, {pastMinutes,timeZone,- }).then((res) => res.json());+ });},enabled: isInView, // Only fetch when in viewstaleTime: Infinity,diff --git a/client/src/api/analytics/useGetPageTitles.ts b/client/src/api/analytics/useGetPageTitles.tsindex 53a07328f..a6ede4b96 100644--- a/client/src/api/analytics/useGetPageTitles.ts+++ b/client/src/api/analytics/useGetPageTitles.ts@@ -1,6 +1,5 @@import { FilterParameter } from "@rybbit/shared";import { useQuery, UseQueryResult } from "@tanstack/react-query";-import { BACKEND_URL } from "@/lib/const";import { timeZone } from "@/lib/dateTimeUtils";import { useStore } from "@/lib/store";import { APIResponse } from "../types";@@ -77,11 +76,9 @@ export function useGetPageTitlesPaginated({isPast24HoursMode ? "past-minutes" : "date-range",],queryFn: () => {- return authedFetch(- `${BACKEND_URL}/page-titles/${site}`,+ return authedFetch<APIResponse<PageTitlesPaginatedResponse>>(+ `/page-titles/${site}`,queryParams- ).then(- (res: any) => res.json() // Added any type for res);},staleTime: Infinity,diff --git a/client/src/api/analytics/useGetPerformanceByDimension.ts b/client/src/api/analytics/useGetPerformanceByDimension.tsindex ad6aaa4ab..b936b7421 100644--- a/client/src/api/analytics/useGetPerformanceByDimension.ts+++ b/client/src/api/analytics/useGetPerformanceByDimension.ts@@ -1,7 +1,6 @@import { Filter } from "@rybbit/shared";import { useQuery, UseQueryResult } from "@tanstack/react-query";import { usePerformanceStore } from "../../app/[site]/performance/performanceStore";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { authedFetch, getStartAndEndDate } from "../utils";@@ -119,13 +118,12 @@ export function useGetPerformanceByDimension({sortBy,sortOrder,],- queryFn: () => {- return authedFetch(- `${BACKEND_URL}/performance/by-dimension/${site}`,+ queryFn: async () => {+ const response = await authedFetch<{ data: any }>(+ `/performance/by-dimension/${site}`,queryParams- )- .then((res) => res.json())- .then(({ data }) => data);+ );+ return response.data;},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useGetPerformanceByPath.ts b/client/src/api/analytics/useGetPerformanceByPath.tsindex 7a3910ff6..707698b40 100644--- a/client/src/api/analytics/useGetPerformanceByPath.ts+++ b/client/src/api/analytics/useGetPerformanceByPath.ts@@ -1,7 +1,6 @@import { Filter } from "@rybbit/shared";import { useQuery, UseQueryResult } from "@tanstack/react-query";import { usePerformanceStore } from "../../app/[site]/performance/performanceStore";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { authedFetch, getStartAndEndDate } from "../utils";@@ -121,13 +120,11 @@ export function useGetPerformanceByPath({sortBy,sortOrder,],- queryFn: () => {- return authedFetch(- `${BACKEND_URL}/performance/by-path/${site}`,- queryParams- )- .then((res) => res.json())- .then(({ data }) => data);+ queryFn: async () => {+ const response = await authedFetch<{+ data: PaginatedPerformanceResponse;+ }>(`/performance/by-path/${site}`, queryParams);+ return response.data;},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useGetPerformanceOverview.ts b/client/src/api/analytics/useGetPerformanceOverview.tsindex 88710cd7b..7695ce641 100644--- a/client/src/api/analytics/useGetPerformanceOverview.ts+++ b/client/src/api/analytics/useGetPerformanceOverview.ts@@ -2,7 +2,6 @@ import { useQuery } from "@tanstack/react-query";import { useStore } from "../../lib/store";import { usePerformanceStore } from "../../app/[site]/performance/performanceStore";import { authedFetch, getStartAndEndDate } from "../utils";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";export type GetPerformanceOverviewResponse = {@@ -45,13 +44,16 @@ export function useGetPerformanceOverview({selectedPercentile,],queryFn: () => {- return authedFetch(`${BACKEND_URL}/performance/overview/${site}`, {- startDate,- endDate,- timeZone,- filters,- percentile: selectedPercentile,- }).then((res) => res.json());+ return authedFetch<{ data: GetPerformanceOverviewResponse }>(+ `/performance/overview/${site}`,+ {+ startDate,+ endDate,+ timeZone,+ filters,+ percentile: selectedPercentile,+ }+ );},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useGetPerformanceTimeSeries.ts b/client/src/api/analytics/useGetPerformanceTimeSeries.tsindex a28a56d24..221239f29 100644--- a/client/src/api/analytics/useGetPerformanceTimeSeries.ts+++ b/client/src/api/analytics/useGetPerformanceTimeSeries.ts@@ -5,7 +5,6 @@ import {useQuery,} from "@tanstack/react-query";import { usePerformanceStore } from "../../app/[site]/performance/performanceStore";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { APIResponse } from "../types";@@ -78,13 +77,16 @@ export function useGetPerformanceTimeSeries({selectedPerformanceMetric,],queryFn: () => {- return authedFetch(`${BACKEND_URL}/performance/time-series/${site}`, {- startDate,- endDate,- timeZone,- bucket: bucketToUse,- filters: combinedFilters,- }).then((res) => res.json());+ return authedFetch<APIResponse<GetPerformanceTimeSeriesResponse>>(+ `/performance/time-series/${site}`,+ {+ startDate,+ endDate,+ timeZone,+ bucket: bucketToUse,+ filters: combinedFilters,+ }+ );},placeholderData: (_, query: any) => {if (!query?.queryKey) return undefined;diff --git a/client/src/api/analytics/useGetRetention.ts b/client/src/api/analytics/useGetRetention.tsindex 3036f5404..5ade17cde 100644--- a/client/src/api/analytics/useGetRetention.ts+++ b/client/src/api/analytics/useGetRetention.ts@@ -1,5 +1,4 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { useStore } from "../../lib/store";import { authedFetch } from "../utils";@@ -20,11 +19,11 @@ export function useGetRetention(const { site } = useStore();return useQuery<ProcessedRetentionData>({queryKey: ["retention", site, mode, range],- queryFn: () =>- authedFetch(- `${BACKEND_URL}/retention/${site}?mode=${mode}&range=${range}`- )- .then((res) => res.json())- .then((data) => data.data),+ queryFn: async () => {+ const response = await authedFetch<{+ data: ProcessedRetentionData;+ }>(`/retention/${site}`, { mode, range });+ return response.data;+ },});}diff --git a/client/src/api/analytics/useInfiniteSingleCol.ts b/client/src/api/analytics/useInfiniteSingleCol.tsindex 7868ea35d..833828289 100644--- a/client/src/api/analytics/useInfiniteSingleCol.ts+++ b/client/src/api/analytics/useInfiniteSingleCol.ts@@ -6,7 +6,6 @@ import {} from "@tanstack/react-query";import { SingleColResponse } from "@/api/analytics/useSingleCol";import { authedFetch, getStartAndEndDate } from "@/api/utils";-import { BACKEND_URL } from "@/lib/const";import { timeZone } from "@/lib/dateTimeUtils";import { useStore } from "@/lib/store";@@ -62,12 +61,10 @@ export function useInfiniteSingleCol({filters: useFilters ? filters : undefined,};- const response = await authedFetch(- `${BACKEND_URL}/single-col/${site}`,- queryParams- );- const json = await response.json();- return json.data;+ const response = await authedFetch<{+ data: InfinitePaginatedResponse;+ }>(`/single-col/${site}`, queryParams);+ return response.data;},initialPageParam: 1,getNextPageParam: (lastPage, allPages) => {diff --git a/client/src/api/analytics/useJourneys.ts b/client/src/api/analytics/useJourneys.tsindex cd027b3a5..ed2680a5d 100644--- a/client/src/api/analytics/useJourneys.ts+++ b/client/src/api/analytics/useJourneys.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";import { authedFetch, getStartAndEndDate } from "../utils";-import { BACKEND_URL } from "../../lib/const";import { Time } from "../../components/DateSelector/types";export interface JourneyParams {@@ -33,20 +32,15 @@ export const useJourneys = ({return useQuery<JourneysResponse>({queryKey: ["journeys", siteId, steps, startDate, endDate, timeZone, limit],queryFn: async () => {- let url = `${BACKEND_URL}/journeys/${siteId}`;- const params = new URLSearchParams();+ const params: Record<string, any> = {};- if (steps) params.append("steps", steps.toString());- if (startDate) params.append("startDate", startDate);- if (endDate) params.append("endDate", endDate);- if (timeZone) params.append("timeZone", timeZone);- if (limit) params.append("limit", limit.toString());+ if (steps) params.steps = steps;+ if (startDate) params.startDate = startDate;+ if (endDate) params.endDate = endDate;+ if (timeZone) params.timeZone = timeZone;+ if (limit) params.limit = limit;- const queryString = params.toString();- if (queryString) url += `?${queryString}`;-- const response = await authedFetch(url);- return response.json();+ return authedFetch<JourneysResponse>(`/journeys/${siteId}`, params);},enabled: !!siteId,});diff --git a/client/src/api/analytics/useLiveUserCount.ts b/client/src/api/analytics/useLiveUserCount.tsindex c8ce720de..c293b9111 100644--- a/client/src/api/analytics/useLiveUserCount.ts+++ b/client/src/api/analytics/useLiveUserCount.ts@@ -1,16 +1,19 @@import { useQuery } from "@tanstack/react-query";import { useStore } from "../../lib/store";-import { BACKEND_URL } from "../../lib/const";import { authedFetch } from "../utils";+export interface LiveUserCountResponse {+ count: number;+}+export function useGetLiveUsercount(minutes = 5) {const { site } = useStore();- return useQuery({+ return useQuery<LiveUserCountResponse>({queryKey: ["live-user-count", site, minutes],refetchInterval: 5000,queryFn: () =>- authedFetch(- `${BACKEND_URL}/live-user-count/${site}?minutes=${minutes}`- ).then((res) => res.json()),+ authedFetch<LiveUserCountResponse>(`/live-user-count/${site}`, {+ minutes,+ }),});}diff --git a/client/src/api/analytics/usePaginatedSingleCol.ts b/client/src/api/analytics/usePaginatedSingleCol.tsindex 2aba7bfc7..6bf8b8e97 100644--- a/client/src/api/analytics/usePaginatedSingleCol.ts+++ b/client/src/api/analytics/usePaginatedSingleCol.ts@@ -2,7 +2,6 @@ import { Filter, FilterParameter } from "@rybbit/shared";import { useQuery, UseQueryResult } from "@tanstack/react-query";import { SingleColResponse } from "@/api/analytics/useSingleCol";import { authedFetch, getStartAndEndDate } from "@/api/utils";-import { BACKEND_URL } from "@/lib/const";import { timeZone } from "@/lib/dateTimeUtils";import { useStore } from "@/lib/store";@@ -66,10 +65,12 @@ export function usePaginatedSingleCol({isPast24HoursMode ? "past-minutes" : "date-range",additionalFilters,],- queryFn: () => {- return authedFetch(`${BACKEND_URL}/single-col/${site}`, queryParams)- .then((res) => res.json())- .then(({ data }) => data);+ queryFn: async () => {+ const response = await authedFetch<{ data: PaginatedResponse }>(+ `/single-col/${site}`,+ queryParams+ );+ return response.data;},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useSingleCol.ts b/client/src/api/analytics/useSingleCol.tsindex 1a9f9617f..935a46551 100644--- a/client/src/api/analytics/useSingleCol.ts+++ b/client/src/api/analytics/useSingleCol.ts@@ -1,6 +1,5 @@import { FilterParameter } from "@rybbit/shared";import { useQuery, UseQueryResult } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import { useStore } from "../../lib/store";import { APIResponse } from "../types";@@ -68,10 +67,11 @@ export function useSingleCol({return useQuery({queryKey,- queryFn: () => {- return authedFetch(`${BACKEND_URL}/single-col/${site}`, queryParams)- .then((res) => res.json())- .then((res) => res.data);+ queryFn: async () => {+ const response = await authedFetch<{+ data: APIResponse<SingleColResponse[]>;+ }>(`/single-col/${site}`, queryParams);+ return response.data;},staleTime: Infinity,placeholderData: (_, query: any) => {@@ -110,13 +110,16 @@ export function useSingleColRealtime({"realtime",],queryFn: () => {- return authedFetch(`${BACKEND_URL}/single-col/${site}`, {- timeZone,- parameter,- limit,- pastMinutesStart,- pastMinutesEnd,- }).then((res) => res.json());+ return authedFetch<APIResponse<SingleColResponse[]>>(+ `/single-col/${site}`,+ {+ timeZone,+ parameter,+ limit,+ pastMinutesStart,+ pastMinutesEnd,+ }+ );},staleTime: Infinity,placeholderData: (_, query: any) => {diff --git a/client/src/api/analytics/useUpdateGoal.ts b/client/src/api/analytics/useUpdateGoal.tsindex 02d24cecd..5ffd4f531 100644--- a/client/src/api/analytics/useUpdateGoal.ts+++ b/client/src/api/analytics/useUpdateGoal.ts@@ -1,6 +1,5 @@import { useMutation, useQueryClient } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";-import { authedFetchWithError } from "../utils";+import { authedFetch } from "../utils";import { useStore } from "../../lib/store";export interface UpdateGoalRequest {@@ -28,14 +27,12 @@ export function useUpdateGoal() {return useMutation<UpdateGoalResponse, Error, UpdateGoalRequest>({mutationFn: async (goalData) => {try {- return await authedFetchWithError<UpdateGoalResponse>(- `${BACKEND_URL}/goal/update`,+ return await authedFetch<UpdateGoalResponse>(+ "/goal/update",+ undefined,{method: "PUT",- headers: {- "Content-Type": "application/json",- },- body: JSON.stringify(goalData),+ data: goalData,});} catch (error) {diff --git a/client/src/api/analytics/userInfo.ts b/client/src/api/analytics/userInfo.tsindex c8a7b8788..901f92f40 100644--- a/client/src/api/analytics/userInfo.ts+++ b/client/src/api/analytics/userInfo.ts@@ -1,5 +1,4 @@import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { authedFetch } from "../utils";export type UserInfo = {@@ -25,10 +24,11 @@ export type UserInfo = {export function useUserInfo(siteId: number, userId: string) {return useQuery<UserInfo>({queryKey: ["user-info", userId, siteId],- queryFn: () => {- return authedFetch(`${BACKEND_URL}/user/info/${userId}/${siteId}`)- .then((res) => res.json())- .then((res) => res.data);+ queryFn: async () => {+ const response = await authedFetch<{ data: UserInfo }>(+ `/user/info/${userId}/${siteId}`+ );+ return response.data;},});}diff --git a/client/src/api/analytics/userSessions.ts b/client/src/api/analytics/userSessions.tsindex bda4caa6d..1502dcdd2 100644--- a/client/src/api/analytics/userSessions.ts+++ b/client/src/api/analytics/userSessions.ts@@ -1,5 +1,4 @@import { useInfiniteQuery, useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import {getFilteredFilters,@@ -35,12 +34,15 @@ export function useGetUserSessions(userId: string) {return useQuery({queryKey: ["user-sessions", userId, time, site, filters],queryFn: () => {- return authedFetch(`${BACKEND_URL}/user/${userId}/sessions/${site}`, {- startDate,- endDate,- timeZone,- filters,- }).then((res) => res.json());+ return authedFetch<UserSessionsResponse>(+ `/user/${userId}/sessions/${site}`,+ {+ startDate,+ endDate,+ timeZone,+ filters,+ }+ );},staleTime: Infinity,});@@ -108,8 +110,9 @@ export function useGetSessionsInfinite(userId?: string) {requestParams.endDate = timeParams.endDate;}- return authedFetch(`${BACKEND_URL}/sessions/${site}`, requestParams).then(- (res) => res.json()+ return authedFetch<APIResponse<GetSessionsResponse>>(+ `/sessions/${site}`,+ requestParams);},initialPageParam: 1,@@ -184,15 +187,21 @@ export function useGetSessionDetailsInfinite(sessionId: string | null) {if (!sessionId) throw new Error("Session ID is required");const limit = 100;- // Build URL with query parameters- let url = `${BACKEND_URL}/session/${sessionId}/${site}?limit=${limit}&offset=${pageParam}`;+ // Build query parameters object+ const queryParams: Record<string, any> = {+ limit,+ offset: pageParam,+ };// Add minutes parameter for last-24-hours modeif (isPast24HoursMode && minutes) {- url += `&minutes=${minutes}`;+ queryParams.minutes = minutes;}- return authedFetch(url).then((res) => res.json());+ return authedFetch<APIResponse<SessionPageviewsAndEvents>>(+ `/session/${sessionId}/${site}`,+ queryParams+ );},initialPageParam: 0,getNextPageParam: (lastPage) => {@@ -217,10 +226,13 @@ export function useGetUserSessionCount(userId: string) {return useQuery<APIResponse<UserSessionCountResponse[]>>({queryKey: ["user-session-count", userId, site],queryFn: () => {- return authedFetch(`${BACKEND_URL}/user/session-count/${site}`, {- userId,- timeZone,- }).then((res) => res.json());+ return authedFetch<APIResponse<UserSessionCountResponse[]>>(+ `/user/session-count/${site}`,+ {+ userId,+ timeZone,+ }+ );},staleTime: Infinity,});diff --git a/client/src/api/analytics/users.ts b/client/src/api/analytics/users.tsindex da4fea730..4e0a26f7c 100644--- a/client/src/api/analytics/users.ts+++ b/client/src/api/analytics/users.ts@@ -1,6 +1,5 @@import { Filter } from "@rybbit/shared";import { useQuery } from "@tanstack/react-query";-import { BACKEND_URL } from "../../lib/const";import { timeZone } from "../../lib/dateTimeUtils";import {useStore,@@ -84,9 +83,13 @@ export function useGetUsers(options: GetUsersOptions) {requestParams.endDate = timeParams.endDate;}- return authedFetch(`${BACKEND_URL}/users/${site}`, requestParams).then(- (res) => res.json()- );+ return authedFetch<+ APIResponse<UsersResponse[]> & {+ totalCount: number;+ page: number;+ pageSize: number;+ }+ >(`/users/${site}`, requestParams);},// Use default staleTime (0) for real-time datastaleTime: 0,diff --git a/client/src/api/utils.ts b/client/src/api/utils.tsindex d4de93fac..866ef1102 100644--- a/client/src/api/utils.ts+++ b/client/src/api/utils.ts@@ -1,5 +1,7 @@import { DateTime } from "luxon";import { Time } from "../components/DateSelector/types";+import axios, { AxiosRequestConfig } from "axios";+import { BACKEND_URL } from "../lib/const";export function getStartAndEndDate(time: Time) {if (time.mode === "range") {@@ -32,69 +34,25 @@ export function getStartAndEndDate(time: Time) {return { startDate: time.day, endDate: time.day };}-/**- * Builds a URL with query parameters from an object- * @param url Base URL- * @param params Object containing query parameters- * @returns URL with query parameters- */-export function buildUrl(url: string, params?: Record<string, any>): string {- if (!params) return url;-- const searchParams = new URLSearchParams();-- Object.entries(params).forEach(([key, value]) => {- if (value === undefined || value === null) return;-- if (typeof value === "object") {- searchParams.append(key, JSON.stringify(value));- } else {- searchParams.append(key, String(value));- }- });-- const queryString = searchParams.toString();- return queryString ? `${url}?${queryString}` : url;-}--export async function authedFetch(- url: string,- paramsOrOpts?: Record<string, any> | RequestInit,- opts: RequestInit = {}-) {- // Handle overloaded function signature- if (- paramsOrOpts &&- ("method" in paramsOrOpts ||- "headers" in paramsOrOpts ||- "body" in paramsOrOpts)- ) {- // If paramsOrOpts looks like RequestInit, treat it as options- return fetch(url, {- credentials: "include",- ...(paramsOrOpts as RequestInit),- });- }-- // Otherwise treat it as params- const fullUrl = buildUrl(url, paramsOrOpts as Record<string, any>);-- return fetch(fullUrl, {- credentials: "include",- ...opts,- });-}--export async function authedFetchWithError<T>(+export async function authedFetch<T>(url: string,- opts: RequestInit = {}+ params?: Record<string, any>,+ config: AxiosRequestConfig = {}): Promise<T> {- const res = await fetch(url, {- credentials: "include",- ...opts,- });- if (!res.ok) {- throw new Error(await res.text());+ const fullUrl = url.startsWith("http") ? url : `${BACKEND_URL}${url}`;++ try {+ const response = await axios({+ url: fullUrl,+ params,+ withCredentials: true,+ ...config,+ });+ return response.data;+ } catch (error: any) {+ if (error?.response?.data?.error) {+ throw new Error(error.response.data.error);+ }+ throw error;}- return res.json();}diff --git a/client/src/app/components/AddSite.tsx b/client/src/app/components/AddSite.tsxindex be65dcaea..0dd329290 100644--- a/client/src/app/components/AddSite.tsx+++ b/client/src/app/components/AddSite.tsx@@ -83,7 +83,7 @@ export function AddSite({saltUserIds,});} catch (error) {- setError("Failed to add site");+ setError(String(error));return;}diff --git a/client/src/lib/configs.ts b/client/src/lib/configs.tsindex 413437a3f..0e13a62a8 100644--- a/client/src/lib/configs.ts+++ b/client/src/lib/configs.ts@@ -1,6 +1,5 @@import { useQuery } from "@tanstack/react-query";-import { authedFetchWithError } from "../api/utils";-import { BACKEND_URL } from "./const";+import { authedFetch } from "../api/utils";interface Configs {disableSignup: boolean;@@ -9,7 +8,7 @@ interface Configs {export function useConfigs() {const { data, isLoading, error } = useQuery<Configs>({queryKey: ["configs"],- queryFn: () => authedFetchWithError<Configs>(`${BACKEND_URL}/config`),+ queryFn: () => authedFetch<Configs>("/config"),});return {diff --git a/memory-bank/decisionLog.md b/memory-bank/decisionLog.mdindex 04235991f..ee2deb6fc 100644--- a/memory-bank/decisionLog.md+++ b/memory-bank/decisionLog.md@@ -23,3 +23,40 @@ Implemented a comprehensive Memory Bank system to maintain project context acros- Prepared framework for documenting future architectural decisions and patterns[2025-06-08 06:53:49] - Docker Build Context Fix: Changed all build contexts from subdirectory (./client, ./server) to monorepo root (.) in docker-compose.cloud.yml and GitHub Actions workflow. Updated Dockerfiles to use correct paths from monorepo root (e.g., COPY client/package.json instead of COPY package.json). This resolves the shared package access issue while maintaining compatibility between local and CI builds.++[2025-06-08 16:43:52] - Enhanced authedFetchWithError to use axios with query parameter support++## Rationale++User requested to replace all instances of authedFetch with authedFetchWithError and wanted to use axios specifically for its params support. This decision was made to:++- Provide clean object-based query parameter support instead of manual string template literals+- Maintain consistency with axios patterns for HTTP requests+- Prepare for eventual replacement of all authedFetch instances+- Leverage axios's built-in parameter serialization and error handling++## Implementation Details++- Added axios dependency to client package.json+- Modified authedFetchWithError to accept query parameters as objects+- Maintained overloaded function signature for backward compatibility+- Used axios withCredentials: true to maintain authentication behavior+- Function now supports both query params as objects and full axios config objects++[2025-06-08 16:46:58] - Simplified authedFetchWithError function signature++## Rationale++User feedback indicated they didn't like the overloading behavior and wanted the 2nd argument to always be params instead of config. This decision was made to:++- Provide a cleaner, more predictable API+- Remove complexity from function signature detection+- Make the second parameter always represent query parameters+- Keep axios configuration as the third parameter for advanced use cases++## Implementation Details++- Removed overloaded function signature detection logic+- Second parameter is now always `params?: Record<string, any>`+- Third parameter remains `config: AxiosRequestConfig = {}` for advanced axios options+- Simplified function body to always treat second argument as query parametersdiff --git a/server/src/index.ts b/server/src/index.tsindex 22ad68a04..cd56dffb2 100644--- a/server/src/index.ts+++ b/server/src/index.ts@@ -85,6 +85,8 @@ server.register(cors, {callback(new Error("Not allowed by CORS"), false);}},+ methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"],+ allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],credentials: true,});