Skip to content

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

Api playground (#757)

Bill Yangead62eb9b54e
diff --git a/client/eslint.config.mjs b/client/eslint.config.mjs
index 29cfe40a3..1d987f0ea 100644
--- a/client/eslint.config.mjs
+++ b/client/eslint.config.mjs
@@ -1,15 +1,15 @@
-import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
-import nextTypescript from "eslint-config-next/typescript";
+// import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
+// import nextTypescript from "eslint-config-next/typescript";
-const eslintConfig = [
- ...nextCoreWebVitals,
- ...nextTypescript,
- {
- rules: {
- "@typescript-eslint/no-explicit-any": "off",
- },
- ignores: ["node_modules/**", ".next/**", "out/**", "build/**", "next-env.d.ts"],
- },
-];
+// const eslintConfig = [
+// ...nextCoreWebVitals,
+// ...nextTypescript,
+// {
+// rules: {
+// "@typescript-eslint/no-explicit-any": "off",
+// },
+// ignores: ["node_modules/**", ".next/**", "out/**", "build/**", "next-env.d.ts"],
+// },
+// ];
-export default eslintConfig;
+// export default eslintConfig;
diff --git a/client/package-lock.json b/client/package-lock.json
index 388b6e5b3..4c6e88984 100644
--- a/client/package-lock.json
+++ b/client/package-lock.json
@@ -72,6 +72,7 @@
"react-hook-form": "7.56.3",
"react-scan": "^0.3.4",
"react-select": "5.10.1",
+ "react-syntax-highlighter": "^16.1.0",
"rrweb-player": "^2.0.0-alpha.11",
"sonner": "2.0.3",
"tailwind-merge": "2.6.0",
@@ -88,6 +89,7 @@
"@types/mapbox-gl": "^3.4.1",
"@types/node": "^20.14.8",
"@types/react": "19.2.7",
+ "@types/react-syntax-highlighter": "^15.5.13",
"eslint": "^9.39.1",
"eslint-config-next": "^16.0.7",
"knip": "^5.60.2",
@@ -323,9 +325,9 @@
}
},
"node_modules/@babel/runtime": {
- "version": "7.27.1",
- "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.27.1.tgz",
- "integrity": "sha512-1x3D2xEk2fRo3PAhwQwu5UubzgiVWSXTBfWpVd2Mx2AzRqJuDJCsgaDVZ7HB5iGzDW1Hl1sWN2mFyKjmR9uAog==",
+ "version": "7.28.4",
+ "resolved": "https://registry.npmjs.org/@babel/runtime/-/runtime-7.28.4.tgz",
+ "integrity": "sha512-Q/N6JNWvIvPnLDvjlE1OUBLPQHH6l3CltCEsHIujp45zQUSSh8K+gHnaEX45yAT1nyngnINhvWtzN+Nb9D8RAQ==",
"license": "MIT",
"engines": {
"node": ">=6.9.0"
@@ -5386,6 +5388,15 @@
"@types/geojson": "*"
}
},
+ "node_modules/@types/hast": {
+ "version": "3.0.4",
+ "resolved": "https://registry.npmjs.org/@types/hast/-/hast-3.0.4.tgz",
+ "integrity": "sha512-WPs+bbQw5aCj+x6laNGWLH3wviHtoCv/P3+otBhbOhJgG8qtpdAMlTCxLtsTWA7LH1Oh/bFCHsBn0TPS5m30EQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "*"
+ }
+ },
"node_modules/@types/json-schema": {
"version": "7.0.15",
"resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz",
@@ -5459,6 +5470,12 @@
"integrity": "sha512-j3pOPiEcWZ34R6a6mN07mUkM4o4Lwf6hPNt8eilOeZhTFbxFXmKhvXl9Y28jotFPaI1bpPDJsbCprUoNke6OrA==",
"license": "MIT"
},
+ "node_modules/@types/prismjs": {
+ "version": "1.26.5",
+ "resolved": "https://registry.npmjs.org/@types/prismjs/-/prismjs-1.26.5.tgz",
+ "integrity": "sha512-AUZTa7hQ2KY5L7AmtSiqxlhWxb4ina0yd8hNbl4TWuqnv/pFP0nDMb3YrfSBf4hJVGLh2YEIBfKaBW/9UEl6IQ==",
+ "license": "MIT"
+ },
"node_modules/@types/rbush": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/@types/rbush/-/rbush-4.0.0.tgz",
@@ -5484,6 +5501,16 @@
"@types/react": "*"
}
},
+ "node_modules/@types/react-syntax-highlighter": {
+ "version": "15.5.13",
+ "resolved": "https://registry.npmjs.org/@types/react-syntax-highlighter/-/react-syntax-highlighter-15.5.13.tgz",
+ "integrity": "sha512-uLGJ87j6Sz8UaBAooU0T6lWJ0dBmjZgN1PZTrj05TNql2/XpC6+4HhMT5syIdFUUt+FASfCeLLv4kBygNU+8qA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/react": "*"
+ }
+ },
"node_modules/@types/react-transition-group": {
"version": "4.4.12",
"resolved": "https://registry.npmjs.org/@types/react-transition-group/-/react-transition-group-4.4.12.tgz",
@@ -5502,6 +5529,12 @@
"@types/geojson": "*"
}
},
+ "node_modules/@types/unist": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-3.0.3.tgz",
+ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
+ "license": "MIT"
+ },
"node_modules/@typescript-eslint/eslint-plugin": {
"version": "8.48.1",
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.48.1.tgz",
@@ -6638,6 +6671,36 @@
"url": "https://github.com/chalk/chalk?sponsor=1"
}
},
+ "node_modules/character-entities": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/character-entities/-/character-entities-2.0.2.tgz",
+ "integrity": "sha512-shx7oQ0Awen/BRIdkjkvz54PnEEI/EjwXDSIZp86/KKdbafHh1Df/RYGBhn4hbe2+uKC9FnT5UCEdyPz3ai9hQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-entities-legacy": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/character-entities-legacy/-/character-entities-legacy-3.0.0.tgz",
+ "integrity": "sha512-RpPp0asT/6ufRm//AJVwpViZbGM/MkjQFxJccQRHmISF/22NBtsHqAWmL+/pmkPWoIUJdWyeVleTl1wydHATVQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/character-reference-invalid": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/character-reference-invalid/-/character-reference-invalid-2.0.1.tgz",
+ "integrity": "sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/cheap-ruler": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/cheap-ruler/-/cheap-ruler-4.0.0.tgz",
@@ -6718,6 +6781,16 @@
"node": ">= 0.8"
}
},
+ "node_modules/comma-separated-tokens": {
+ "version": "2.0.3",
+ "resolved": "https://registry.npmjs.org/comma-separated-tokens/-/comma-separated-tokens-2.0.3.tgz",
+ "integrity": "sha512-Fu4hJdvzeylCfQPp9SGWidpzrMs7tTrlu6Vb8XGaRGck8QSNZJJp538Wrb60Lax4fPwR64ViY468OIUTbRlGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/commander": {
"version": "7.2.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-7.2.0.tgz",
@@ -7322,6 +7395,19 @@
}
}
},
+ "node_modules/decode-named-character-reference": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/decode-named-character-reference/-/decode-named-character-reference-1.2.0.tgz",
+ "integrity": "sha512-c6fcElNV6ShtZXmsgNgFFV5tVX2PaV4g+MOAkb8eXHvn6sryJBrZa9r0zV6+dtTyoCKxtDy5tyQ5ZwQuidtd+Q==",
+ "license": "MIT",
+ "dependencies": {
+ "character-entities": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/deep-is": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
@@ -8250,6 +8336,19 @@
"reusify": "^1.0.4"
}
},
+ "node_modules/fault": {
+ "version": "1.0.4",
+ "resolved": "https://registry.npmjs.org/fault/-/fault-1.0.4.tgz",
+ "integrity": "sha512-CJ0HCB5tL5fYTEA7ToAq5+kTwd++Borf1/bifxd9iT70QcXr4MRrO3Llf8Ifs70q+SJcGHFtnIE/Nw6giCtECA==",
+ "license": "MIT",
+ "dependencies": {
+ "format": "^0.2.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/fd-package-json": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/fd-package-json/-/fd-package-json-2.0.0.tgz",
@@ -8379,6 +8478,14 @@
"node": ">= 6"
}
},
+ "node_modules/format": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/format/-/format-0.2.2.tgz",
+ "integrity": "sha512-wzsgA6WOq+09wrU1tsJ09udeR/YZRaeArL9e1wPbFg3GG2yDnC2ldKpxs4xunpFF9DgqCqOIra3bc1HWrJ37Ww==",
+ "engines": {
+ "node": ">=0.4.x"
+ }
+ },
"node_modules/formatly": {
"version": "0.2.4",
"resolved": "https://registry.npmjs.org/formatly/-/formatly-0.2.4.tgz",
@@ -8765,6 +8872,36 @@
"node": ">= 0.4"
}
},
+ "node_modules/hast-util-parse-selector": {
+ "version": "4.0.0",
+ "resolved": "https://registry.npmjs.org/hast-util-parse-selector/-/hast-util-parse-selector-4.0.0.tgz",
+ "integrity": "sha512-wkQCkSYoOGCRKERFWcxMVMOcYE2K1AaNLU8DXS9arxnLOUEWbOXKXiJUNzEpqZ3JOKpnha3jkFrumEjVliDe7A==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
+ "node_modules/hastscript": {
+ "version": "9.0.1",
+ "resolved": "https://registry.npmjs.org/hastscript/-/hastscript-9.0.1.tgz",
+ "integrity": "sha512-g7df9rMFX/SPi34tyGCyUBREQoKkapwdY/T04Qn9TDWfHhAYt4/I0gMVirzK5wEzeUqIjEB+LXC/ypb7Aqno5w==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "comma-separated-tokens": "^2.0.0",
+ "hast-util-parse-selector": "^4.0.0",
+ "property-information": "^7.0.0",
+ "space-separated-tokens": "^2.0.0"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/unified"
+ }
+ },
"node_modules/hermes-estree": {
"version": "0.25.1",
"resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz",
@@ -8782,6 +8919,21 @@
"hermes-estree": "0.25.1"
}
},
+ "node_modules/highlight.js": {
+ "version": "10.7.3",
+ "resolved": "https://registry.npmjs.org/highlight.js/-/highlight.js-10.7.3.tgz",
+ "integrity": "sha512-tzcUFauisWKNHaRkN4Wjl/ZA07gENAjFl3J/c480dprkGTg5EQstgaNFqBfUqCq54kZRIEcreTsAgF/m2quD7A==",
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": "*"
+ }
+ },
+ "node_modules/highlightjs-vue": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/highlightjs-vue/-/highlightjs-vue-1.0.0.tgz",
+ "integrity": "sha512-PDEfEF102G23vHmPhLyPboFCD+BkMGu+GuJe2d9/eH4FsCwvgBpnc9n0pGE+ffKdph38s6foEZiEjdgHdzp+IA==",
+ "license": "CC0-1.0"
+ },
"node_modules/hoist-non-react-statics": {
"version": "3.3.2",
"resolved": "https://registry.npmjs.org/hoist-non-react-statics/-/hoist-non-react-statics-3.3.2.tgz",
@@ -8884,6 +9036,30 @@
"node": ">= 12"
}
},
+ "node_modules/is-alphabetical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphabetical/-/is-alphabetical-2.0.1.tgz",
+ "integrity": "sha512-FWyyY60MeTNyeSRpkM2Iry0G9hpr7/9kD40mD/cGQEuilcZYS4okz8SN2Q6rLCJ8gbCt6fN+rC+6tMGS99LaxQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/is-alphanumerical": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-alphanumerical/-/is-alphanumerical-2.0.1.tgz",
+ "integrity": "sha512-hmbYhX/9MUMF5uh7tOXyK/n0ZvWpad5caBA17GsC6vyuCqaWliRG5K1qS9inmUhEMaOBIW7/whAnSwveW/LtZw==",
+ "license": "MIT",
+ "dependencies": {
+ "is-alphabetical": "^2.0.0",
+ "is-decimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-array-buffer": {
"version": "3.0.5",
"resolved": "https://registry.npmjs.org/is-array-buffer/-/is-array-buffer-3.0.5.tgz",
@@ -9034,6 +9210,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/is-decimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-decimal/-/is-decimal-2.0.1.tgz",
+ "integrity": "sha512-AAB9hiomQs5DXWcRB1rqsxGUstbRroFOPPVAomNk/3XHR5JyEZChOyTWe2oayKnsSsr/kcGqF+z6yuH6HHpN0A==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-extglob": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz",
@@ -9093,6 +9279,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/is-hexadecimal": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/is-hexadecimal/-/is-hexadecimal-2.0.1.tgz",
+ "integrity": "sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/is-map": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/is-map/-/is-map-2.0.3.tgz",
@@ -9907,6 +10103,20 @@
"loose-envify": "cli.js"
}
},
+ "node_modules/lowlight": {
+ "version": "1.20.0",
+ "resolved": "https://registry.npmjs.org/lowlight/-/lowlight-1.20.0.tgz",
+ "integrity": "sha512-8Ktj+prEb1RoCPkEOrPMYUN/nCggB7qAWe3a7OpMjWQkh3l2RD5wKRQ+o8Q8YuI9RG/xs95waaI/E6ym/7NsTw==",
+ "license": "MIT",
+ "dependencies": {
+ "fault": "^1.0.0",
+ "highlight.js": "~10.7.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/lucide-react": {
"version": "0.510.0",
"resolved": "https://registry.npmjs.org/lucide-react/-/lucide-react-0.510.0.tgz",
@@ -10568,6 +10778,31 @@
"node": ">=6"
}
},
+ "node_modules/parse-entities": {
+ "version": "4.0.2",
+ "resolved": "https://registry.npmjs.org/parse-entities/-/parse-entities-4.0.2.tgz",
+ "integrity": "sha512-GG2AQYWoLgL877gQIKeRPGO1xF9+eG1ujIb5soS5gPvLQ1y2o8FL90w2QWNdf9I361Mpp7726c+lj3U0qK1uGw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/unist": "^2.0.0",
+ "character-entities-legacy": "^3.0.0",
+ "character-reference-invalid": "^2.0.0",
+ "decode-named-character-reference": "^1.0.0",
+ "is-alphanumerical": "^2.0.0",
+ "is-decimal": "^2.0.0",
+ "is-hexadecimal": "^2.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
+ "node_modules/parse-entities/node_modules/@types/unist": {
+ "version": "2.0.11",
+ "resolved": "https://registry.npmjs.org/@types/unist/-/unist-2.0.11.tgz",
+ "integrity": "sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==",
+ "license": "MIT"
+ },
"node_modules/parse-headers": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/parse-headers/-/parse-headers-2.0.6.tgz",
@@ -10779,6 +11014,15 @@
"url": "https://github.com/prettier/prettier?sponsor=1"
}
},
+ "node_modules/prismjs": {
+ "version": "1.30.0",
+ "resolved": "https://registry.npmjs.org/prismjs/-/prismjs-1.30.0.tgz",
+ "integrity": "sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
"node_modules/process-nextick-args": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/process-nextick-args/-/process-nextick-args-2.0.1.tgz",
@@ -10796,6 +11040,16 @@
"react-is": "^16.13.1"
}
},
+ "node_modules/property-information": {
+ "version": "7.1.0",
+ "resolved": "https://registry.npmjs.org/property-information/-/property-information-7.1.0.tgz",
+ "integrity": "sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/protocol-buffers-schema": {
"version": "3.6.0",
"resolved": "https://registry.npmjs.org/protocol-buffers-schema/-/protocol-buffers-schema-3.6.0.tgz",
@@ -11102,6 +11356,26 @@
}
}
},
+ "node_modules/react-syntax-highlighter": {
+ "version": "16.1.0",
+ "resolved": "https://registry.npmjs.org/react-syntax-highlighter/-/react-syntax-highlighter-16.1.0.tgz",
+ "integrity": "sha512-E40/hBiP5rCNwkeBN1vRP+xow1X0pndinO+z3h7HLsHyjztbyjfzNWNKuAsJj+7DLam9iT4AaaOZnueCU+Nplg==",
+ "license": "MIT",
+ "dependencies": {
+ "@babel/runtime": "^7.28.4",
+ "highlight.js": "^10.4.1",
+ "highlightjs-vue": "^1.0.0",
+ "lowlight": "^1.17.0",
+ "prismjs": "^1.30.0",
+ "refractor": "^5.0.0"
+ },
+ "engines": {
+ "node": ">= 16.20.2"
+ },
+ "peerDependencies": {
+ "react": ">= 0.14.0"
+ }
+ },
"node_modules/react-transition-group": {
"version": "4.4.5",
"resolved": "https://registry.npmjs.org/react-transition-group/-/react-transition-group-4.4.5.tgz",
@@ -11168,6 +11442,22 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/refractor": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/refractor/-/refractor-5.0.0.tgz",
+ "integrity": "sha512-QXOrHQF5jOpjjLfiNk5GFnWhRXvxjUVnlFxkeDmewR5sXkr3iM46Zo+CnRR8B+MDVqkULW4EcLVcRBNOPXHosw==",
+ "license": "MIT",
+ "dependencies": {
+ "@types/hast": "^3.0.0",
+ "@types/prismjs": "^1.0.0",
+ "hastscript": "^9.0.0",
+ "parse-entities": "^4.0.0"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/regexp.prototype.flags": {
"version": "1.5.4",
"resolved": "https://registry.npmjs.org/regexp.prototype.flags/-/regexp.prototype.flags-1.5.4.tgz",
@@ -11679,6 +11969,16 @@
"node": ">=0.10.0"
}
},
+ "node_modules/space-separated-tokens": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/space-separated-tokens/-/space-separated-tokens-2.0.2.tgz",
+ "integrity": "sha512-PEGlAwrG8yXGXRjW32fGbg66JAlOAwbObuqVoJpv/mRgoWDQfgH1wDPvtzWyUSNAXBGSk8h755YDbbcEy3SH2Q==",
+ "license": "MIT",
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/wooorm"
+ }
+ },
"node_modules/splaytree": {
"version": "0.1.4",
"resolved": "https://registry.npmjs.org/splaytree/-/splaytree-0.1.4.tgz",
diff --git a/client/package.json b/client/package.json
index d48beddeb..5b555cae6 100644
--- a/client/package.json
+++ b/client/package.json
@@ -76,6 +76,7 @@
"react-hook-form": "7.56.3",
"react-scan": "^0.3.4",
"react-select": "5.10.1",
+ "react-syntax-highlighter": "^16.1.0",
"rrweb-player": "^2.0.0-alpha.11",
"sonner": "2.0.3",
"tailwind-merge": "2.6.0",
@@ -92,6 +93,7 @@
"@types/mapbox-gl": "^3.4.1",
"@types/node": "^20.14.8",
"@types/react": "19.2.7",
+ "@types/react-syntax-highlighter": "^15.5.13",
"eslint": "^9.39.1",
"eslint-config-next": "^16.0.7",
"knip": "^5.60.2",
diff --git a/client/src/api/admin/useGetAdminServiceEventCount.ts b/client/src/api/admin/useGetAdminServiceEventCount.ts
index fa361525b..649392238 100644
--- a/client/src/api/admin/useGetAdminServiceEventCount.ts
+++ b/client/src/api/admin/useGetAdminServiceEventCount.ts
@@ -34,12 +34,10 @@ export function useGetAdminServiceEventCount({
startDate,
endDate,
timeZone,
- enabled = true,
}: {
startDate?: string;
endDate?: string;
timeZone: string;
- enabled?: boolean;
}) {
return useQuery({
queryKey: ["admin-service-event-count", startDate, endDate, timeZone],
@@ -49,7 +47,6 @@ export function useGetAdminServiceEventCount({
endDate,
timeZone,
}),
- enabled,
staleTime: 1000 * 60 * 5, // 5 minutes
});
}
diff --git a/client/src/api/analytics/endpoints/errors.ts b/client/src/api/analytics/endpoints/errors.ts
new file mode 100644
index 000000000..992a50de0
--- /dev/null
+++ b/client/src/api/analytics/endpoints/errors.ts
@@ -0,0 +1,136 @@
+import { TimeBucket } from "@rybbit/shared";
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+
+// Error Name Item type
+export type ErrorNameItem = {
+ value: string; // Error message
+ errorName: string; // Error type (TypeError, ReferenceError, etc.)
+ count: number; // Total occurrences
+ sessionCount: number; // Unique sessions affected
+ percentage: number;
+};
+
+// Paginated response for error names
+export type ErrorNamesPaginatedResponse = {
+ data: ErrorNameItem[];
+ totalCount: number;
+};
+
+// Non-paginated response (standard format)
+export type ErrorNamesStandardResponse = ErrorNameItem[];
+
+// Error Event type
+export type ErrorEvent = {
+ timestamp: string;
+ session_id: string;
+ user_id: string | null;
+ pathname: string | null;
+ hostname: string | null;
+ page_title: string | null;
+ referrer: string | null;
+ browser: string | null;
+ browser_version: string | null;
+ operating_system: string | null;
+ operating_system_version: string | null;
+ device_type: string | null;
+ country: string | null;
+ city: string | null;
+ region: string | null;
+ // Parsed error properties
+ message: string;
+ stack: string | null;
+ fileName: string | null;
+ lineNumber: number | null;
+ columnNumber: number | null;
+};
+
+// Paginated response for error events
+export type ErrorEventsPaginatedResponse = {
+ data: ErrorEvent[];
+ totalCount: number;
+};
+
+// Non-paginated response (standard format)
+export type ErrorEventsStandardResponse = ErrorEvent[];
+
+// Error bucketed response (time series)
+export type GetErrorBucketedResponse = {
+ time: string;
+ error_count: number;
+}[];
+
+export interface ErrorNamesParams extends CommonApiParams, PaginationParams {}
+
+export interface ErrorEventsParams extends CommonApiParams, PaginationParams {
+ errorMessage: string;
+}
+
+export interface ErrorBucketedParams extends CommonApiParams {
+ errorMessage: string;
+ bucket: TimeBucket;
+}
+
+/**
+ * Fetch error names with counts
+ * GET /api/error-names/:site
+ */
+export async function fetchErrorNames(
+ site: string | number,
+ params: ErrorNamesParams
+): Promise<ErrorNamesPaginatedResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ limit: params.limit,
+ page: params.page,
+ };
+
+ const response = await authedFetch<{ data: ErrorNamesPaginatedResponse }>(
+ `/error-names/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch individual error events
+ * GET /api/error-events/:site
+ */
+export async function fetchErrorEvents(
+ site: string | number,
+ params: ErrorEventsParams
+): Promise<ErrorEventsPaginatedResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ errorMessage: params.errorMessage,
+ limit: params.limit,
+ page: params.page,
+ };
+
+ const response = await authedFetch<{ data: ErrorEventsPaginatedResponse }>(
+ `/error-events/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch error counts over time
+ * GET /api/error-bucketed/:site
+ */
+export async function fetchErrorBucketed(
+ site: string | number,
+ params: ErrorBucketedParams
+): Promise<GetErrorBucketedResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ errorMessage: params.errorMessage,
+ bucket: params.bucket,
+ };
+
+ const response = await authedFetch<{ data: GetErrorBucketedResponse }>(
+ `/error-bucketed/${site}`,
+ queryParams
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/endpoints/events.ts b/client/src/api/analytics/endpoints/events.ts
new file mode 100644
index 000000000..daea9208d
--- /dev/null
+++ b/client/src/api/analytics/endpoints/events.ts
@@ -0,0 +1,130 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+
+// Event type
+export type Event = {
+ timestamp: string;
+ event_name: string;
+ properties: string;
+ user_id: string;
+ hostname: string;
+ pathname: string;
+ querystring: string;
+ page_title: string;
+ referrer: string;
+ browser: string;
+ operating_system: string;
+ country: string;
+ device_type: string;
+ type: string;
+};
+
+// Events response with pagination
+export interface EventsResponse {
+ data: Event[];
+ pagination: {
+ total: number;
+ page: number;
+ pageSize: number;
+ totalPages: number;
+ };
+}
+
+// Event name with count
+export type EventName = {
+ eventName: string;
+ count: number;
+};
+
+// Event property key-value pair
+export type EventProperty = {
+ propertyKey: string;
+ propertyValue: string;
+ count: number;
+};
+
+// Outbound link click data
+export type OutboundLink = {
+ url: string;
+ count: number;
+ lastClicked: string;
+};
+
+export interface EventsParams extends CommonApiParams, PaginationParams {
+ pageSize?: number;
+}
+
+export interface EventPropertiesParams extends CommonApiParams {
+ eventName: string;
+}
+
+/**
+ * Fetch paginated events
+ * GET /api/events/:site
+ */
+export async function fetchEvents(
+ site: string | number,
+ params: EventsParams
+): Promise<EventsResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ page: params.page,
+ page_size: params.pageSize ?? params.limit,
+ };
+
+ const response = await authedFetch<EventsResponse>(
+ `/events/${site}`,
+ queryParams
+ );
+ return response;
+}
+
+/**
+ * Fetch event names
+ * GET /api/events/names/:site
+ */
+export async function fetchEventNames(
+ site: string | number,
+ params: CommonApiParams
+): Promise<EventName[]> {
+ const response = await authedFetch<{ data: EventName[] }>(
+ `/events/names/${site}`,
+ toQueryParams(params)
+ );
+ return response.data;
+}
+
+/**
+ * Fetch event properties for a specific event name
+ * GET /api/events/properties/:site
+ */
+export async function fetchEventProperties(
+ site: string | number,
+ params: EventPropertiesParams
+): Promise<EventProperty[]> {
+ const queryParams = {
+ ...toQueryParams(params),
+ event_name: params.eventName,
+ };
+
+ const response = await authedFetch<{ data: EventProperty[] }>(
+ `/events/properties/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch outbound link clicks
+ * GET /api/events/outbound/:site
+ */
+export async function fetchOutboundLinks(
+ site: string | number,
+ params: CommonApiParams
+): Promise<OutboundLink[]> {
+ const response = await authedFetch<{ data: OutboundLink[] }>(
+ `/events/outbound/${site}`,
+ toQueryParams(params)
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/endpoints/funnels.ts b/client/src/api/analytics/endpoints/funnels.ts
new file mode 100644
index 000000000..415c22f1f
--- /dev/null
+++ b/client/src/api/analytics/endpoints/funnels.ts
@@ -0,0 +1,163 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+import type { GetSessionsResponse } from "./sessions";
+
+// Funnel step type
+export type FunnelStep = {
+ value: string;
+ name?: string;
+ type: "page" | "event";
+ hostname?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+};
+
+// Funnel request type
+export type FunnelRequest = {
+ steps: FunnelStep[];
+ name?: string;
+};
+
+// Save funnel request type
+export type SaveFunnelRequest = {
+ steps: FunnelStep[];
+ name: string;
+ reportId?: number;
+};
+
+// Funnel response type
+export type FunnelResponse = {
+ step_number: number;
+ step_name: string;
+ visitors: number;
+ conversion_rate: number;
+ dropoff_rate: number;
+};
+
+// Saved funnel type
+export interface SavedFunnel {
+ id: number;
+ name: string;
+ steps: FunnelStep[];
+ createdAt: string;
+ updatedAt: string;
+ conversionRate: number | null;
+ totalVisitors: number | null;
+}
+
+export interface AnalyzeFunnelParams extends CommonApiParams {
+ steps: FunnelStep[];
+ name?: string;
+}
+
+export interface FunnelStepSessionsParams extends CommonApiParams, PaginationParams {
+ steps: FunnelStep[];
+ stepNumber: number;
+ mode: "reached" | "dropped";
+}
+
+export interface SaveFunnelParams {
+ steps: FunnelStep[];
+ name: string;
+ reportId?: number;
+}
+
+/**
+ * Fetch all saved funnels
+ * GET /api/funnels/:site
+ */
+export async function fetchFunnels(
+ site: string | number
+): Promise<SavedFunnel[]> {
+ const response = await authedFetch<{ data: SavedFunnel[] }>(
+ `/funnels/${site}`
+ );
+ return response.data;
+}
+
+/**
+ * Analyze a funnel configuration
+ * POST /api/funnels/analyze/:site
+ */
+export async function analyzeFunnel(
+ site: string | number,
+ params: AnalyzeFunnelParams
+): Promise<FunnelResponse[]> {
+ const queryParams = toQueryParams(params);
+
+ const response = await authedFetch<{ data: FunnelResponse[] }>(
+ `/funnels/analyze/${site}`,
+ queryParams,
+ {
+ method: "POST",
+ data: {
+ steps: params.steps,
+ name: params.name,
+ },
+ }
+ );
+ return response.data;
+}
+
+/**
+ * Get sessions at a specific funnel step
+ * POST /api/funnels/:stepNumber/sessions/:site
+ */
+export async function fetchFunnelStepSessions(
+ site: string | number,
+ params: FunnelStepSessionsParams
+): Promise<{ data: GetSessionsResponse }> {
+ const queryParams = {
+ ...toQueryParams(params),
+ mode: params.mode,
+ page: params.page,
+ limit: params.limit,
+ };
+
+ const response = await authedFetch<{ data: GetSessionsResponse }>(
+ `/funnels/${params.stepNumber}/sessions/${site}`,
+ queryParams,
+ {
+ method: "POST",
+ data: { steps: params.steps },
+ }
+ );
+ return response;
+}
+
+/**
+ * Create or update a saved funnel
+ * POST /api/funnels/:site
+ */
+export async function saveFunnel(
+ site: string | number,
+ params: SaveFunnelParams
+): Promise<{ success: boolean; funnelId: number }> {
+ const response = await authedFetch<{ success: boolean; funnelId: number }>(
+ `/funnels/${site}`,
+ undefined,
+ {
+ method: "POST",
+ data: params,
+ }
+ );
+ return response;
+}
+
+/**
+ * Delete a saved funnel
+ * DELETE /api/funnels/:funnelId/:site
+ */
+export async function deleteFunnel(
+ site: string | number,
+ funnelId: number
+): Promise<{ success: boolean }> {
+ const response = await authedFetch<{ success: boolean }>(
+ `/funnels/${funnelId}/${site}`,
+ undefined,
+ {
+ method: "DELETE",
+ }
+ );
+ return response;
+}
diff --git a/client/src/api/analytics/endpoints/goals.ts b/client/src/api/analytics/endpoints/goals.ts
new file mode 100644
index 000000000..58cf890cc
--- /dev/null
+++ b/client/src/api/analytics/endpoints/goals.ts
@@ -0,0 +1,156 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
+import type { GetSessionsResponse } from "./sessions";
+
+// Goal type
+export interface Goal {
+ goalId: number;
+ name: string | null;
+ goalType: "path" | "event";
+ config: {
+ pathPattern?: string;
+ eventName?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+ };
+ createdAt: string;
+ total_conversions: number;
+ total_sessions: number;
+ conversion_rate: number;
+}
+
+// Pagination meta type
+export interface PaginationMeta {
+ total: number;
+ page: number;
+ pageSize: number;
+ totalPages: number;
+}
+
+// Goals response type
+export interface GoalsResponse {
+ data: Goal[];
+ meta: PaginationMeta;
+}
+
+export interface GoalsParams extends CommonApiParams, PaginationParams, SortParams {
+ pageSize?: number;
+ sort?: "goalId" | "name" | "goalType" | "createdAt";
+ order?: "asc" | "desc";
+}
+
+export interface GoalSessionsParams extends CommonApiParams, PaginationParams {
+ goalId: number;
+}
+
+export interface CreateGoalParams {
+ name?: string;
+ goalType: "path" | "event";
+ config: {
+ pathPattern?: string;
+ eventName?: string;
+ eventPropertyKey?: string;
+ eventPropertyValue?: string | number | boolean;
+ };
+}
+
+export interface UpdateGoalParams extends CreateGoalParams {
+ goalId: number;
+}
+
+/**
+ * Fetch goals with pagination
+ * GET /api/goals/:site
+ */
+export async function fetchGoals(
+ site: string | number,
+ params: GoalsParams
+): Promise<GoalsResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ page: params.page,
+ page_size: params.pageSize ?? params.limit,
+ sort: params.sort,
+ order: params.order,
+ };
+
+ const response = await authedFetch<GoalsResponse>(`/goals/${site}`, queryParams);
+ return response;
+}
+
+/**
+ * Fetch sessions that completed a goal
+ * GET /api/goals/:goalId/sessions/:site
+ */
+export async function fetchGoalSessions(
+ site: string | number,
+ params: GoalSessionsParams
+): Promise<{ data: GetSessionsResponse }> {
+ const queryParams = {
+ ...toQueryParams(params),
+ page: params.page,
+ limit: params.limit,
+ };
+
+ const response = await authedFetch<{ data: GetSessionsResponse }>(
+ `/goals/${params.goalId}/sessions/${site}`,
+ queryParams
+ );
+ return response;
+}
+
+/**
+ * Create a new goal
+ * POST /api/goals/:site
+ */
+export async function createGoal(
+ site: string | number,
+ params: CreateGoalParams
+): Promise<{ success: boolean; goalId: number }> {
+ const response = await authedFetch<{ success: boolean; goalId: number }>(
+ `/goals/${site}`,
+ undefined,
+ {
+ method: "POST",
+ data: params,
+ }
+ );
+ return response;
+}
+
+/**
+ * Update an existing goal
+ * PUT /api/goals/:goalId/:site
+ */
+export async function updateGoal(
+ site: string | number,
+ params: UpdateGoalParams
+): Promise<{ success: boolean; goalId: number }> {
+ const response = await authedFetch<{ success: boolean; goalId: number }>(
+ `/goals/${params.goalId}/${site}`,
+ undefined,
+ {
+ method: "PUT",
+ data: params,
+ }
+ );
+ return response;
+}
+
+/**
+ * Delete a goal
+ * DELETE /api/goals/:goalId/:site
+ */
+export async function deleteGoal(
+ site: string | number,
+ goalId: number
+): Promise<{ success: boolean }> {
+ const response = await authedFetch<{ success: boolean }>(
+ `/goals/${goalId}/${site}`,
+ undefined,
+ {
+ method: "DELETE",
+ }
+ );
+ return response;
+}
diff --git a/client/src/api/analytics/endpoints/index.ts b/client/src/api/analytics/endpoints/index.ts
new file mode 100644
index 000000000..4d5e6230a
--- /dev/null
+++ b/client/src/api/analytics/endpoints/index.ts
@@ -0,0 +1,130 @@
+// Types
+export * from "./types";
+
+// Overview endpoints
+export { fetchOverview, fetchOverviewBucketed, fetchMetric, fetchLiveUserCount } from "./overview";
+export type {
+ GetOverviewResponse,
+ GetOverviewBucketedResponse,
+ MetricResponse,
+ LiveUserCountResponse,
+} from "./overview";
+
+// Events endpoints
+export { fetchEvents, fetchEventNames, fetchEventProperties, fetchOutboundLinks } from "./events";
+export type {
+ Event,
+ EventsResponse,
+ EventName,
+ EventProperty,
+ OutboundLink,
+ EventsParams,
+ EventPropertiesParams,
+} from "./events";
+
+// Errors endpoints
+export { fetchErrorNames, fetchErrorEvents, fetchErrorBucketed } from "./errors";
+export type {
+ ErrorNameItem,
+ ErrorNamesPaginatedResponse,
+ ErrorNamesStandardResponse,
+ ErrorEvent,
+ ErrorEventsPaginatedResponse,
+ ErrorEventsStandardResponse,
+ GetErrorBucketedResponse,
+ ErrorNamesParams,
+ ErrorEventsParams,
+ ErrorBucketedParams,
+} from "./errors";
+
+// Goals endpoints
+export { fetchGoals, fetchGoalSessions, createGoal, updateGoal, deleteGoal } from "./goals";
+export type {
+ Goal,
+ PaginationMeta,
+ GoalsResponse,
+ GoalsParams,
+ GoalSessionsParams,
+ CreateGoalParams,
+ UpdateGoalParams,
+} from "./goals";
+
+// Funnels endpoints
+export { fetchFunnels, analyzeFunnel, fetchFunnelStepSessions, saveFunnel, deleteFunnel } from "./funnels";
+export type {
+ SavedFunnel,
+ FunnelStep,
+ FunnelRequest,
+ SaveFunnelRequest,
+ FunnelResponse,
+ AnalyzeFunnelParams,
+ FunnelStepSessionsParams,
+ SaveFunnelParams,
+} from "./funnels";
+
+// Performance endpoints
+export { fetchPerformanceOverview, fetchPerformanceTimeSeries, fetchPerformanceByDimension } from "./performance";
+export type {
+ GetPerformanceOverviewResponse,
+ GetPerformanceTimeSeriesResponse,
+ PerformanceByDimensionItem,
+ PerformanceOverviewParams,
+ PerformanceTimeSeriesParams,
+ PerformanceByDimensionParams,
+ PaginatedPerformanceResponse,
+} from "./performance";
+
+// Sessions endpoints
+export { fetchSessions, fetchSession, fetchSessionLocations } from "./sessions";
+export type {
+ GetSessionsResponse,
+ SessionDetails,
+ SessionEvent,
+ SessionEventProps,
+ SessionPageviewsAndEvents,
+ LiveSessionLocation,
+ SessionsParams,
+ SessionDetailsParams,
+} from "./sessions";
+
+// Users endpoints
+export { fetchUsers, fetchUserSessionCount, fetchUserInfo } from "./users";
+export type {
+ UsersResponse,
+ UserInfo,
+ LinkedDevice,
+ UserSessionCountResponse,
+ UsersParams,
+ UserSessionsParams,
+ UserSessionCountParams,
+ UsersListResponse,
+} from "./users";
+
+// Misc endpoints (retention, journeys, page titles, org event count)
+export { fetchRetention, fetchJourneys, fetchPageTitles, fetchOrgEventCount } from "./misc";
+export type {
+ ProcessedRetentionData,
+ RetentionMode,
+ Journey,
+ JourneysResponse,
+ RetentionParams,
+ JourneysParams,
+ PageTitleItem,
+ PageTitlesPaginatedResponse,
+ PageTitlesStandardResponse,
+ PageTitlesParams,
+ OrgEventCountResponse,
+ GetOrgEventCountResponse,
+ OrgEventCountParams,
+} from "./misc";
+
+// Session Replay endpoints
+export { fetchSessionReplays, fetchSessionReplayEvents, deleteSessionReplay } from "./sessionReplay";
+export type {
+ SessionReplayListItem,
+ SessionReplayListResponse,
+ SessionReplayEvent,
+ SessionReplayMetadata,
+ GetSessionReplayEventsResponse,
+ SessionReplaysParams,
+} from "./sessionReplay";
diff --git a/client/src/api/analytics/endpoints/misc.ts b/client/src/api/analytics/endpoints/misc.ts
new file mode 100644
index 000000000..c1e2440c1
--- /dev/null
+++ b/client/src/api/analytics/endpoints/misc.ts
@@ -0,0 +1,156 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+
+// Retention types
+export interface ProcessedRetentionData {
+ cohorts: Record<string, { size: number; percentages: (number | null)[] }>;
+ maxPeriods: number;
+ mode: "day" | "week";
+ range: number;
+}
+
+export type RetentionMode = "day" | "week";
+
+// Journey types
+export interface Journey {
+ path: string[];
+ count: number;
+ percentage: number;
+}
+
+export interface JourneysResponse {
+ journeys: Journey[];
+}
+
+// Page title types
+export type PageTitleItem = {
+ value: string; // The page_title
+ pathname: string; // A representative pathname
+ count: number;
+ percentage: number;
+ time_on_page_seconds?: number;
+};
+
+export type PageTitlesPaginatedResponse = {
+ data: PageTitleItem[];
+ totalCount: number;
+};
+
+export type PageTitlesStandardResponse = PageTitleItem[];
+
+// Org event count types
+export type OrgEventCountResponse = {
+ event_date: string;
+ pageview_count: number;
+ custom_event_count: number;
+ performance_count: number;
+ event_count: number;
+}[];
+
+export type GetOrgEventCountResponse = {
+ data: OrgEventCountResponse;
+};
+
+export interface RetentionParams {
+ mode?: RetentionMode;
+ range?: number;
+}
+
+export interface JourneysParams extends CommonApiParams {
+ steps?: number;
+ limit?: number;
+ stepFilters?: Record<number, string>;
+}
+
+/**
+ * Fetch retention cohort data
+ * GET /api/retention/:site
+ */
+export async function fetchRetention(
+ site: string | number,
+ params: RetentionParams = {}
+): Promise<ProcessedRetentionData> {
+ const { mode = "week", range = 90 } = params;
+
+ const response = await authedFetch<{ data: ProcessedRetentionData }>(
+ `/retention/${site}`,
+ { mode, range }
+ );
+ return response.data;
+}
+
+/**
+ * Fetch user journey paths
+ * GET /api/journeys/:site
+ */
+export async function fetchJourneys(
+ site: string | number,
+ params: JourneysParams
+): Promise<JourneysResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ steps: params.steps ?? 3,
+ limit: params.limit ?? 100,
+ stepFilters:
+ params.stepFilters && Object.keys(params.stepFilters).length > 0
+ ? JSON.stringify(params.stepFilters)
+ : undefined,
+ };
+
+ const response = await authedFetch<JourneysResponse>(
+ `/journeys/${site}`,
+ queryParams
+ );
+ return response;
+}
+
+export interface PageTitlesParams extends CommonApiParams, PaginationParams {
+ useFilters?: boolean;
+}
+
+export interface OrgEventCountParams {
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}
+
+/**
+ * Fetch page titles with pagination
+ * GET /api/page-titles/:site
+ */
+export async function fetchPageTitles(
+ site: string | number,
+ params: PageTitlesParams
+): Promise<PageTitlesPaginatedResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ limit: params.limit,
+ page: params.page,
+ };
+
+ const response = await authedFetch<{ data: PageTitlesPaginatedResponse }>(
+ `/page-titles/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch organization event count
+ * GET /api/org-event-count/:organizationId
+ */
+export async function fetchOrgEventCount(
+ organizationId: string,
+ params: OrgEventCountParams = {}
+): Promise<GetOrgEventCountResponse> {
+ const queryParams: Record<string, string> = {};
+ if (params.startDate) queryParams.start_date = params.startDate;
+ if (params.endDate) queryParams.end_date = params.endDate;
+ if (params.timeZone) queryParams.time_zone = params.timeZone;
+
+ const response = await authedFetch<GetOrgEventCountResponse>(
+ `/org-event-count/${organizationId}`,
+ queryParams
+ );
+ return response;
+}
diff --git a/client/src/api/analytics/endpoints/overview.ts b/client/src/api/analytics/endpoints/overview.ts
new file mode 100644
index 000000000..ad028c014
--- /dev/null
+++ b/client/src/api/analytics/endpoints/overview.ts
@@ -0,0 +1,106 @@
+import { authedFetch } from "../../utils";
+import {
+ CommonApiParams,
+ BucketedParams,
+ MetricParams,
+ toQueryParams,
+ toBucketedQueryParams,
+ toMetricQueryParams,
+} from "./types";
+
+// Overview response type
+export type GetOverviewResponse = {
+ sessions: number;
+ pageviews: number;
+ users: number;
+ pages_per_session: number;
+ bounce_rate: number;
+ session_duration: number;
+};
+
+// Overview bucketed response type
+export type GetOverviewBucketedResponse = {
+ time: string;
+ pageviews: number;
+ sessions: number;
+ pages_per_session: number;
+ bounce_rate: number;
+ session_duration: number;
+ users: number;
+}[];
+
+// Metric response type
+export type MetricResponse = {
+ value: string;
+ title?: string;
+ count: number;
+ percentage: number;
+ pageviews?: number;
+ pageviews_percentage?: number;
+ time_on_page_seconds?: number;
+ bounce_rate?: number;
+};
+
+// Live user count response type
+export interface LiveUserCountResponse {
+ count: number;
+}
+
+/**
+ * Fetch overview metrics for a site
+ * GET /api/overview/:site
+ */
+export async function fetchOverview(
+ site: string | number,
+ params: CommonApiParams
+): Promise<GetOverviewResponse> {
+ const response = await authedFetch<{ data: GetOverviewResponse }>(
+ `/overview/${site}`,
+ toQueryParams(params)
+ );
+ return response.data;
+}
+
+/**
+ * Fetch time-series overview data
+ * GET /api/overview-bucketed/:site
+ */
+export async function fetchOverviewBucketed(
+ site: string | number,
+ params: BucketedParams
+): Promise<GetOverviewBucketedResponse> {
+ const response = await authedFetch<{ data: GetOverviewBucketedResponse }>(
+ `/overview-bucketed/${site}`,
+ toBucketedQueryParams(params)
+ );
+ return response.data;
+}
+
+/**
+ * Fetch dimensional metric data
+ * GET /api/metric/:site
+ */
+export async function fetchMetric(
+ site: string | number,
+ params: MetricParams
+): Promise<{ data: MetricResponse[]; totalCount: number }> {
+ const response = await authedFetch<{
+ data: { data: MetricResponse[]; totalCount: number };
+ }>(`/metric/${site}`, toMetricQueryParams(params));
+ return response.data;
+}
+
+/**
+ * Fetch live user count
+ * GET /api/live-user-count/:site
+ */
+export async function fetchLiveUserCount(
+ site: string | number,
+ minutes: number = 5
+): Promise<LiveUserCountResponse> {
+ const response = await authedFetch<LiveUserCountResponse>(
+ `/live-user-count/${site}`,
+ { minutes }
+ );
+ return response;
+}
diff --git a/client/src/api/analytics/endpoints/performance.ts b/client/src/api/analytics/endpoints/performance.ts
new file mode 100644
index 000000000..5a3047b0d
--- /dev/null
+++ b/client/src/api/analytics/endpoints/performance.ts
@@ -0,0 +1,164 @@
+import { TimeBucket } from "@rybbit/shared";
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
+
+// Performance Overview Response
+export type GetPerformanceOverviewResponse = {
+ current: {
+ lcp: number;
+ cls: number;
+ inp: number;
+ fcp: number;
+ ttfb: number;
+ };
+ previous: {
+ lcp: number;
+ cls: number;
+ inp: number;
+ fcp: number;
+ ttfb: number;
+ };
+};
+
+// Performance Time Series Response
+export type GetPerformanceTimeSeriesResponse = {
+ time: string;
+ event_count: number;
+ lcp_p50: number | null;
+ lcp_p75: number | null;
+ lcp_p90: number | null;
+ lcp_p99: number | null;
+ cls_p50: number | null;
+ cls_p75: number | null;
+ cls_p90: number | null;
+ cls_p99: number | null;
+ inp_p50: number | null;
+ inp_p75: number | null;
+ inp_p90: number | null;
+ inp_p99: number | null;
+ fcp_p50: number | null;
+ fcp_p75: number | null;
+ fcp_p90: number | null;
+ fcp_p99: number | null;
+ ttfb_p50: number | null;
+ ttfb_p75: number | null;
+ ttfb_p90: number | null;
+ ttfb_p99: number | null;
+}[];
+
+// Performance By Dimension Item
+export type PerformanceByDimensionItem = {
+ [key: string]: any;
+ event_count: number;
+ lcp_avg: number | null;
+ lcp_p50: number | null;
+ lcp_p75: number | null;
+ lcp_p90: number | null;
+ lcp_p99: number | null;
+ cls_avg: number | null;
+ cls_p50: number | null;
+ cls_p75: number | null;
+ cls_p90: number | null;
+ cls_p99: number | null;
+ inp_avg: number | null;
+ inp_p50: number | null;
+ inp_p75: number | null;
+ inp_p90: number | null;
+ inp_p99: number | null;
+ fcp_avg: number | null;
+ fcp_p50: number | null;
+ fcp_p75: number | null;
+ fcp_p90: number | null;
+ fcp_p99: number | null;
+ ttfb_avg: number | null;
+ ttfb_p50: number | null;
+ ttfb_p75: number | null;
+ ttfb_p90: number | null;
+ ttfb_p99: number | null;
+};
+
+export interface PerformanceOverviewParams extends CommonApiParams {
+ percentile?: number | string;
+}
+
+export interface PerformanceTimeSeriesParams extends CommonApiParams {
+ bucket: TimeBucket;
+}
+
+export interface PerformanceByDimensionParams
+ extends CommonApiParams,
+ PaginationParams,
+ SortParams {
+ dimension: string;
+ percentile?: number | string;
+}
+
+export interface PaginatedPerformanceResponse {
+ data: PerformanceByDimensionItem[];
+ totalCount: number;
+}
+
+/**
+ * Fetch performance overview (Core Web Vitals)
+ * GET /api/performance/overview/:site
+ */
+export async function fetchPerformanceOverview(
+ site: string | number,
+ params: PerformanceOverviewParams
+): Promise<GetPerformanceOverviewResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ percentile: params.percentile,
+ };
+
+ const response = await authedFetch<{ data: GetPerformanceOverviewResponse }>(
+ `/performance/overview/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch performance time series data
+ * GET /api/performance/time-series/:site
+ */
+export async function fetchPerformanceTimeSeries(
+ site: string | number,
+ params: PerformanceTimeSeriesParams
+): Promise<GetPerformanceTimeSeriesResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ bucket: params.bucket,
+ };
+
+ const response = await authedFetch<{ data: GetPerformanceTimeSeriesResponse }>(
+ `/performance/time-series/${site}`,
+ queryParams
+ );
+ return response.data;
+}
+
+/**
+ * Fetch performance broken down by dimension
+ * GET /api/performance/by-dimension/:site
+ */
+export async function fetchPerformanceByDimension(
+ site: string | number,
+ params: PerformanceByDimensionParams
+): Promise<PaginatedPerformanceResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ dimension: params.dimension,
+ limit: params.limit,
+ page: params.page,
+ sort_by: params.sortBy,
+ sort_order: params.sortOrder,
+ percentile: params.percentile,
+ };
+
+ const response = await authedFetch<{ data: PaginatedPerformanceResponse }>(
+ `/performance/by-dimension/${site}`,
+ queryParams
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/endpoints/sessionReplay.ts b/client/src/api/analytics/endpoints/sessionReplay.ts
new file mode 100644
index 000000000..76bdb52c0
--- /dev/null
+++ b/client/src/api/analytics/endpoints/sessionReplay.ts
@@ -0,0 +1,126 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, toQueryParams } from "./types";
+
+// Session replay list item type
+export interface SessionReplayListItem {
+ session_id: string;
+ user_id: string;
+ identified_user_id: string;
+ traits: Record<string, unknown> | null;
+ start_time: string;
+ end_time?: string;
+ duration_ms?: number;
+ page_url: string;
+ event_count: number;
+ country: string;
+ region: string;
+ city: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ device_type: string;
+ screen_width: number;
+ screen_height: number;
+}
+
+// Session replay list response type
+export interface SessionReplayListResponse {
+ data: SessionReplayListItem[];
+ totalCount: number;
+}
+
+// Session replay event type
+export interface SessionReplayEvent {
+ timestamp: number;
+ type: string | number;
+ data: any;
+}
+
+// Session replay metadata type
+export interface SessionReplayMetadata {
+ session_id: string;
+ user_id: string;
+ identified_user_id: string;
+ traits: Record<string, unknown> | null;
+ start_time: Date;
+ end_time?: Date;
+ duration_ms?: number;
+ event_count: number;
+ compressed_size_bytes: number;
+ page_url: string;
+ user_agent: string;
+ country: string;
+ region: string;
+ city: string;
+ lat: number;
+ lon: number;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ language: string;
+ screen_width: number;
+ screen_height: number;
+ device_type: string;
+ channel: string;
+ hostname: string;
+ referrer: string;
+ has_replay_data: boolean;
+ created_at: Date;
+}
+
+// Get session replay events response type
+export interface GetSessionReplayEventsResponse {
+ events: SessionReplayEvent[];
+ metadata: SessionReplayMetadata;
+}
+
+// Session replays params
+export interface SessionReplaysParams extends CommonApiParams {
+ limit?: number;
+ offset?: number;
+ minDuration?: number;
+}
+
+/**
+ * Fetch session replays list
+ * GET /api/session-replay/list/:site
+ */
+export async function fetchSessionReplays(
+ site: string | number,
+ params: SessionReplaysParams
+): Promise<SessionReplayListResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ limit: params.limit,
+ offset: params.offset,
+ min_duration: params.minDuration,
+ };
+
+ const response = await authedFetch<SessionReplayListResponse>(`/session-replay/list/${site}`, queryParams);
+ return response;
+}
+
+/**
+ * Fetch session replay events for a specific session
+ * GET /api/session-replay/:sessionId/:site
+ */
+export async function fetchSessionReplayEvents(
+ site: string | number,
+ sessionId: string
+): Promise<GetSessionReplayEventsResponse> {
+ const response = await authedFetch<GetSessionReplayEventsResponse>(`/session-replay/${sessionId}/${site}`);
+ return response;
+}
+
+/**
+ * Delete a session replay
+ * DELETE /api/session-replay/:sessionId/:site
+ */
+export async function deleteSessionReplay(site: string | number, sessionId: string): Promise<{ success: boolean }> {
+ const response = await authedFetch<{ success: boolean }>(`/session-replay/${sessionId}/${site}`, undefined, {
+ method: "DELETE",
+ });
+ return response;
+}
diff --git a/client/src/api/analytics/endpoints/sessions.ts b/client/src/api/analytics/endpoints/sessions.ts
new file mode 100644
index 000000000..9e7e192dc
--- /dev/null
+++ b/client/src/api/analytics/endpoints/sessions.ts
@@ -0,0 +1,184 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, toQueryParams } from "./types";
+
+// Session response type
+export type GetSessionsResponse = {
+ session_id: string;
+ user_id: string; // Device fingerprint
+ identified_user_id: string; // Custom user ID when identified, empty string otherwise
+ traits: Record<string, unknown> | null;
+ country: string;
+ region: string;
+ city: string;
+ language: string;
+ device_type: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ screen_width: number;
+ screen_height: number;
+ referrer: string;
+ channel: string;
+ hostname: string;
+ page_title: string;
+ querystring: string;
+ utm_source: string;
+ utm_medium: string;
+ utm_campaign: string;
+ utm_term: string;
+ utm_content: string;
+ session_end: string;
+ session_start: string;
+ session_duration: number;
+ entry_page: string;
+ exit_page: string;
+ pageviews: number;
+ events: number;
+ errors: number;
+ outbound: number;
+ ip: string;
+ lat: number;
+ lon: number;
+}[];
+
+// Session details type
+export interface SessionDetails {
+ session_id: string;
+ user_id: string;
+ country: string;
+ region: string;
+ city: string;
+ language: string;
+ device_type: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ screen_width: number;
+ screen_height: number;
+ referrer: string;
+ channel: string;
+ session_end: string;
+ session_start: string;
+ pageviews: number;
+ entry_page: string;
+ exit_page: string;
+ ip: string;
+}
+
+// Session event props type
+export interface SessionEventProps {
+ [key: string]: unknown;
+ // Error-specific props
+ message?: string;
+ stack?: string;
+}
+
+// Session event type
+export interface SessionEvent {
+ timestamp: string;
+ pathname: string;
+ hostname: string;
+ querystring: string;
+ page_title: string;
+ referrer: string;
+ type: string;
+ event_name?: string;
+ props?: SessionEventProps;
+}
+
+// Session pageviews and events response
+export interface SessionPageviewsAndEvents {
+ session: SessionDetails;
+ events: SessionEvent[];
+ pagination: {
+ total: number;
+ limit: number;
+ offset: number;
+ hasMore: boolean;
+ };
+}
+
+// Live session location type (for map)
+export type LiveSessionLocation = {
+ lat: number;
+ lon: number;
+ count: number;
+ city: string;
+ country: string;
+};
+
+export interface SessionsParams extends CommonApiParams, PaginationParams {
+ userId?: string;
+ identifiedOnly?: boolean;
+}
+
+export interface SessionDetailsParams {
+ sessionId: string;
+ limit?: number;
+ offset?: number;
+ minutes?: number;
+}
+
+/**
+ * Fetch sessions list
+ * GET /api/sessions/:site
+ */
+export async function fetchSessions(
+ site: string | number,
+ params: SessionsParams
+): Promise<{ data: GetSessionsResponse }> {
+ const queryParams = {
+ ...toQueryParams(params),
+ page: params.page,
+ limit: params.limit,
+ user_id: params.userId,
+ identified_only: params.identifiedOnly,
+ };
+
+ const response = await authedFetch<{ data: GetSessionsResponse }>(
+ `/sessions/${site}`,
+ queryParams
+ );
+ return response;
+}
+
+/**
+ * Fetch details of a specific session
+ * GET /api/sessions/:sessionId/:site
+ */
+export async function fetchSession(
+ site: string | number,
+ params: SessionDetailsParams
+): Promise<{ data: SessionPageviewsAndEvents }> {
+ const queryParams: Record<string, any> = {
+ limit: params.limit,
+ offset: params.offset,
+ };
+
+ if (params.minutes) {
+ queryParams.minutes = params.minutes;
+ }
+
+ const response = await authedFetch<{ data: SessionPageviewsAndEvents }>(
+ `/sessions/${params.sessionId}/${site}`,
+ queryParams
+ );
+ return response;
+}
+
+/**
+ * Fetch session locations for map visualization
+ * GET /api/session-locations/:site
+ */
+export async function fetchSessionLocations(
+ site: string | number,
+ params: CommonApiParams
+): Promise<LiveSessionLocation[]> {
+ const response = await authedFetch<{ data: LiveSessionLocation[] }>(
+ `/session-locations/${site}`,
+ toQueryParams(params)
+ );
+ return response.data;
+}
diff --git a/client/src/api/analytics/endpoints/types.ts b/client/src/api/analytics/endpoints/types.ts
new file mode 100644
index 000000000..38770fe73
--- /dev/null
+++ b/client/src/api/analytics/endpoints/types.ts
@@ -0,0 +1,93 @@
+import { Filter, FilterParameter, TimeBucket } from "@rybbit/shared";
+
+/**
+ * Common parameters shared across most analytics API endpoints
+ * Supports either date range mode OR past-minutes mode
+ */
+export interface CommonApiParams {
+ startDate: string; // YYYY-MM-DD format (empty string for past-minutes mode)
+ endDate: string; // YYYY-MM-DD format (empty string for past-minutes mode)
+ timeZone: string; // IANA timezone string
+ filters?: Filter[];
+ // Optional past-minutes mode params (when startDate/endDate are empty)
+ pastMinutesStart?: number;
+ pastMinutesEnd?: number;
+}
+
+/**
+ * Parameters for bucketed/time-series endpoints
+ */
+export interface BucketedParams extends CommonApiParams {
+ bucket: TimeBucket;
+}
+
+/**
+ * Pagination parameters
+ */
+export interface PaginationParams {
+ page?: number;
+ limit?: number;
+}
+
+/**
+ * Parameters for the metric endpoint
+ */
+export interface MetricParams extends CommonApiParams, PaginationParams {
+ parameter: FilterParameter;
+}
+
+/**
+ * Sort parameters for paginated endpoints
+ */
+export interface SortParams {
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+}
+
+/**
+ * Convert CommonApiParams to query params format expected by the API
+ * Handles both date range mode and past-minutes mode
+ */
+export function toQueryParams(params: CommonApiParams): Record<string, any> {
+ // Use past-minutes mode if pastMinutesStart is provided
+ if (params.pastMinutesStart !== undefined) {
+ return {
+ time_zone: params.timeZone,
+ past_minutes_start: params.pastMinutesStart,
+ past_minutes_end: params.pastMinutesEnd ?? 0,
+ filters: params.filters?.length ? params.filters : undefined,
+ };
+ }
+
+ // Default to date range mode
+ return {
+ start_date: params.startDate,
+ end_date: params.endDate,
+ time_zone: params.timeZone,
+ filters: params.filters?.length ? params.filters : undefined,
+ };
+}
+
+/**
+ * Convert BucketedParams to query params format
+ */
+export function toBucketedQueryParams(
+ params: BucketedParams
+): Record<string, any> {
+ return {
+ ...toQueryParams(params),
+ bucket: params.bucket,
+ };
+}
+
+/**
+ * Convert MetricParams to query params format
+ */
+export function toMetricQueryParams(params: MetricParams): Record<string, any> {
+ return {
+ ...toQueryParams(params),
+ parameter: params.parameter,
+ limit: params.limit,
+ page: params.page,
+ };
+}
diff --git a/client/src/api/analytics/endpoints/users.ts b/client/src/api/analytics/endpoints/users.ts
new file mode 100644
index 000000000..181751c9e
--- /dev/null
+++ b/client/src/api/analytics/endpoints/users.ts
@@ -0,0 +1,125 @@
+import { authedFetch } from "../../utils";
+import { CommonApiParams, PaginationParams, SortParams, toQueryParams } from "./types";
+import type { GetSessionsResponse } from "./sessions";
+
+// User response type
+export type UsersResponse = {
+ user_id: string; // Device fingerprint
+ identified_user_id: string; // Custom user ID when identified, empty string otherwise
+ traits: Record<string, unknown> | null;
+ country: string;
+ region: string;
+ city: string;
+ language: string;
+ browser: string;
+ operating_system: string;
+ device_type: string;
+ referrer: string;
+ channel: string;
+ pageviews: number;
+ events: number;
+ sessions: number;
+ last_seen: string;
+ first_seen: string;
+};
+
+// Linked device type
+export type LinkedDevice = {
+ anonymous_id: string;
+ created_at: string;
+};
+
+// User info type
+export type UserInfo = {
+ duration: number;
+ sessions: number;
+ user_id: string; // Device fingerprint
+ identified_user_id: string; // Custom user ID when identified, empty string otherwise
+ country: string;
+ region: string;
+ city: string;
+ language: string;
+ device_type: string;
+ browser: string;
+ browser_version: string;
+ operating_system: string;
+ operating_system_version: string;
+ screen_height: number;
+ screen_width: number;
+ last_seen: string;
+ first_seen: string;
+ pageviews: number;
+ events: number;
+ ip?: string;
+ traits: Record<string, unknown> | null;
+ linked_devices: LinkedDevice[];
+};
+
+// User session count response type
+export interface UserSessionCountResponse {
+ date: string;
+ sessions: number;
+}
+
+export interface UsersParams extends CommonApiParams, PaginationParams, SortParams {
+ pageSize?: number;
+ identifiedOnly?: boolean;
+}
+
+export interface UserSessionsParams extends CommonApiParams {
+ userId: string;
+}
+
+export interface UserSessionCountParams {
+ userId: string;
+ timeZone: string;
+}
+
+export interface UsersListResponse {
+ data: UsersResponse[];
+ totalCount: number;
+ page: number;
+ pageSize: number;
+}
+
+/**
+ * Fetch users list with pagination
+ * GET /api/users/:site
+ */
+export async function fetchUsers(site: string | number, params: UsersParams): Promise<UsersListResponse> {
+ const queryParams = {
+ ...toQueryParams(params),
+ page: params.page,
+ page_size: params.pageSize ?? params.limit,
+ sort_by: params.sortBy,
+ sort_order: params.sortOrder,
+ identified_only: params.identifiedOnly,
+ };
+
+ const response = await authedFetch<UsersListResponse>(`/users/${site}`, queryParams);
+ return response;
+}
+
+/**
+ * Fetch session count per day for a user
+ * GET /api/users/session-count/:site
+ */
+export async function fetchUserSessionCount(
+ site: string | number,
+ params: UserSessionCountParams
+): Promise<{ data: UserSessionCountResponse[] }> {
+ const response = await authedFetch<{ data: UserSessionCountResponse[] }>(`/users/session-count/${site}`, {
+ user_id: params.userId,
+ time_zone: params.timeZone,
+ });
+ return response;
+}
+
+/**
+ * Fetch detailed user information
+ * GET /api/users/:userId/:site
+ */
+export async function fetchUserInfo(site: string | number, userId: string): Promise<UserInfo> {
+ const response = await authedFetch<{ data: UserInfo }>(`/users/${userId}/${site}`);
+ return response.data;
+}
diff --git a/client/src/api/analytics/errors/useGetErrorEvents.ts b/client/src/api/analytics/errors/useGetErrorEvents.ts
deleted file mode 100644
index ef8746f63..000000000
--- a/client/src/api/analytics/errors/useGetErrorEvents.ts
+++ /dev/null
@@ -1,77 +0,0 @@
-import { useStore } from "@/lib/store";
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { APIResponse } from "../../types";
-import { authedFetch, getQueryParams } from "../../utils";
-
-// This should match ErrorEvent from the backend
-export type ErrorEvent = {
- timestamp: string;
- session_id: string;
- user_id: string | null;
- pathname: string | null;
- hostname: string | null;
- page_title: string | null;
- referrer: string | null;
- browser: string | null;
- browser_version: string | null;
- operating_system: string | null;
- operating_system_version: string | null;
- device_type: string | null;
- country: string | null;
- city: string | null;
- region: string | null;
- // Parsed error properties (now from backend)
- message: string;
- stack: string | null;
- fileName: string | null;
- lineNumber: number | null;
- columnNumber: number | null;
-};
-
-// This should match the paginated response structure from getErrorEvents.ts
-export type ErrorEventsPaginatedResponse = {
- data: ErrorEvent[];
- totalCount: number;
-};
-
-// This is for non-paginated use
-export type ErrorEventsStandardResponse = ErrorEvent[];
-
-type UseGetErrorEventsOptions = {
- errorMessage: string;
- limit?: number;
- page?: number;
- useFilters?: boolean;
- enabled?: boolean;
-};
-
-// Hook for infinite scrolling
-export function useGetErrorEventsInfinite(errorMessage: string, enabled: boolean = true) {
- const { time, site, filters } = useStore();
-
- return useInfiniteQuery({
- queryKey: ["error-events-infinite", time, site, filters, errorMessage],
- queryFn: async ({ pageParam = 1 }) => {
- const queryParams = {
- ...getQueryParams(time),
- errorMessage,
- limit: 20,
- page: pageParam,
- filters,
- };
-
- return authedFetch<APIResponse<ErrorEventsPaginatedResponse>>(`/error-events/${site}`, queryParams);
- },
- initialPageParam: 1,
- getNextPageParam: (lastPage: APIResponse<ErrorEventsPaginatedResponse>, allPages) => {
- const currentPage = allPages.length;
- const totalItems = lastPage.data?.totalCount || 0;
- const itemsPerPage = 20;
- const totalPages = Math.ceil(totalItems / itemsPerPage);
-
- return currentPage < totalPages ? currentPage + 1 : undefined;
- },
- enabled: enabled && !!errorMessage && !!site,
- staleTime: Infinity,
- });
-}
diff --git a/client/src/api/analytics/errors/useGetErrorNames.ts b/client/src/api/analytics/errors/useGetErrorNames.ts
deleted file mode 100644
index cafadeb51..000000000
--- a/client/src/api/analytics/errors/useGetErrorNames.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import { useStore } from "@/lib/store";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { APIResponse } from "../../types";
-import { authedFetch, getQueryParams } from "../../utils";
-
-// This should match ErrorNameItem from the backend
-export type ErrorNameItem = {
- value: string; // Error message
- errorName: string; // Error type (TypeError, ReferenceError, etc.)
- count: number; // Total occurrences
- sessionCount: number; // Unique sessions affected
- percentage: number;
-};
-
-// This should match the paginated response structure from getErrorNames.ts
-export type ErrorNamesPaginatedResponse = {
- data: ErrorNameItem[];
- totalCount: number;
-};
-
-// This is for non-paginated use by StandardSection (or similar)
-export type ErrorNamesStandardResponse = ErrorNameItem[];
-
-type UseGetErrorNamesOptions = {
- limit?: number;
- page?: number;
- useFilters?: boolean;
-};
-
-// Hook for paginated fetching (e.g., for a dedicated "All Errors" screen)
-export function useGetErrorNamesPaginated({
- limit = 10,
- page = 1,
- useFilters = true,
-}: UseGetErrorNamesOptions): UseQueryResult<APIResponse<ErrorNamesPaginatedResponse>> {
- const { time, site, filters } = useStore();
-
- const queryParams = {
- ...getQueryParams(time),
- limit,
- page,
- filters: useFilters ? filters : undefined,
- };
-
- return useQuery({
- queryKey: ["error-names", time, site, filters, limit, page],
- queryFn: () => {
- return authedFetch<APIResponse<ErrorNamesPaginatedResponse>>(`/error-names/${site}`, queryParams);
- },
- staleTime: Infinity,
- });
-}
-
-// Hook for standard (non-paginated) fetching
-export function useGetErrorNames({
- limit = 10,
- useFilters = true,
-}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<APIResponse<ErrorNamesStandardResponse>> {
- const { time, site, filters } = useStore();
-
- const queryParams = {
- ...getQueryParams(time),
- limit,
- filters: useFilters ? filters : undefined,
- };
-
- return useQuery({
- queryKey: ["error-names", time, site, filters, limit],
- queryFn: () => {
- return authedFetch<APIResponse<ErrorNamesStandardResponse>>(`/error-names/${site}`, queryParams);
- },
- staleTime: Infinity,
- });
-}
diff --git a/client/src/api/analytics/events/useGetEventNames.ts b/client/src/api/analytics/events/useGetEventNames.ts
deleted file mode 100644
index 31e846a55..000000000
--- a/client/src/api/analytics/events/useGetEventNames.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { Time } from "../../../components/DateSelector/types";
-import { EVENT_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters, useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type EventName = {
- eventName: string;
- count: number;
-};
-
-export function useGetEventNames() {
- const { site, time, filters } = useStore();
-
- const timeParams = getQueryParams(time);
- const filteredFilters = getFilteredFilters(EVENT_FILTERS);
-
- return useQuery({
- queryKey: ["event-names", site, timeParams, filteredFilters],
- enabled: !!site,
- queryFn: () => {
- const params = {
- ...timeParams,
- filters: filteredFilters.length > 0 ? filteredFilters : undefined,
- };
-
- return authedFetch<{ data: EventName[] }>(`/events/names/${site}`, params).then(res => res.data);
- },
- });
-}
-
-/**
- * Standalone fetch function for event names (used for exports)
- */
-export async function fetchEventNames(
- site: number | string,
- time: Time,
- filters: Filter[] = []
-): Promise<EventName[]> {
- const timeParams = getQueryParams(time);
- const params = {
- ...timeParams,
- filters: filters.length > 0 ? filters : undefined,
- };
- const response = await authedFetch<{ data: EventName[] }>(
- `/events/names/${site}`,
- params
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/events/useGetEventProperties.ts b/client/src/api/analytics/events/useGetEventProperties.ts
deleted file mode 100644
index fd8614c72..000000000
--- a/client/src/api/analytics/events/useGetEventProperties.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { getFilteredFilters, useStore } from "../../../lib/store";
-import { EVENT_FILTERS } from "../../../lib/filterGroups";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type EventProperty = {
- propertyKey: string;
- propertyValue: string;
- count: number;
-};
-
-export function useGetEventProperties(eventName: string | null) {
- const { site, time, filters } = useStore();
-
- const timeParams = getQueryParams(time);
- const filteredFilters = getFilteredFilters(EVENT_FILTERS);
-
- return useQuery({
- queryKey: ["event-properties", site, eventName, timeParams, filteredFilters],
- enabled: !!site && !!eventName,
- queryFn: () => {
- const params = {
- ...timeParams,
- event_name: eventName,
- filters: filteredFilters.length > 0 ? filteredFilters : undefined,
- };
-
- return authedFetch<{ data: EventProperty[] }>(`/events/properties/${site}`, params).then(res => res.data);
- },
- });
-}
diff --git a/client/src/api/analytics/events/useGetOutboundLinks.ts b/client/src/api/analytics/events/useGetOutboundLinks.ts
deleted file mode 100644
index b7a607d3a..000000000
--- a/client/src/api/analytics/events/useGetOutboundLinks.ts
+++ /dev/null
@@ -1,52 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { Time } from "../../../components/DateSelector/types";
-import { EVENT_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters, useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type OutboundLink = {
- url: string;
- count: number;
- lastClicked: string;
-};
-
-export function useGetOutboundLinks() {
- const { site, time, filters } = useStore();
-
- const timeParams = getQueryParams(time);
- const filteredFilters = getFilteredFilters(EVENT_FILTERS);
-
- return useQuery({
- queryKey: ["outbound-links", site, timeParams, filteredFilters],
- enabled: !!site,
- queryFn: () => {
- const params = {
- ...timeParams,
- filters: filteredFilters.length > 0 ? filteredFilters : undefined,
- };
-
- return authedFetch<{ data: OutboundLink[] }>(`/events/outbound/${site}`, params).then(res => res.data);
- },
- });
-}
-
-/**
- * Standalone fetch function for outbound links (used for exports)
- */
-export async function fetchOutboundLinks(
- site: number | string,
- time: Time,
- filters: Filter[] = []
-): Promise<OutboundLink[]> {
- const timeParams = getQueryParams(time);
- const params = {
- ...timeParams,
- filters: filters.length > 0 ? filters : undefined,
- };
- const response = await authedFetch<{ data: OutboundLink[] }>(
- `/events/outbound/${site}`,
- params
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/funnels/useGetFunnel.ts b/client/src/api/analytics/funnels/useGetFunnel.ts
deleted file mode 100644
index 38a5be54e..000000000
--- a/client/src/api/analytics/funnels/useGetFunnel.ts
+++ /dev/null
@@ -1,108 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useDebounce } from "@uidotdev/usehooks";
-import { timeZone } from "../../../lib/dateTimeUtils";
-import { FUNNEL_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters, useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type FunnelStep = {
- value: string;
- name?: string;
- type: "page" | "event";
- hostname?: string;
- eventPropertyKey?: string;
- eventPropertyValue?: string | number | boolean;
-};
-
-export type FunnelRequest = {
- steps: FunnelStep[];
- name?: string;
-};
-
-export type SaveFunnelRequest = {
- steps: FunnelStep[];
- name: string;
- reportId?: number;
-};
-
-export type FunnelResponse = {
- step_number: number;
- step_name: string;
- visitors: number;
- conversion_rate: number;
- dropoff_rate: number;
-};
-
-/**
- * Hook for analyzing conversion funnels through a series of steps
- */
-export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {
- const { site, time } = useStore();
-
- const debouncedConfig = useDebounce(config, 500);
-
- const queryParams = getQueryParams(time, { filters: getFilteredFilters(FUNNEL_PAGE_FILTERS) });
-
- const configToUse = debounce ? debouncedConfig : config;
-
- return useQuery<FunnelResponse[], Error>({
- queryKey: ["funnel", site, queryParams, configToUse?.steps.map(s => s.value + s.type)],
- queryFn: async () => {
- if (!configToUse) {
- throw new Error("Funnel configuration is required");
- }
-
- // Add time zone to the request
- const fullConfig = {
- ...configToUse,
- };
- try {
- const response = await authedFetch<{ data: FunnelResponse[] }>(`/funnels/analyze/${site}`, queryParams, {
- method: "POST",
- data: fullConfig,
- });
-
- return response.data;
- } catch (error) {
- throw new Error("Failed to analyze funnel");
- }
- },
- enabled: !!site && !!configToUse,
- });
-}
-
-/**
- * Hook for saving funnel configurations without analyzing them
- */
-export function useSaveFunnel() {
- const { site } = useStore();
- const queryClient = useQueryClient();
-
- return useMutation<{ success: boolean; funnelId: number }, Error, SaveFunnelRequest>({
- mutationFn: async funnelConfig => {
- // Add time zone to the request
- const fullConfig = {
- ...funnelConfig,
- timeZone,
- };
-
- try {
- // Save the funnel configuration
- const saveResponse = await authedFetch<{
- success: boolean;
- funnelId: number;
- }>(`/funnels/${site}`, undefined, {
- method: "POST",
- data: fullConfig,
- });
-
- // Invalidate the funnels query to refresh the list
- queryClient.invalidateQueries({ queryKey: ["funnels", site] });
-
- return saveResponse;
- } catch (error) {
- throw new Error("Failed to save funnel");
- }
- },
- });
-}
diff --git a/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts b/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts
deleted file mode 100644
index 9782934e2..000000000
--- a/client/src/api/analytics/funnels/useGetFunnelStepSessions.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { Time } from "../../../components/DateSelector/types";
-import { FUNNEL_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { getFilteredFilters } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-import { GetSessionsResponse } from "../useGetUserSessions";
-import { FunnelStep } from "./useGetFunnel";
-
-interface FunnelStepSessionsResponse {
- data: GetSessionsResponse;
-}
-
-export function useGetFunnelStepSessions({
- steps,
- stepNumber,
- siteId,
- time,
- mode,
- page = 1,
- limit = 25,
- enabled = false,
-}: {
- steps: FunnelStep[];
- stepNumber: number;
- siteId: number;
- time: Time;
- mode: "reached" | "dropped";
- page?: number;
- limit?: number;
- enabled?: boolean;
-}) {
- const timeParams = getQueryParams(time);
- const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
-
- return useQuery({
- queryKey: ["funnel-step-sessions", steps, stepNumber, siteId, timeParams, mode, page, limit, filteredFilters],
- queryFn: async () => {
- return authedFetch<FunnelStepSessionsResponse>(
- `/funnels/${stepNumber}/sessions/${siteId}`,
- {
- ...timeParams,
- mode,
- page,
- limit,
- filters: filteredFilters,
- },
- {
- method: "POST",
- data: { steps },
- }
- );
- },
- enabled: !!siteId && !!steps && steps.length >= 2 && enabled,
- });
-}
diff --git a/client/src/api/analytics/funnels/useGetFunnels.ts b/client/src/api/analytics/funnels/useGetFunnels.ts
deleted file mode 100644
index c67f08aec..000000000
--- a/client/src/api/analytics/funnels/useGetFunnels.ts
+++ /dev/null
@@ -1,32 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../../utils";
-import { FunnelStep } from "./useGetFunnel";
-
-export interface SavedFunnel {
- id: number;
- name: string;
- steps: FunnelStep[];
- createdAt: string;
- updatedAt: string;
- conversionRate: number | null;
- totalVisitors: number | null;
-}
-
-export function useGetFunnels(siteId?: string | number) {
- return useQuery<SavedFunnel[]>({
- queryKey: ["funnels", siteId],
- queryFn: async () => {
- if (!siteId) {
- return [];
- }
- try {
- const response = await authedFetch<{ data: SavedFunnel[] }>(`/funnels/${siteId}`);
- return response.data;
- } catch (error) {
- throw new Error("Failed to fetch funnels");
- }
- },
- enabled: !!siteId,
- });
-}
diff --git a/client/src/api/analytics/goals/useGetGoalSessions.ts b/client/src/api/analytics/goals/useGetGoalSessions.ts
deleted file mode 100644
index 2093d9029..000000000
--- a/client/src/api/analytics/goals/useGetGoalSessions.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch, getQueryParams } from "../../utils";
-import { GetSessionsResponse } from "../useGetUserSessions";
-import { Time } from "../../../components/DateSelector/types";
-
-interface GoalSessionsResponse {
- data: GetSessionsResponse;
-}
-
-export function useGetGoalSessions({
- goalId,
- siteId,
- time,
- page = 1,
- limit = 25,
- enabled = false,
-}: {
- goalId: number;
- siteId: number;
- time: Time;
- page?: number;
- limit?: number;
- enabled?: boolean;
-}) {
- const timeParams = getQueryParams(time);
-
- return useQuery({
- queryKey: ["goal-sessions", goalId, siteId, timeParams, page, limit],
- queryFn: async () => {
- return authedFetch<GoalSessionsResponse>(`/goals/${goalId}/sessions/${siteId}`, {
- ...timeParams,
- page,
- limit,
- });
- },
- enabled: !!siteId && !!goalId && enabled,
- });
-}
diff --git a/client/src/api/analytics/goals/useGetGoals.ts b/client/src/api/analytics/goals/useGetGoals.ts
deleted file mode 100644
index c6911e051..000000000
--- a/client/src/api/analytics/goals/useGetGoals.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { getFilteredFilters, useStore } from "../../../lib/store";
-import { GOALS_PAGE_FILTERS } from "../../../lib/filterGroups";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export interface Goal {
- goalId: number;
- name: string | null;
- goalType: "path" | "event";
- config: {
- pathPattern?: string;
- eventName?: string;
- eventPropertyKey?: string;
- eventPropertyValue?: string | number | boolean;
- };
- createdAt: string;
- total_conversions: number;
- total_sessions: number;
- conversion_rate: number;
-}
-
-export interface PaginationMeta {
- total: number;
- page: number;
- pageSize: number;
- totalPages: number;
-}
-
-interface GoalsResponse {
- data: Goal[];
- meta: PaginationMeta;
-}
-
-export function useGetGoals({
- page = 1,
- pageSize = 10,
- sort = "createdAt",
- order = "desc",
- enabled = true,
-}: {
- page?: number;
- pageSize?: number;
- sort?: "goalId" | "name" | "goalType" | "createdAt";
- order?: "asc" | "desc";
- enabled?: boolean;
-}) {
- const { site, time } = useStore();
- const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
-
- const timeParams = getQueryParams(time);
-
- return useQuery({
- queryKey: ["goals", site, timeParams, filteredFilters, page, pageSize, sort, order],
- queryFn: async () => {
- return authedFetch<GoalsResponse>(`/goals/${site}`, {
- ...timeParams,
- filters: filteredFilters,
- page,
- page_size: pageSize,
- sort,
- order,
- });
- },
- enabled: !!site && enabled,
- });
-}
diff --git a/client/src/api/analytics/errors/useGetErrorBucketed.ts b/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
similarity index 50%
rename from client/src/api/analytics/errors/useGetErrorBucketed.ts
rename to client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
index 1cc58d23c..378e35316 100644
--- a/client/src/api/analytics/errors/useGetErrorBucketed.ts
+++ b/client/src/api/analytics/hooks/errors/useGetErrorBucketed.ts
@@ -1,39 +1,29 @@
import { useStore } from "@/lib/store";
import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { authedFetch, getQueryParams } from "../../utils";
-
-// This should match GetErrorBucketedResponse from the backend
-export type GetErrorBucketedResponse = {
- time: string;
- error_count: number;
-}[];
+import { buildApiParams } from "../../../utils";
+import { fetchErrorBucketed, GetErrorBucketedResponse } from "../../endpoints";
type UseGetErrorBucketedOptions = {
errorMessage: string;
- enabled?: boolean;
};
export function useGetErrorBucketed({
errorMessage,
- enabled = true,
}: UseGetErrorBucketedOptions): UseQueryResult<GetErrorBucketedResponse> {
const { time, site, filters, bucket } = useStore();
- const queryParams = {
- ...getQueryParams(time),
- bucket,
- errorMessage,
- filters,
- };
+ const params = buildApiParams(time, { filters });
return useQuery({
queryKey: ["error-bucketed", time, site, filters, bucket, errorMessage],
queryFn: () => {
- return authedFetch<any>(`/error-bucketed/${site}`, queryParams).then(res => {
- return res.data;
+ return fetchErrorBucketed(site, {
+ ...params,
+ errorMessage,
+ bucket,
});
},
- enabled: enabled && !!errorMessage && !!site,
+ enabled: !!errorMessage && !!site,
staleTime: Infinity,
});
}
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
new file mode 100644
index 000000000..02c9cc97d
--- /dev/null
+++ b/client/src/api/analytics/hooks/errors/useGetErrorEvents.ts
@@ -0,0 +1,43 @@
+import { useStore } from "@/lib/store";
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { getStartAndEndDate, timeZone } from "../../../utils";
+import {
+ fetchErrorEvents,
+ ErrorEvent,
+ ErrorEventsPaginatedResponse,
+ ErrorEventsStandardResponse,
+} from "../../endpoints";
+
+// Hook for infinite scrolling
+export function useGetErrorEventsInfinite(errorMessage: string, enabled: boolean = true) {
+ const { time, site, filters } = useStore();
+
+ const { startDate, endDate } = getStartAndEndDate(time);
+
+ return useInfiniteQuery({
+ queryKey: ["error-events-infinite", time, site, filters, errorMessage],
+ queryFn: async ({ pageParam = 1 }) => {
+ const data = await fetchErrorEvents(site, {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters,
+ errorMessage,
+ limit: 20,
+ page: pageParam,
+ });
+ return { data };
+ },
+ initialPageParam: 1,
+ getNextPageParam: (lastPage: { data: ErrorEventsPaginatedResponse }, allPages) => {
+ const currentPage = allPages.length;
+ const totalItems = lastPage?.data?.totalCount || 0;
+ const itemsPerPage = 20;
+ const totalPages = Math.ceil(totalItems / itemsPerPage);
+
+ return currentPage < totalPages ? currentPage + 1 : undefined;
+ },
+ enabled: enabled && !!errorMessage && !!site,
+ staleTime: Infinity,
+ });
+}
diff --git a/client/src/api/analytics/hooks/errors/useGetErrorNames.ts b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
new file mode 100644
index 000000000..d4568e185
--- /dev/null
+++ b/client/src/api/analytics/hooks/errors/useGetErrorNames.ts
@@ -0,0 +1,67 @@
+import { useStore } from "@/lib/store";
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
+import { getStartAndEndDate, timeZone } from "../../../utils";
+import {
+ fetchErrorNames,
+ ErrorNameItem,
+ ErrorNamesPaginatedResponse,
+ ErrorNamesStandardResponse,
+} from "../../endpoints";
+
+type UseGetErrorNamesOptions = {
+ limit?: number;
+ page?: number;
+ useFilters?: boolean;
+};
+
+// Hook for paginated fetching (e.g., for a dedicated "All Errors" screen)
+export function useGetErrorNamesPaginated({
+ limit = 10,
+ page = 1,
+ useFilters = true,
+}: UseGetErrorNamesOptions): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
+ const { time, site, filters } = useStore();
+
+ const { startDate, endDate } = getStartAndEndDate(time);
+
+ return useQuery({
+ queryKey: ["error-names", time, site, filters, limit, page, useFilters],
+ queryFn: async () => {
+ const data = await fetchErrorNames(site, {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters: useFilters ? filters : undefined,
+ limit,
+ page,
+ });
+ return { data };
+ },
+ staleTime: Infinity,
+ });
+}
+
+// Hook for standard (non-paginated) fetching
+export function useGetErrorNames({
+ limit = 10,
+ useFilters = true,
+}: Omit<UseGetErrorNamesOptions, "page">): UseQueryResult<{ data: ErrorNamesPaginatedResponse }> {
+ const { time, site, filters } = useStore();
+
+ const { startDate, endDate } = getStartAndEndDate(time);
+
+ return useQuery({
+ queryKey: ["error-names", time, site, filters, limit],
+ queryFn: async () => {
+ const data = await fetchErrorNames(site, {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters: useFilters ? filters : undefined,
+ limit,
+ });
+ return { data };
+ },
+ staleTime: Infinity,
+ });
+}
diff --git a/client/src/api/analytics/hooks/events/useGetEventNames.ts b/client/src/api/analytics/hooks/events/useGetEventNames.ts
new file mode 100644
index 000000000..6131d7ed9
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetEventNames.ts
@@ -0,0 +1,20 @@
+import { useQuery } from "@tanstack/react-query";
+import { EVENT_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchEventNames, EventName } from "../../endpoints";
+
+export function useGetEventNames() {
+ const { site, time } = useStore();
+
+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);
+ const params = buildApiParams(time, {
+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,
+ });
+
+ return useQuery({
+ queryKey: ["event-names", site, time, filteredFilters],
+ enabled: !!site,
+ queryFn: () => fetchEventNames(site, params),
+ });
+}
diff --git a/client/src/api/analytics/hooks/events/useGetEventProperties.ts b/client/src/api/analytics/hooks/events/useGetEventProperties.ts
new file mode 100644
index 000000000..1ee77712c
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetEventProperties.ts
@@ -0,0 +1,26 @@
+import { useQuery } from "@tanstack/react-query";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { EVENT_FILTERS } from "../../../../lib/filterGroups";
+import { getStartAndEndDate, timeZone } from "../../../utils";
+import { fetchEventProperties, EventProperty } from "../../endpoints";
+
+export function useGetEventProperties(eventName: string | null) {
+ const { site, time } = useStore();
+
+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);
+ const { startDate, endDate } = getStartAndEndDate(time);
+
+ return useQuery({
+ queryKey: ["event-properties", site, eventName, time, filteredFilters],
+ enabled: !!site && !!eventName,
+ queryFn: () => {
+ return fetchEventProperties(site, {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,
+ eventName: eventName!,
+ });
+ },
+ });
+}
diff --git a/client/src/api/analytics/events/useGetEvents.ts b/client/src/api/analytics/hooks/events/useGetEvents.ts
similarity index 50%
rename from client/src/api/analytics/events/useGetEvents.ts
rename to client/src/api/analytics/hooks/events/useGetEvents.ts
index b7a4782bc..856b925d2 100644
--- a/client/src/api/analytics/events/useGetEvents.ts
+++ b/client/src/api/analytics/hooks/events/useGetEvents.ts
@@ -1,34 +1,8 @@
import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { Time } from "../../../components/DateSelector/types";
-import { useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type Event = {
- timestamp: string;
- event_name: string;
- properties: string;
- user_id: string;
- hostname: string;
- pathname: string;
- querystring: string;
- page_title: string;
- referrer: string;
- browser: string;
- operating_system: string;
- country: string;
- device_type: string;
- type: string;
-};
-
-export interface EventsResponse {
- data: Event[];
- pagination: {
- total: number;
- page: number;
- pageSize: number;
- totalPages: number;
- };
-}
+import { Time } from "../../../../components/DateSelector/types";
+import { useStore } from "../../../../lib/store";
+import { buildApiParams, timeZone } from "../../../utils";
+import { EventsResponse, fetchEvents } from "../../endpoints";
export interface GetEventsOptions {
time?: Time;
@@ -40,34 +14,40 @@ export interface GetEventsOptions {
export function useGetEvents(count = 10) {
const { site } = useStore();
+
return useQuery({
queryKey: ["events", site, count],
refetchInterval: 5000,
queryFn: () =>
- authedFetch<{ data: Event[] }>(`/events/${site}`, {
- count,
+ fetchEvents(site, {
+ startDate: "",
+ endDate: "",
+ timeZone,
+ limit: count,
}).then(res => res.data),
+ enabled: !!site,
});
}
-// New hook with pagination and filtering support
+// Hook with pagination and filtering support
export function useGetEventsInfinite(options: GetEventsOptions = {}) {
const { site, time, filters } = useStore();
const pageSize = options.pageSize || 20;
+ const params = buildApiParams(time, {
+ filters: filters && filters.length > 0 ? filters : undefined,
+ });
+
return useInfiniteQuery<EventsResponse, Error>({
queryKey: ["events-infinite", site, time, filters, pageSize, options.isRealtime],
initialPageParam: 1,
queryFn: async ({ pageParam }) => {
- const params = getQueryParams(time, {
- page: pageParam,
- page_size: pageSize,
- filters: filters && filters.length > 0 ? JSON.stringify(filters) : undefined,
- count: options.count,
+ return fetchEvents(site, {
+ ...params,
+ page: pageParam as number,
+ pageSize,
+ limit: options.count,
});
-
- const response = await authedFetch<EventsResponse>(`/events/${site}`, params);
- return response;
},
getNextPageParam: (lastPage: EventsResponse) => {
if (lastPage.pagination.page < lastPage.pagination.totalPages) {
@@ -76,5 +56,6 @@ export function useGetEventsInfinite(options: GetEventsOptions = {}) {
return undefined;
},
refetchInterval: options.isRealtime ? 5000 : undefined,
+ enabled: !!site,
});
}
diff --git a/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts b/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts
new file mode 100644
index 000000000..cea39edae
--- /dev/null
+++ b/client/src/api/analytics/hooks/events/useGetOutboundLinks.ts
@@ -0,0 +1,20 @@
+import { useQuery } from "@tanstack/react-query";
+import { EVENT_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchOutboundLinks } from "../../endpoints";
+
+export function useGetOutboundLinks() {
+ const { site, time } = useStore();
+
+ const filteredFilters = getFilteredFilters(EVENT_FILTERS);
+ const params = buildApiParams(time, {
+ filters: filteredFilters.length > 0 ? filteredFilters : undefined,
+ });
+
+ return useQuery({
+ queryKey: ["outbound-links", site, time, filteredFilters],
+ enabled: !!site,
+ queryFn: () => fetchOutboundLinks(site, params),
+ });
+}
diff --git a/client/src/api/analytics/funnels/useDeleteFunnel.ts b/client/src/api/analytics/hooks/funnels/useDeleteFunnel.ts
similarity index 58%
rename from client/src/api/analytics/funnels/useDeleteFunnel.ts
rename to client/src/api/analytics/hooks/funnels/useDeleteFunnel.ts
index 8d968f93b..5687e114d 100644
--- a/client/src/api/analytics/funnels/useDeleteFunnel.ts
+++ b/client/src/api/analytics/hooks/funnels/useDeleteFunnel.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { authedFetch } from "../../utils";
+import { useStore } from "../../../../lib/store";
+import { deleteFunnel } from "../../endpoints";
/**
* Hook for deleting a saved funnel report
@@ -11,14 +11,7 @@ export function useDeleteFunnel() {
return useMutation<{ success: boolean }, Error, number>({
mutationFn: async reportId => {
- try {
- return await authedFetch<{ success: boolean }>(`/funnels/${reportId}/${site}`, undefined, {
- method: "DELETE",
- });
- } catch (error) {
- console.error(error);
- throw new Error("Failed to delete funnel");
- }
+ return deleteFunnel(site, reportId);
},
onSuccess: () => {
// Invalidate the funnels query to refresh the list
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnel.ts b/client/src/api/analytics/hooks/funnels/useGetFunnel.ts
new file mode 100644
index 000000000..2f9c7991d
--- /dev/null
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnel.ts
@@ -0,0 +1,62 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useDebounce } from "@uidotdev/usehooks";
+import { FUNNEL_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { analyzeFunnel, FunnelRequest, FunnelResponse, saveFunnel, SaveFunnelRequest } from "../../endpoints";
+
+/**
+ * Hook for analyzing conversion funnels through a series of steps
+ */
+export function useGetFunnel(config?: FunnelRequest, debounce?: boolean) {
+ const { site, time } = useStore();
+
+ const debouncedConfig = useDebounce(config, 500);
+ const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ const configToUse = debounce ? debouncedConfig : config;
+
+ return useQuery<FunnelResponse[], Error>({
+ queryKey: ["funnel", site, time, filteredFilters, configToUse?.steps],
+ queryFn: async () => {
+ if (!configToUse) {
+ throw new Error("Funnel configuration is required");
+ }
+
+ return analyzeFunnel(site, {
+ ...params,
+ steps: configToUse.steps,
+ name: configToUse.name,
+ });
+ },
+ enabled: !!site && !!configToUse,
+ });
+}
+
+/**
+ * Hook for saving funnel configurations without analyzing them
+ */
+export function useSaveFunnel() {
+ const { site } = useStore();
+ const queryClient = useQueryClient();
+
+ return useMutation<{ success: boolean; funnelId: number }, Error, SaveFunnelRequest>({
+ mutationFn: async funnelConfig => {
+ try {
+ const saveResponse = await saveFunnel(site, {
+ steps: funnelConfig.steps,
+ name: funnelConfig.name,
+ reportId: funnelConfig.reportId,
+ });
+
+ // Invalidate the funnels query to refresh the list
+ queryClient.invalidateQueries({ queryKey: ["funnels", site] });
+
+ return saveResponse;
+ } catch (error) {
+ throw new Error("Failed to save funnel");
+ }
+ },
+ });
+}
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
new file mode 100644
index 000000000..1ca9b2dfe
--- /dev/null
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnelStepSessions.ts
@@ -0,0 +1,44 @@
+import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../../../components/DateSelector/types";
+import { FUNNEL_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchFunnelStepSessions, FunnelStep } from "../../endpoints";
+
+export function useGetFunnelStepSessions({
+ steps,
+ stepNumber,
+ siteId,
+ time,
+ mode,
+ page = 1,
+ limit = 25,
+ enabled = false,
+}: {
+ steps: FunnelStep[];
+ stepNumber: number;
+ siteId: number;
+ time: Time;
+ mode: "reached" | "dropped";
+ page?: number;
+ limit?: number;
+ enabled?: boolean;
+}) {
+ const filteredFilters = getFilteredFilters(FUNNEL_PAGE_FILTERS);
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery({
+ queryKey: ["funnel-step-sessions", steps, stepNumber, siteId, time, mode, page, limit, filteredFilters],
+ queryFn: async () => {
+ return fetchFunnelStepSessions(siteId, {
+ ...params,
+ steps,
+ stepNumber,
+ mode,
+ page,
+ limit,
+ });
+ },
+ enabled: !!siteId && !!steps && steps.length >= 2 && enabled,
+ });
+}
diff --git a/client/src/api/analytics/hooks/funnels/useGetFunnels.ts b/client/src/api/analytics/hooks/funnels/useGetFunnels.ts
new file mode 100644
index 000000000..714f2d547
--- /dev/null
+++ b/client/src/api/analytics/hooks/funnels/useGetFunnels.ts
@@ -0,0 +1,15 @@
+import { useQuery } from "@tanstack/react-query";
+import { fetchFunnels, SavedFunnel } from "../../endpoints";
+
+export function useGetFunnels(siteId?: string | number) {
+ return useQuery<SavedFunnel[]>({
+ queryKey: ["funnels", siteId],
+ queryFn: async () => {
+ if (!siteId) {
+ return [];
+ }
+ return fetchFunnels(siteId);
+ },
+ enabled: !!siteId,
+ });
+}
diff --git a/client/src/api/analytics/goals/useCreateGoal.ts b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
similarity index 70%
rename from client/src/api/analytics/goals/useCreateGoal.ts
rename to client/src/api/analytics/hooks/goals/useCreateGoal.ts
index 6f41e4c11..c4ec8cce0 100644
--- a/client/src/api/analytics/goals/useCreateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useCreateGoal.ts
@@ -1,5 +1,5 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../../utils";
+import { createGoal } from "../../endpoints";
export interface CreateGoalRequest {
siteId: number;
@@ -23,14 +23,11 @@ export function useCreateGoal() {
return useMutation<CreateGoalResponse, Error, CreateGoalRequest>({
mutationFn: async goalData => {
- try {
- return await authedFetch<CreateGoalResponse>(`/goals/${goalData.siteId}`, undefined, {
- method: "POST",
- data: goalData,
- });
- } catch (error) {
- throw new Error(error instanceof Error ? error.message : "Failed to create goal");
- }
+ return createGoal(goalData.siteId, {
+ name: goalData.name,
+ goalType: goalData.goalType,
+ config: goalData.config,
+ });
},
onSuccess: (_, variables) => {
// Invalidate goals query to refetch with the new goal
diff --git a/client/src/api/analytics/goals/useDeleteGoal.ts b/client/src/api/analytics/hooks/goals/useDeleteGoal.ts
similarity index 56%
rename from client/src/api/analytics/goals/useDeleteGoal.ts
rename to client/src/api/analytics/hooks/goals/useDeleteGoal.ts
index 0bff93dfa..164e62966 100644
--- a/client/src/api/analytics/goals/useDeleteGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useDeleteGoal.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../../utils";
-import { useStore } from "../../../lib/store";
+import { useStore } from "../../../../lib/store";
+import { deleteGoal } from "../../endpoints";
export function useDeleteGoal() {
const queryClient = useQueryClient();
@@ -8,13 +8,7 @@ export function useDeleteGoal() {
return useMutation<{ success: boolean }, Error, number>({
mutationFn: async (goalId: number) => {
- try {
- return await authedFetch<{ success: boolean }>(`/goals/${goalId}/${site}`, undefined, {
- method: "DELETE",
- });
- } catch (error) {
- throw new Error(error instanceof Error ? error.message : "Failed to delete goal");
- }
+ return deleteGoal(site, goalId);
},
onSuccess: () => {
// Invalidate goals query to refetch without the deleted goal
diff --git a/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts b/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts
new file mode 100644
index 000000000..9b2a897b9
--- /dev/null
+++ b/client/src/api/analytics/hooks/goals/useGetGoalSessions.ts
@@ -0,0 +1,35 @@
+import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../../../components/DateSelector/types";
+import { buildApiParams } from "../../../utils";
+import { fetchGoalSessions } from "../../endpoints";
+
+export function useGetGoalSessions({
+ goalId,
+ siteId,
+ time,
+ page = 1,
+ limit = 25,
+ enabled = false,
+}: {
+ goalId: number;
+ siteId: number;
+ time: Time;
+ page?: number;
+ limit?: number;
+ enabled?: boolean;
+}) {
+ const params = buildApiParams(time);
+
+ return useQuery({
+ queryKey: ["goal-sessions", goalId, siteId, time, page, limit],
+ queryFn: async () => {
+ return fetchGoalSessions(siteId, {
+ ...params,
+ goalId,
+ page,
+ limit,
+ });
+ },
+ enabled: !!siteId && !!goalId && enabled,
+ });
+}
diff --git a/client/src/api/analytics/hooks/goals/useGetGoals.ts b/client/src/api/analytics/hooks/goals/useGetGoals.ts
new file mode 100644
index 000000000..7b9d4ef6f
--- /dev/null
+++ b/client/src/api/analytics/hooks/goals/useGetGoals.ts
@@ -0,0 +1,36 @@
+import { useQuery } from "@tanstack/react-query";
+import { GOALS_PAGE_FILTERS } from "../../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchGoals } from "../../endpoints";
+
+export function useGetGoals({
+ page = 1,
+ pageSize = 10,
+ sort = "createdAt",
+ order = "desc",
+}: {
+ page?: number;
+ pageSize?: number;
+ sort?: "goalId" | "name" | "goalType" | "createdAt";
+ order?: "asc" | "desc";
+}) {
+ const { site, time } = useStore();
+ const filteredFilters = getFilteredFilters(GOALS_PAGE_FILTERS);
+
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery({
+ queryKey: ["goals", site, time, filteredFilters, page, pageSize, sort, order],
+ queryFn: async () => {
+ return fetchGoals(site, {
+ ...params,
+ page,
+ pageSize,
+ sort,
+ order,
+ });
+ },
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/goals/useUpdateGoal.ts b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
similarity index 67%
rename from client/src/api/analytics/goals/useUpdateGoal.ts
rename to client/src/api/analytics/hooks/goals/useUpdateGoal.ts
index 2ef42dc27..639abfba9 100644
--- a/client/src/api/analytics/goals/useUpdateGoal.ts
+++ b/client/src/api/analytics/hooks/goals/useUpdateGoal.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../../utils";
-import { useStore } from "../../../lib/store";
+import { useStore } from "../../../../lib/store";
+import { updateGoal } from "../../endpoints";
export interface UpdateGoalRequest {
goalId: number;
@@ -26,14 +26,12 @@ export function useUpdateGoal() {
return useMutation<UpdateGoalResponse, Error, UpdateGoalRequest>({
mutationFn: async goalData => {
- try {
- return await authedFetch<UpdateGoalResponse>(`/goals/${goalData.goalId}/${goalData.siteId}`, undefined, {
- method: "PUT",
- data: goalData,
- });
- } catch (error) {
- throw new Error(error instanceof Error ? error.message : "Failed to update goal");
- }
+ return updateGoal(goalData.siteId, {
+ goalId: goalData.goalId,
+ name: goalData.name,
+ goalType: goalData.goalType,
+ config: goalData.config,
+ });
},
onSuccess: () => {
// Invalidate goals query to refetch with the updated goal
diff --git a/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
new file mode 100644
index 000000000..14cd99034
--- /dev/null
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceByDimension.ts
@@ -0,0 +1,78 @@
+import { Filter } from "@rybbit/shared";
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
+import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
+import { useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchPerformanceByDimension, PaginatedPerformanceResponse, PerformanceByDimensionItem } from "../../endpoints";
+
+// Keep the old type for backward compatibility
+export type PerformanceByPathItem = PerformanceByDimensionItem & {
+ pathname: string;
+};
+
+type UseGetPerformanceByDimensionOptions = {
+ site: number | string;
+ dimension: string;
+ limit?: number;
+ page?: number;
+ useFilters?: boolean;
+ additionalFilters?: Filter[];
+ sortBy?: string;
+ sortOrder?: "asc" | "desc";
+};
+
+export function useGetPerformanceByDimension({
+ site,
+ dimension,
+ limit = 10,
+ page = 1,
+ useFilters = true,
+ additionalFilters = [],
+ sortBy,
+ sortOrder,
+}: UseGetPerformanceByDimensionOptions): UseQueryResult<PaginatedPerformanceResponse> {
+ const { time, filters } = useStore();
+ const { selectedPercentile } = usePerformanceStore();
+
+ const combinedFilters = useFilters ? [...filters, ...additionalFilters] : undefined;
+ const params = buildApiParams(time, { filters: combinedFilters });
+
+ return useQuery({
+ queryKey: [
+ "performance-by-dimension",
+ dimension,
+ time,
+ site,
+ filters,
+ selectedPercentile,
+ limit,
+ page,
+ additionalFilters,
+ sortBy,
+ sortOrder,
+ ],
+ queryFn: () => {
+ return fetchPerformanceByDimension(site, {
+ ...params,
+ dimension,
+ limit,
+ page,
+ percentile: selectedPercentile,
+ sortBy,
+ sortOrder,
+ });
+ },
+ staleTime: Infinity,
+ placeholderData: (_, query: any) => {
+ if (!query?.queryKey) return undefined;
+ const prevQueryKey = query.queryKey;
+ const [, , , prevSite] = prevQueryKey;
+
+ if (prevSite === site) {
+ return query.state.data;
+ }
+ return undefined;
+ },
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/performance/useGetPerformanceOverview.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
similarity index 56%
rename from client/src/api/analytics/performance/useGetPerformanceOverview.ts
rename to client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
index df1550be6..e1c5511c3 100644
--- a/client/src/api/analytics/performance/useGetPerformanceOverview.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceOverview.ts
@@ -1,24 +1,8 @@
import { useQuery } from "@tanstack/react-query";
-import { usePerformanceStore } from "../../../app/[site]/performance/performanceStore";
-import { useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export type GetPerformanceOverviewResponse = {
- current: {
- lcp: number;
- cls: number;
- inp: number;
- fcp: number;
- ttfb: number;
- };
- previous: {
- lcp: number;
- cls: number;
- inp: number;
- fcp: number;
- ttfb: number;
- };
-};
+import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
+import { useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchPerformanceOverview } from "../../endpoints";
type PeriodTime = "current" | "previous";
@@ -27,15 +11,15 @@ export function useGetPerformanceOverview({ periodTime, site }: { periodTime?: P
const { selectedPercentile } = usePerformanceStore();
const timeToUse = periodTime === "previous" ? previousTime : time;
- const queryParams = getQueryParams(timeToUse, {
- filters,
- percentile: selectedPercentile,
- });
+ const params = buildApiParams(timeToUse, { filters });
return useQuery({
queryKey: ["performance-overview", timeToUse, site, filters, selectedPercentile],
queryFn: () => {
- return authedFetch<{ data: GetPerformanceOverviewResponse }>(`/performance/overview/${site}`, queryParams);
+ return fetchPerformanceOverview(site!, {
+ ...params,
+ percentile: selectedPercentile,
+ }).then(data => ({ data }));
},
staleTime: Infinity,
placeholderData: (_, query: any) => {
diff --git a/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts b/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
similarity index 53%
rename from client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts
rename to client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
index 59d3753fa..53fd3e000 100644
--- a/client/src/api/analytics/performance/useGetPerformanceTimeSeries.ts
+++ b/client/src/api/analytics/hooks/performance/useGetPerformanceTimeSeries.ts
@@ -1,37 +1,13 @@
import { Filter, TimeBucket } from "@rybbit/shared";
-import { UseQueryOptions, UseQueryResult, useQuery } from "@tanstack/react-query";
-import { usePerformanceStore } from "../../../app/[site]/performance/performanceStore";
-import { useStore } from "../../../lib/store";
-import { APIResponse } from "../../types";
-import { authedFetch, getQueryParams } from "../../utils";
+import { useQuery, UseQueryOptions, UseQueryResult } from "@tanstack/react-query";
+import { usePerformanceStore } from "../../../../app/[site]/performance/performanceStore";
+import { useStore } from "../../../../lib/store";
+import { APIResponse } from "../../../types";
+import { buildApiParams } from "../../../utils";
+import { fetchPerformanceTimeSeries, GetPerformanceTimeSeriesResponse } from "../../endpoints";
type PeriodTime = "current" | "previous";
-export type GetPerformanceTimeSeriesResponse = {
- time: string;
- event_count: number;
- lcp_p50: number | null;
- lcp_p75: number | null;
- lcp_p90: number | null;
- lcp_p99: number | null;
- cls_p50: number | null;
- cls_p75: number | null;
- cls_p90: number | null;
- cls_p99: number | null;
- inp_p50: number | null;
- inp_p75: number | null;
- inp_p90: number | null;
- inp_p99: number | null;
- fcp_p50: number | null;
- fcp_p75: number | null;
- fcp_p90: number | null;
- fcp_p99: number | null;
- ttfb_p50: number | null;
- ttfb_p75: number | null;
- ttfb_p90: number | null;
- ttfb_p99: number | null;
-}[];
-
export function useGetPerformanceTimeSeries({
periodTime,
site,
@@ -52,18 +28,12 @@ export function useGetPerformanceTimeSeries({
const bucketToUse = bucket || storeBucket;
const combinedFilters = [...globalFilters, ...dynamicFilters];
- const queryParams = getQueryParams(timeToUse, {
- bucket: bucketToUse,
- filters: combinedFilters,
- });
+ const params = buildApiParams(timeToUse, { filters: combinedFilters });
return useQuery({
queryKey: ["performance-time-series", timeToUse, bucketToUse, site, combinedFilters, selectedPerformanceMetric],
queryFn: () => {
- return authedFetch<APIResponse<GetPerformanceTimeSeriesResponse>>(
- `/performance/time-series/${site}`,
- queryParams
- );
+ return fetchPerformanceTimeSeries(site, { ...params, bucket: bucketToUse }).then(data => ({ data }));
},
placeholderData: (_, query: any) => {
if (!query?.queryKey) return undefined;
diff --git a/client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts b/client/src/api/analytics/hooks/sessionReplay/useDeleteSessionReplay.ts
similarity index 64%
rename from client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts
rename to client/src/api/analytics/hooks/sessionReplay/useDeleteSessionReplay.ts
index c48b64a23..37ddedaed 100644
--- a/client/src/api/analytics/sessionReplay/useDeleteSessionReplay.ts
+++ b/client/src/api/analytics/hooks/sessionReplay/useDeleteSessionReplay.ts
@@ -1,6 +1,6 @@
import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { authedFetch } from "../../utils";
+import { useStore } from "../../../../lib/store";
+import { deleteSessionReplay } from "../../endpoints";
interface DeleteSessionReplayParams {
sessionId: string;
@@ -12,14 +12,7 @@ export function useDeleteSessionReplay() {
return useMutation({
mutationFn: async ({ sessionId }: DeleteSessionReplayParams) => {
- const response = await authedFetch<{ success: boolean }>(
- `/session-replay/${sessionId}/${site}`,
- {},
- {
- method: "DELETE",
- }
- );
- return response;
+ return deleteSessionReplay(site, sessionId);
},
onSuccess: () => {
// Invalidate the session replay list query to refetch data
diff --git a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts
new file mode 100644
index 000000000..e11c5bbc8
--- /dev/null
+++ b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplayEvents.ts
@@ -0,0 +1,11 @@
+import { useQuery } from "@tanstack/react-query";
+import { fetchSessionReplayEvents } from "../../endpoints";
+
+export function useGetSessionReplayEvents(siteId: number, sessionId: string) {
+ return useQuery({
+ queryKey: ["session-replay-events", siteId, sessionId],
+ queryFn: () => fetchSessionReplayEvents(siteId, sessionId),
+ enabled: !!siteId && !!sessionId,
+ staleTime: 1000 * 60 * 10, // 10 minutes
+ });
+}
diff --git a/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts
new file mode 100644
index 000000000..8d8e6ee81
--- /dev/null
+++ b/client/src/api/analytics/hooks/sessionReplay/useGetSessionReplays.ts
@@ -0,0 +1,34 @@
+import { useInfiniteQuery } from "@tanstack/react-query";
+import { useStore } from "../../../../lib/store";
+import { buildApiParams } from "../../../utils";
+import { fetchSessionReplays } from "../../endpoints";
+
+type UseGetSessionReplaysOptions = {
+ limit?: number;
+ minDuration?: number;
+};
+
+export function useGetSessionReplays({ limit = 20, minDuration = 30 }: UseGetSessionReplaysOptions = {}) {
+ const { time, site, filters } = useStore();
+ const params = buildApiParams(time, { filters });
+
+ return useInfiniteQuery({
+ queryKey: ["session-replays", site, time, filters, limit, minDuration],
+ queryFn: async ({ pageParam = 0 }) => {
+ return fetchSessionReplays(site, {
+ ...params,
+ limit,
+ offset: pageParam,
+ minDuration,
+ });
+ },
+ initialPageParam: 0,
+ getNextPageParam: (lastPage, allPages) => {
+ const totalFetched = allPages.reduce((acc, page) => acc + (page.data?.length || 0), 0);
+ return lastPage.data?.length === limit ? totalFetched : undefined;
+ },
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ refetchOnWindowFocus: false,
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetJourneys.ts b/client/src/api/analytics/hooks/useGetJourneys.ts
new file mode 100644
index 000000000..2a741be85
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetJourneys.ts
@@ -0,0 +1,33 @@
+import { useQuery } from "@tanstack/react-query";
+import { Time } from "../../../components/DateSelector/types";
+import { JOURNEY_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters } from "../../../lib/store";
+import { buildApiParams } from "../../utils";
+import { fetchJourneys, Journey, JourneysResponse } from "../endpoints";
+
+export interface JourneyParams {
+ siteId?: number;
+ steps?: number;
+ timeZone?: string;
+ time: Time;
+ limit?: number;
+ stepFilters?: Record<number, string>;
+}
+
+export const useJourneys = ({ siteId, steps = 3, time, limit = 100, stepFilters }: JourneyParams) => {
+ const filteredFilters = getFilteredFilters(JOURNEY_PAGE_FILTERS);
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery<JourneysResponse>({
+ queryKey: ["journeys", siteId, steps, time, limit, filteredFilters, stepFilters],
+ queryFn: () =>
+ fetchJourneys(siteId!, {
+ ...params,
+ steps,
+ limit,
+ stepFilters,
+ }),
+ enabled: !!siteId,
+ placeholderData: previousData => previousData,
+ });
+};
diff --git a/client/src/api/analytics/hooks/useGetLiveUserCount.ts b/client/src/api/analytics/hooks/useGetLiveUserCount.ts
new file mode 100644
index 000000000..25a08fc49
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetLiveUserCount.ts
@@ -0,0 +1,13 @@
+import { useQuery } from "@tanstack/react-query";
+import { useStore } from "../../../lib/store";
+import { fetchLiveUserCount, LiveUserCountResponse } from "../endpoints";
+
+export function useGetLiveUserCount(minutes = 5) {
+ const { site } = useStore();
+ return useQuery<LiveUserCountResponse>({
+ queryKey: ["live-user-count", site, minutes],
+ refetchInterval: 5000,
+ queryFn: () => fetchLiveUserCount(site, minutes),
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/useGetMetric.ts b/client/src/api/analytics/hooks/useGetMetric.ts
similarity index 61%
rename from client/src/api/analytics/useGetMetric.ts
rename to client/src/api/analytics/hooks/useGetMetric.ts
index 8460cf88e..ca349ef07 100644
--- a/client/src/api/analytics/useGetMetric.ts
+++ b/client/src/api/analytics/hooks/useGetMetric.ts
@@ -6,24 +6,14 @@ import {
useQuery,
UseQueryResult,
} from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { APIResponse } from "../types";
-import { authedFetch, getQueryParams } from "../utils";
-import { Time } from "../../components/DateSelector/types";
+import { useStore } from "../../../lib/store";
+import { APIResponse } from "../../types";
+import { buildApiParams } from "../../utils";
+import { Time } from "../../../components/DateSelector/types";
+import { fetchMetric, MetricResponse } from "../endpoints";
type PeriodTime = "current" | "previous";
-export type MetricResponse = {
- value: string;
- title?: string;
- count: number;
- percentage: number;
- pageviews?: number;
- pageviews_percentage?: number;
- time_on_page_seconds?: number;
- bounce_rate?: number;
-};
-
export function useMetric({
parameter,
limit = 1000,
@@ -40,30 +30,27 @@ export function useMetric({
// For "previous" periods in past-minutes mode, we need to modify the time object
// to use doubled duration for the start and the original start as the end
- const timeForQuery =
+ const timeForQuery: Time =
timeToUse.mode === "past-minutes" && periodTime === "previous"
? {
...timeToUse,
- past_minutes_start: timeToUse.pastMinutesStart * 2,
- past_minutes_end: timeToUse.pastMinutesStart,
+ pastMinutesStart: timeToUse.pastMinutesStart * 2,
+ pastMinutesEnd: timeToUse.pastMinutesStart,
}
: timeToUse;
- const queryParams = getQueryParams(timeForQuery, {
- parameter,
- limit,
- filters: useFilters ? filters : undefined,
- });
-
+ const params = buildApiParams(timeForQuery, { filters: useFilters ? filters : undefined });
const queryKey = [parameter, timeForQuery, site, filters, limit, useFilters];
return useQuery({
queryKey,
queryFn: async () => {
- const response = await authedFetch<{
- data: APIResponse<MetricResponse[]>;
- }>(`/metric/${site}`, queryParams);
- return response.data;
+ const result = await fetchMetric(site, {
+ ...params,
+ parameter,
+ limit,
+ });
+ return { data: result.data };
},
staleTime: 60_000,
placeholderData: (_, query: any) => {
@@ -76,6 +63,7 @@ export function useMetric({
}
return undefined;
},
+ enabled: !!site,
});
}
@@ -89,7 +77,6 @@ export function usePaginatedMetric({
limit = 10,
page = 1,
useFilters = true,
- enabled = true,
additionalFilters = [],
customFilters = [],
customTime,
@@ -104,20 +91,24 @@ export function usePaginatedMetric({
customTime?: Time;
}): UseQueryResult<PaginatedResponse> {
const { time, site, filters } = useStore();
+ const timeToUse = customTime ?? time;
+ const combinedFilters = useFilters
+ ? customFilters.length > 0
+ ? customFilters
+ : [...filters, ...additionalFilters]
+ : undefined;
- const queryParams = {
- ...getQueryParams(customTime ?? time),
- parameter,
- limit,
- page,
- filters: useFilters ? (customFilters.length > 0 ? customFilters : [...filters, ...additionalFilters]) : undefined,
- };
+ const params = buildApiParams(timeToUse, { filters: combinedFilters });
return useQuery({
queryKey: [parameter, customTime, time, site, filters, limit, page, additionalFilters, customFilters],
queryFn: async () => {
- const response = await authedFetch<{ data: PaginatedResponse }>(`/metric/${site}`, queryParams);
- return response.data;
+ return fetchMetric(site, {
+ ...params,
+ parameter,
+ limit,
+ page,
+ });
},
staleTime: 60_000,
placeholderData: (_, query: any) => {
@@ -130,7 +121,7 @@ export function usePaginatedMetric({
}
return undefined;
},
- enabled,
+ enabled: !!site,
});
}
@@ -144,22 +135,17 @@ export function useInfiniteMetric({
useFilters?: boolean;
}): UseInfiniteQueryResult<InfiniteData<PaginatedResponse>> {
const { time, site, filters } = useStore();
+ const params = buildApiParams(time, { filters: useFilters ? filters : undefined });
return useInfiniteQuery({
queryKey: [parameter, time, site, filters, limit, "infinite-metric"],
queryFn: async ({ pageParam = 1 }) => {
- const queryParams = {
- ...getQueryParams(time),
+ return fetchMetric(site, {
+ ...params,
parameter,
limit,
page: pageParam,
- filters: useFilters ? filters : undefined,
- };
-
- const response = await authedFetch<{
- data: PaginatedResponse;
- }>(`/metric/${site}`, queryParams);
- return response.data;
+ });
},
initialPageParam: 1,
getNextPageParam: (lastPage, allPages) => {
@@ -174,28 +160,6 @@ export function useInfiniteMetric({
return allPages.length + 1;
},
staleTime: 60_000,
+ enabled: !!site,
});
}
-
-/**
- * Standalone fetch function for metric data (used for exports)
- */
-export async function fetchMetric(
- site: number | string,
- parameter: FilterParameter,
- time: Time,
- filters: Filter[] = [],
- limit = 100
-): Promise<MetricResponse[]> {
- const queryParams = {
- ...getQueryParams(time),
- parameter,
- limit,
- filters: filters.length > 0 ? filters : undefined,
- };
- const response = await authedFetch<{ data: { data: MetricResponse[] } }>(
- `/metric/${site}`,
- queryParams
- );
- return response.data.data;
-}
diff --git a/client/src/api/analytics/hooks/useGetOrgEventCount.ts b/client/src/api/analytics/hooks/useGetOrgEventCount.ts
new file mode 100644
index 000000000..874a5dca1
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetOrgEventCount.ts
@@ -0,0 +1,26 @@
+import { useQuery } from "@tanstack/react-query";
+import { fetchOrgEventCount } from "../endpoints";
+
+export function useGetOrgEventCount({
+ organizationId,
+ startDate,
+ endDate,
+ timeZone = "UTC",
+}: {
+ organizationId: string;
+ startDate?: string;
+ endDate?: string;
+ timeZone?: string;
+}) {
+ return useQuery({
+ queryKey: ["org-event-count", organizationId, startDate, endDate, timeZone],
+ queryFn: () =>
+ fetchOrgEventCount(organizationId, {
+ startDate,
+ endDate,
+ timeZone,
+ }),
+ enabled: !!organizationId,
+ staleTime: 1000 * 60 * 5, // 5 minutes
+ });
+}
diff --git a/client/src/api/analytics/useGetOverview.ts b/client/src/api/analytics/hooks/useGetOverview.ts
similarity index 71%
rename from client/src/api/analytics/useGetOverview.ts
rename to client/src/api/analytics/hooks/useGetOverview.ts
index 4cef89301..b0c0e3108 100644
--- a/client/src/api/analytics/useGetOverview.ts
+++ b/client/src/api/analytics/hooks/useGetOverview.ts
@@ -1,15 +1,7 @@
import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { authedFetch, getQueryParams } from "../utils";
-
-export type GetOverviewResponse = {
- sessions: number;
- pageviews: number;
- users: number;
- pages_per_session: number;
- bounce_rate: number;
- session_duration: number;
-};
+import { useStore } from "../../../lib/store";
+import { buildApiParams } from "../../utils";
+import { fetchOverview } from "../endpoints";
type PeriodTime = "current" | "previous";
@@ -28,14 +20,13 @@ export function useGetOverview({ periodTime, site, overrideTime }: UseGetOvervie
const baseTime = overrideTime || time;
const timeToUse = periodTime === "previous" ? previousTime : baseTime;
- const queryParams = getQueryParams(timeToUse, { filters });
-
+ const params = buildApiParams(timeToUse, { filters });
const queryKey = ["overview", timeToUse, site, filters];
return useQuery({
queryKey,
queryFn: () => {
- return authedFetch<{ data: GetOverviewResponse }>(`/overview/${site}`, queryParams);
+ return fetchOverview(site!, params).then(data => ({ data }));
},
staleTime: 60_000,
placeholderData: (_, query: any) => {
@@ -48,5 +39,6 @@ export function useGetOverview({ periodTime, site, overrideTime }: UseGetOvervie
}
return undefined;
},
+ enabled: !!site,
});
}
diff --git a/client/src/api/analytics/useGetOverviewBucketed.ts b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
similarity index 63%
rename from client/src/api/analytics/useGetOverviewBucketed.ts
rename to client/src/api/analytics/hooks/useGetOverviewBucketed.ts
index c692959f1..a06d9425b 100644
--- a/client/src/api/analytics/useGetOverviewBucketed.ts
+++ b/client/src/api/analytics/hooks/useGetOverviewBucketed.ts
@@ -1,22 +1,12 @@
import { Filter, TimeBucket } from "@rybbit/shared";
-import { Time } from "../../components/DateSelector/types";
import { UseQueryOptions, UseQueryResult, useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { APIResponse } from "../types";
-import { authedFetch, getQueryParams } from "../utils";
+import { useStore } from "../../../lib/store";
+import { APIResponse } from "../../types";
+import { buildApiParams } from "../../utils";
+import { fetchOverviewBucketed, GetOverviewBucketedResponse } from "../endpoints";
type PeriodTime = "current" | "previous";
-export type GetOverviewBucketedResponse = {
- time: string;
- pageviews: number;
- sessions: number;
- pages_per_session: number;
- bounce_rate: number;
- session_duration: number;
- users: number;
-}[];
-
export function useGetOverviewBucketed({
periodTime,
site,
@@ -43,12 +33,6 @@ export function useGetOverviewBucketed({
const timeToUse = periodTime === "previous" ? previousTime : baseTime;
const combinedFilters = [...globalFilters, ...dynamicFilters];
- // Use getQueryParams utility to handle conditional logic
- const queryParams = getQueryParams(timeToUse, {
- bucket,
- filters: combinedFilters,
- });
-
// Generate appropriate query key based on whether we're using past minutes or regular time
const queryKey =
timeToUse.mode === "past-minutes"
@@ -62,10 +46,12 @@ export function useGetOverviewBucketed({
]
: ["overview-bucketed", timeToUse, bucket, site, combinedFilters];
+ const params = buildApiParams(timeToUse, { filters: combinedFilters });
+
return useQuery({
queryKey,
queryFn: () => {
- return authedFetch<APIResponse<GetOverviewBucketedResponse>>(`/overview-bucketed/${site}`, queryParams);
+ return fetchOverviewBucketed(site, { ...params, bucket }).then(data => ({ data }));
},
refetchInterval,
placeholderData: (_, query: any) => {
@@ -80,23 +66,7 @@ export function useGetOverviewBucketed({
return undefined;
},
staleTime: 60_000,
+ enabled: !!site,
...props,
});
}
-
-/**
- * Standalone fetch function for overview bucketed data (used for exports)
- */
-export async function fetchOverviewBucketed(
- site: number | string,
- time: Time,
- bucket: TimeBucket = "day",
- filters: Filter[] = []
-): Promise<GetOverviewBucketedResponse> {
- const queryParams = getQueryParams(time, { bucket, filters });
- const response = await authedFetch<APIResponse<GetOverviewBucketedResponse>>(
- `/overview-bucketed/${site}`,
- queryParams
- );
- return response.data;
-}
diff --git a/client/src/api/analytics/hooks/useGetPageTitles.ts b/client/src/api/analytics/hooks/useGetPageTitles.ts
new file mode 100644
index 000000000..ff2121d84
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetPageTitles.ts
@@ -0,0 +1,35 @@
+import { useStore } from "@/lib/store";
+import { useQuery, UseQueryResult } from "@tanstack/react-query";
+import { buildApiParams } from "../../utils";
+import { fetchPageTitles, PageTitlesPaginatedResponse } from "../endpoints";
+
+type UseGetPageTitlesOptions = {
+ limit?: number;
+ page?: number;
+ useFilters?: boolean;
+};
+
+// Hook for paginated fetching (e.g., for a dedicated "All Page Titles" screen)
+export function useGetPageTitlesPaginated({
+ limit = 10,
+ page = 1,
+ useFilters = true,
+}: UseGetPageTitlesOptions): UseQueryResult<{ data: PageTitlesPaginatedResponse }> {
+ const { time, site, filters } = useStore();
+
+ const params = buildApiParams(time, { filters: useFilters ? filters : undefined });
+
+ return useQuery({
+ queryKey: ["page-titles", time, site, filters, limit, page, useFilters],
+ queryFn: async () => {
+ const data = await fetchPageTitles(site, {
+ ...params,
+ limit,
+ page,
+ });
+ return { data };
+ },
+ staleTime: Infinity,
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetRetention.ts b/client/src/api/analytics/hooks/useGetRetention.ts
new file mode 100644
index 000000000..cab01b0d3
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetRetention.ts
@@ -0,0 +1,12 @@
+import { useQuery } from "@tanstack/react-query";
+import { useStore } from "../../../lib/store";
+import { fetchRetention, ProcessedRetentionData, RetentionMode } from "../endpoints";
+
+export function useGetRetention(mode: RetentionMode = "week", range: number = 90) {
+ const { site } = useStore();
+ return useQuery<ProcessedRetentionData>({
+ queryKey: ["retention", site, mode, range],
+ queryFn: () => fetchRetention(site, { mode, range }),
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetSessionLocations.ts b/client/src/api/analytics/hooks/useGetSessionLocations.ts
new file mode 100644
index 000000000..70d641958
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetSessionLocations.ts
@@ -0,0 +1,28 @@
+import { useQuery } from "@tanstack/react-query";
+import { useStore } from "../../../lib/store";
+import { buildApiParams } from "../../utils";
+import { fetchSessionLocations, LiveSessionLocation } from "../endpoints";
+
+export function useGetSessionLocations() {
+ const { time, site, filters } = useStore();
+
+ // Filter out location-related filters to avoid circular dependencies
+ const locationExcludedFilters = filters.filter(
+ f =>
+ f.parameter !== "lat" &&
+ f.parameter !== "lon" &&
+ f.parameter !== "city" &&
+ f.parameter !== "country" &&
+ f.parameter !== "region"
+ );
+
+ const params = buildApiParams(time, { filters: locationExcludedFilters });
+
+ return useQuery<LiveSessionLocation[]>({
+ queryKey: ["session-locations", site, time, locationExcludedFilters],
+ queryFn: () => {
+ return fetchSessionLocations(site, params);
+ },
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetUserSessions.ts b/client/src/api/analytics/hooks/useGetUserSessions.ts
new file mode 100644
index 000000000..1565261fe
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetUserSessions.ts
@@ -0,0 +1,125 @@
+import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
+import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { getFilteredFilters, useStore } from "../../../lib/store";
+import { buildApiParams, timeZone } from "../../utils";
+import {
+ fetchSession,
+ fetchSessions,
+ fetchUserSessionCount,
+ GetSessionsResponse,
+ SessionPageviewsAndEvents,
+ UserSessionCountResponse,
+} from "../endpoints";
+
+export function useGetSessions(
+ userId?: string,
+ page: number = 1,
+ limit: number = 100,
+ identifiedOnly: boolean = false
+) {
+ const { time, site } = useStore();
+
+ const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+
+ // When filtering by userId, we fetch all sessions for that user (no time filter)
+ // Otherwise use buildApiParams which handles past-minutes mode
+ const params = userId
+ ? { startDate: "", endDate: "", timeZone, filters: filteredFilters }
+ : buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery<{ data: GetSessionsResponse }>({
+ queryKey: ["sessions", time, site, filteredFilters, userId, page, limit, identifiedOnly],
+ queryFn: () => {
+ return fetchSessions(site, {
+ ...params,
+ page,
+ limit,
+ userId,
+ identifiedOnly,
+ });
+ },
+ staleTime: Infinity,
+ });
+}
+
+export function useGetSessionsInfinite(userId?: string) {
+ const { time, site } = useStore();
+
+ const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
+
+ // When filtering by userId, we fetch all sessions for that user (no time filter)
+ // Otherwise use buildApiParams which handles past-minutes mode
+ const params = userId
+ ? { startDate: "", endDate: "", timeZone, filters: filteredFilters }
+ : buildApiParams(time, { filters: filteredFilters });
+
+ return useInfiniteQuery<{ data: GetSessionsResponse }>({
+ queryKey: ["sessions-infinite", time, site, filteredFilters, userId],
+ queryFn: ({ pageParam = 1 }) => {
+ return fetchSessions(site, {
+ ...params,
+ page: pageParam as number,
+ userId,
+ });
+ },
+ initialPageParam: 1,
+ getNextPageParam: (lastPage: { data: GetSessionsResponse }, allPages) => {
+ // If we have data and it's a full page (100 items), there might be more
+ if (lastPage?.data && lastPage.data.length === 100) {
+ return allPages.length + 1;
+ }
+ return undefined;
+ },
+ staleTime: Infinity,
+ });
+}
+
+export function useGetSessionDetailsInfinite(sessionId: string | null) {
+ const { site, time } = useStore();
+ const pastMinutesMode = time.mode === "past-minutes";
+
+ // Get minutes based on the time mode
+ let minutes: number | undefined;
+ if (pastMinutesMode && time.mode === "past-minutes") {
+ minutes = time.pastMinutesStart;
+ }
+
+ return useInfiniteQuery<{ data: SessionPageviewsAndEvents }>({
+ queryKey: ["session-details-infinite", sessionId, site, minutes],
+ queryFn: ({ pageParam = 0 }) => {
+ if (!sessionId) throw new Error("Session ID is required");
+
+ return fetchSession(site, {
+ sessionId,
+ limit: 100,
+ offset: pageParam as number,
+ minutes: pastMinutesMode ? minutes : undefined,
+ });
+ },
+ initialPageParam: 0,
+ getNextPageParam: lastPage => {
+ if (lastPage?.data?.pagination?.hasMore) {
+ return lastPage.data.pagination.offset + lastPage.data.pagination.limit;
+ }
+ return undefined;
+ },
+ enabled: !!sessionId && !!site,
+ staleTime: Infinity,
+ });
+}
+
+export function useGetUserSessionCount(userId: string) {
+ const { site } = useStore();
+
+ return useQuery<{ data: UserSessionCountResponse[] }>({
+ queryKey: ["user-session-count", userId, site],
+ queryFn: () => {
+ return fetchUserSessionCount(site, {
+ userId,
+ timeZone,
+ });
+ },
+ staleTime: Infinity,
+ enabled: !!site && !!userId,
+ });
+}
diff --git a/client/src/api/analytics/hooks/useGetUsers.ts b/client/src/api/analytics/hooks/useGetUsers.ts
new file mode 100644
index 000000000..316ad8703
--- /dev/null
+++ b/client/src/api/analytics/hooks/useGetUsers.ts
@@ -0,0 +1,55 @@
+import { Filter } from "@rybbit/shared";
+import { useQuery } from "@tanstack/react-query";
+import { getFilteredFilters, useStore } from "../../../lib/store";
+import { USER_PAGE_FILTERS } from "../../../lib/filterGroups";
+import { APIResponse } from "../../types";
+import { buildApiParams } from "../../utils";
+import { fetchUsers, UsersResponse } from "../endpoints";
+
+export interface GetUsersOptions {
+ page: number;
+ pageSize: number;
+ sortBy: string;
+ sortOrder: string;
+ filters?: Filter[];
+ identifiedOnly?: boolean;
+}
+
+export function useGetUsers(options: GetUsersOptions) {
+ const { time, site } = useStore();
+
+ const { page, pageSize, sortBy, sortOrder, identifiedOnly = false } = options;
+ const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
+ const params = buildApiParams(time, { filters: filteredFilters });
+
+ return useQuery<
+ APIResponse<UsersResponse[]> & {
+ totalCount: number;
+ page: number;
+ pageSize: number;
+ }
+ >({
+ queryKey: ["users", site, time, page, pageSize, sortBy, sortOrder, filteredFilters, identifiedOnly],
+ queryFn: async () => {
+ const result = await fetchUsers(site, {
+ ...params,
+ page,
+ pageSize,
+ sortBy,
+ sortOrder: sortOrder as "asc" | "desc",
+ identifiedOnly,
+ });
+ return {
+ data: result.data as UsersResponse[],
+ totalCount: result.totalCount,
+ page: result.page,
+ pageSize: result.pageSize,
+ };
+ },
+ // Use default staleTime (0) for real-time data
+ staleTime: 0,
+ // Enable refetching when the window regains focus
+ refetchOnWindowFocus: true,
+ enabled: !!site,
+ });
+}
diff --git a/client/src/api/analytics/hooks/userGetInfo.ts b/client/src/api/analytics/hooks/userGetInfo.ts
new file mode 100644
index 000000000..8738be447
--- /dev/null
+++ b/client/src/api/analytics/hooks/userGetInfo.ts
@@ -0,0 +1,10 @@
+import { useQuery } from "@tanstack/react-query";
+import { fetchUserInfo, UserInfo } from "../endpoints";
+
+export function useUserInfo(siteId: number, userId: string) {
+ return useQuery<UserInfo>({
+ queryKey: ["user-info", userId, siteId],
+ queryFn: () => fetchUserInfo(siteId, userId),
+ enabled: !!siteId && !!userId,
+ });
+}
diff --git a/client/src/api/analytics/performance/useGetPerformanceByDimension.ts b/client/src/api/analytics/performance/useGetPerformanceByDimension.ts
deleted file mode 100644
index b7b9d7173..000000000
--- a/client/src/api/analytics/performance/useGetPerformanceByDimension.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { usePerformanceStore } from "../../../app/[site]/performance/performanceStore";
-import { useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-type UseGetPerformanceByDimensionOptions = {
- site: number | string;
- dimension: string;
- limit?: number;
- page?: number;
- useFilters?: boolean;
- enabled?: boolean;
- additionalFilters?: Filter[];
- sortBy?: string;
- sortOrder?: "asc" | "desc";
-};
-
-// Generic type that can represent any dimension
-export type PerformanceByDimensionItem = {
- [key: string]: any; // The dimension field (pathname, country, etc.)
- event_count: number;
- lcp_avg: number | null;
- lcp_p50: number | null;
- lcp_p75: number | null;
- lcp_p90: number | null;
- lcp_p99: number | null;
- cls_avg: number | null;
- cls_p50: number | null;
- cls_p75: number | null;
- cls_p90: number | null;
- cls_p99: number | null;
- inp_avg: number | null;
- inp_p50: number | null;
- inp_p75: number | null;
- inp_p90: number | null;
- inp_p99: number | null;
- fcp_avg: number | null;
- fcp_p50: number | null;
- fcp_p75: number | null;
- fcp_p90: number | null;
- fcp_p99: number | null;
- ttfb_avg: number | null;
- ttfb_p50: number | null;
- ttfb_p75: number | null;
- ttfb_p90: number | null;
- ttfb_p99: number | null;
-};
-
-// Keep the old type for backward compatibility
-export type PerformanceByPathItem = PerformanceByDimensionItem & {
- pathname: string;
-};
-
-type PaginatedPerformanceResponse = {
- data: PerformanceByDimensionItem[];
- totalCount: number;
-};
-
-export function useGetPerformanceByDimension({
- site,
- dimension,
- limit = 10,
- page = 1,
- useFilters = true,
- enabled = true,
- additionalFilters = [],
- sortBy,
- sortOrder,
-}: UseGetPerformanceByDimensionOptions): UseQueryResult<PaginatedPerformanceResponse> {
- const { time, filters } = useStore();
- const { selectedPercentile } = usePerformanceStore();
-
- const queryParams = getQueryParams(time, {
- limit,
- page,
- percentile: selectedPercentile,
- filters: useFilters ? [...filters, ...additionalFilters] : undefined,
- sort_by: sortBy,
- sort_order: sortOrder,
- dimension,
- });
-
- return useQuery({
- queryKey: [
- "performance-by-dimension",
- dimension,
- time,
- site,
- filters,
- selectedPercentile,
- limit,
- page,
- additionalFilters,
- sortBy,
- sortOrder,
- ],
- queryFn: async () => {
- const response = await authedFetch<{ data: any }>(`/performance/by-dimension/${site}`, queryParams);
- return response.data;
- },
- staleTime: Infinity,
- placeholderData: (_, query: any) => {
- if (!query?.queryKey) return undefined;
- const prevQueryKey = query.queryKey;
- const [, , , prevSite] = prevQueryKey;
-
- if (prevSite === site) {
- return query.state.data;
- }
- return undefined;
- },
- enabled,
- });
-}
diff --git a/client/src/api/analytics/sessionReplay/useGetSessionReplayEvents.ts b/client/src/api/analytics/sessionReplay/useGetSessionReplayEvents.ts
deleted file mode 100644
index d69734a1a..000000000
--- a/client/src/api/analytics/sessionReplay/useGetSessionReplayEvents.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../../utils";
-
-export interface SessionReplayEvent {
- timestamp: number;
- type: string | number;
- data: any;
-}
-
-export interface SessionReplayMetadata {
- session_id: string;
- user_id: string;
- identified_user_id: string;
- traits: Record<string, unknown> | null;
- start_time: Date;
- end_time?: Date;
- duration_ms?: number;
- event_count: number;
- compressed_size_bytes: number;
- page_url: string;
- user_agent: string;
- country: string;
- region: string;
- city: string;
- lat: number;
- lon: number;
- browser: string;
- browser_version: string;
- operating_system: string;
- operating_system_version: string;
- language: string;
- screen_width: number;
- screen_height: number;
- device_type: string;
- channel: string;
- hostname: string;
- referrer: string;
- has_replay_data: boolean;
- created_at: Date;
-}
-
-export interface GetSessionReplayEventsResponse {
- events: SessionReplayEvent[];
- metadata: SessionReplayMetadata;
-}
-
-export function useGetSessionReplayEvents(siteId: number, sessionId: string) {
- return useQuery({
- queryKey: ["session-replay-events", siteId, sessionId],
- queryFn: () => {
- return authedFetch<GetSessionReplayEventsResponse>(`/session-replay/${sessionId}/${siteId}`);
- },
- enabled: !!siteId && !!sessionId,
- staleTime: 1000 * 60 * 10, // 10 minutes
- });
-}
diff --git a/client/src/api/analytics/sessionReplay/useGetSessionReplays.ts b/client/src/api/analytics/sessionReplay/useGetSessionReplays.ts
deleted file mode 100644
index 9aa6d33a6..000000000
--- a/client/src/api/analytics/sessionReplay/useGetSessionReplays.ts
+++ /dev/null
@@ -1,62 +0,0 @@
-import { useInfiniteQuery } from "@tanstack/react-query";
-import { useStore } from "../../../lib/store";
-import { authedFetch, getQueryParams } from "../../utils";
-
-export interface SessionReplayListItem {
- session_id: string;
- user_id: string;
- identified_user_id: string;
- traits: Record<string, unknown> | null;
- start_time: string;
- end_time?: string;
- duration_ms?: number;
- page_url: string;
- event_count: number;
- country: string;
- region: string;
- city: string;
- browser: string;
- browser_version: string;
- operating_system: string;
- operating_system_version: string;
- device_type: string;
- screen_width: number;
- screen_height: number;
-}
-
-export interface SessionReplayListResponse {
- data: SessionReplayListItem[];
- totalCount: number;
-}
-
-type UseGetSessionReplaysOptions = {
- limit?: number;
- minDuration?: number;
-};
-
-export function useGetSessionReplays({ limit = 20, minDuration = 30 }: UseGetSessionReplaysOptions = {}) {
- const { time, site, filters } = useStore();
-
- return useInfiniteQuery({
- queryKey: ["session-replays", site, time, filters, limit, minDuration],
- queryFn: async ({ pageParam = 0 }) => {
- const queryParams = {
- ...getQueryParams(time),
- limit,
- offset: pageParam,
- filters,
- minDuration,
- };
-
- const response = await authedFetch<SessionReplayListResponse>(`/session-replay/list/${site}`, queryParams);
- return response;
- },
- initialPageParam: 0,
- getNextPageParam: (lastPage, allPages) => {
- const totalFetched = allPages.reduce((acc, page) => acc + (page.data?.length || 0), 0);
- return lastPage.data?.length === limit ? totalFetched : undefined;
- },
- staleTime: 1000 * 60 * 5, // 5 minutes
- refetchOnWindowFocus: false,
- });
-}
diff --git a/client/src/api/analytics/useGetJourneys.ts b/client/src/api/analytics/useGetJourneys.ts
deleted file mode 100644
index 186b6d6b5..000000000
--- a/client/src/api/analytics/useGetJourneys.ts
+++ /dev/null
@@ -1,43 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { Time } from "../../components/DateSelector/types";
-import { JOURNEY_PAGE_FILTERS } from "../../lib/filterGroups";
-import { getFilteredFilters } from "../../lib/store";
-import { authedFetch, getQueryParams } from "../utils";
-
-export interface JourneyParams {
- siteId?: number;
- steps?: number;
- timeZone?: string;
- time: Time;
- limit?: number;
- stepFilters?: Record<number, string>;
-}
-
-export interface Journey {
- path: string[];
- count: number;
- percentage: number;
-}
-
-export interface JourneysResponse {
- journeys: Journey[];
-}
-
-export const useJourneys = ({ siteId, steps = 3, time, limit = 100, stepFilters }: JourneyParams) => {
- const filteredFilters = getFilteredFilters(JOURNEY_PAGE_FILTERS);
-
- return useQuery<JourneysResponse>({
- queryKey: ["journeys", siteId, steps, time, limit, filteredFilters, stepFilters],
- queryFn: async () => {
- const params = getQueryParams(time, {
- steps,
- limit,
- filters: filteredFilters,
- stepFilters: stepFilters && Object.keys(stepFilters).length > 0 ? JSON.stringify(stepFilters) : undefined,
- });
- return authedFetch<JourneysResponse>(`/journeys/${siteId}`, params);
- },
- enabled: !!siteId,
- placeholderData: previousData => previousData,
- });
-};
diff --git a/client/src/api/analytics/useGetLiveUserCount.ts b/client/src/api/analytics/useGetLiveUserCount.ts
deleted file mode 100644
index c293b9111..000000000
--- a/client/src/api/analytics/useGetLiveUserCount.ts
+++ /dev/null
@@ -1,19 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { authedFetch } from "../utils";
-
-export interface LiveUserCountResponse {
- count: number;
-}
-
-export function useGetLiveUsercount(minutes = 5) {
- const { site } = useStore();
- return useQuery<LiveUserCountResponse>({
- queryKey: ["live-user-count", site, minutes],
- refetchInterval: 5000,
- queryFn: () =>
- authedFetch<LiveUserCountResponse>(`/live-user-count/${site}`, {
- minutes,
- }),
- });
-}
diff --git a/client/src/api/analytics/useGetOrgEventCount.ts b/client/src/api/analytics/useGetOrgEventCount.ts
deleted file mode 100644
index b4947d280..000000000
--- a/client/src/api/analytics/useGetOrgEventCount.ts
+++ /dev/null
@@ -1,60 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-
-export type OrgEventCountResponse = {
- event_date: string;
- pageview_count: number;
- custom_event_count: number;
- performance_count: number;
- event_count: number;
-}[];
-
-export type GetOrgEventCountResponse = {
- data: OrgEventCountResponse;
-};
-
-async function getOrgEventCount({
- organizationId,
- startDate,
- endDate,
- timeZone = "UTC",
-}: {
- organizationId: string;
- startDate?: string;
- endDate?: string;
- timeZone?: string;
-}): Promise<GetOrgEventCountResponse> {
- const params = new URLSearchParams();
- if (startDate) params.append("start_date", startDate);
- if (endDate) params.append("end_date", endDate);
- if (timeZone) params.append("time_zone", timeZone);
-
- return authedFetch(`/org-event-count/${organizationId}`, Object.fromEntries(params));
-}
-
-export function useGetOrgEventCount({
- organizationId,
- startDate,
- endDate,
- timeZone = "UTC",
- enabled = true,
-}: {
- organizationId: string;
- startDate?: string;
- endDate?: string;
- timeZone?: string;
- enabled?: boolean;
-}) {
- return useQuery({
- queryKey: ["org-event-count", organizationId, startDate, endDate, timeZone],
- queryFn: () =>
- getOrgEventCount({
- organizationId,
- startDate,
- endDate,
- timeZone,
- }),
- enabled: enabled && !!organizationId,
- staleTime: 1000 * 60 * 5, // 5 minutes
- });
-}
diff --git a/client/src/api/analytics/useGetPageTitles.ts b/client/src/api/analytics/useGetPageTitles.ts
deleted file mode 100644
index b12b63eaa..000000000
--- a/client/src/api/analytics/useGetPageTitles.ts
+++ /dev/null
@@ -1,55 +0,0 @@
-import { useStore } from "@/lib/store";
-import { useQuery, UseQueryResult } from "@tanstack/react-query";
-import { APIResponse } from "../types";
-import { authedFetch, getQueryParams } from "../utils";
-
-// This should match PageTitleItem from the backend
-export type PageTitleItem = {
- value: string; // The page_title
- pathname: string; // A representative pathname
- count: number;
- percentage: number;
- time_on_page_seconds?: number;
- // Add other potential fields if your backend query for page_titles includes them
-};
-
-// This should match the paginated response structure from getPageTitles.ts
-export type PageTitlesPaginatedResponse = {
- data: PageTitleItem[];
- totalCount: number;
-};
-
-// This is for non-paginated use by StandardSection (or similar)
-// It directly expects an array of PageTitleItem ype PageTitlesStandardResponse = PageTitleItem[];
-export type PageTitlesStandardResponse = PageTitleItem[];
-
-type UseGetPageTitlesOptions = {
- limit?: number;
- page?: number;
- useFilters?: boolean;
- // No specific 'parameter' needed as this hook is for page_titles
-};
-
-// Hook for paginated fetching (e.g., for a dedicated "All Page Titles" screen)
-export function useGetPageTitlesPaginated({
- limit = 10,
- page = 1,
- useFilters = true,
-}: UseGetPageTitlesOptions): UseQueryResult<APIResponse<PageTitlesPaginatedResponse>> {
- const { time, site, filters } = useStore();
-
- const queryParams = {
- ...getQueryParams(time),
- limit,
- page,
- filters: useFilters ? filters : undefined,
- };
-
- return useQuery({
- queryKey: ["page-titles", time, site, filters, limit, page],
- queryFn: () => {
- return authedFetch<APIResponse<PageTitlesPaginatedResponse>>(`/page-titles/${site}`, queryParams);
- },
- staleTime: Infinity,
- });
-}
diff --git a/client/src/api/analytics/useGetRetention.ts b/client/src/api/analytics/useGetRetention.ts
deleted file mode 100644
index 0cebc503d..000000000
--- a/client/src/api/analytics/useGetRetention.ts
+++ /dev/null
@@ -1,26 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { authedFetch } from "../utils";
-
-// Define the interface for processed retention data
-export interface ProcessedRetentionData {
- cohorts: Record<string, { size: number; percentages: (number | null)[] }>;
- maxPeriods: number;
- mode: "day" | "week";
- range: number;
-}
-
-export type RetentionMode = "day" | "week";
-
-export function useGetRetention(mode: RetentionMode = "week", range: number = 90) {
- const { site } = useStore();
- return useQuery<ProcessedRetentionData>({
- queryKey: ["retention", site, mode, range],
- queryFn: async () => {
- const response = await authedFetch<{
- data: ProcessedRetentionData;
- }>(`/retention/${site}`, { mode, range });
- return response.data;
- },
- });
-}
diff --git a/client/src/api/analytics/useGetSessionLocations.ts b/client/src/api/analytics/useGetSessionLocations.ts
deleted file mode 100644
index b4324b0d1..000000000
--- a/client/src/api/analytics/useGetSessionLocations.ts
+++ /dev/null
@@ -1,33 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { useStore } from "../../lib/store";
-import { authedFetch, getQueryParams } from "../utils";
-
-export type LiveSessionLocation = {
- lat: number;
- lon: number;
- count: number;
- city: string;
- country: string;
-};
-
-export function useGetSessionLocations() {
- const { time, site, filters } = useStore();
- return useQuery<LiveSessionLocation[]>({
- queryKey: ["session-locations", site, time, filters],
- queryFn: () => {
- const queryParams = {
- ...getQueryParams(time),
- filters: filters.filter(
- f =>
- f.parameter !== "lat" &&
- f.parameter !== "lon" &&
- f.parameter !== "city" &&
- f.parameter !== "country" &&
- f.parameter !== "region"
- ),
- };
-
- return authedFetch(`/session-locations/${site}`, queryParams).then((res: any) => res.data);
- },
- });
-}
diff --git a/client/src/api/analytics/useGetUserSessions.ts b/client/src/api/analytics/useGetUserSessions.ts
deleted file mode 100644
index a18064ec9..000000000
--- a/client/src/api/analytics/useGetUserSessions.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import { useInfiniteQuery, useQuery } from "@tanstack/react-query";
-import { timeZone } from "../../lib/dateTimeUtils";
-import { getFilteredFilters, useStore } from "../../lib/store";
-import { SESSION_PAGE_FILTERS } from "../../lib/filterGroups";
-import { APIResponse } from "../types";
-import { authedFetch, getQueryParams } from "../utils";
-
-export type GetSessionsResponse = {
- session_id: string;
- user_id: string; // Device fingerprint
- identified_user_id: string; // Custom user ID when identified, empty string otherwise
- traits: Record<string, unknown> | null;
- country: string;
- region: string;
- city: string;
- language: string;
- device_type: string;
- browser: string;
- browser_version: string;
- operating_system: string;
- operating_system_version: string;
- screen_width: number;
- screen_height: number;
- referrer: string;
- channel: string;
- hostname: string;
- page_title: string;
- querystring: string;
- utm_source: string;
- utm_medium: string;
- utm_campaign: string;
- utm_term: string;
- utm_content: string;
- session_end: string;
- session_start: string;
- session_duration: number;
- entry_page: string;
- exit_page: string;
- pageviews: number;
- events: number;
- errors: number;
- outbound: number;
- ip: string;
- lat: number;
- lon: number;
-}[];
-
-export function useGetSessions(
- userId?: string,
- page: number = 1,
- limit: number = 100,
- identifiedOnly: boolean = false
-) {
- const { time, site } = useStore();
-
- // Get the appropriate time parameters using getQueryParams
- const timeParams = getQueryParams(time);
-
- const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
-
- return useQuery<APIResponse<GetSessionsResponse>>({
- queryKey: ["sessions", time, site, filteredFilters, userId, page, limit, identifiedOnly],
- queryFn: () => {
- // Use an object for request parameters so we can conditionally add fields
- const requestParams: Record<string, any> = {
- time_zone: timeZone,
- filters: filteredFilters,
- page,
- limit,
- identified_only: identifiedOnly,
- };
-
- // Add userId if provided
- if (userId) {
- requestParams.user_id = userId;
- }
-
- // Add time parameters
- if (time.mode === "past-minutes") {
- Object.assign(requestParams, timeParams);
- } else if (!userId) {
- // Only add date parameters if not filtering by userId
- requestParams.start_date = timeParams.start_date;
- requestParams.end_date = timeParams.end_date;
- }
-
- return authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);
- },
- staleTime: Infinity,
- });
-}
-
-export function useGetSessionsInfinite(userId?: string) {
- const { time, site } = useStore();
-
- // Get the appropriate time parameters using getQueryParams
- const timeParams = getQueryParams(time);
-
- const filteredFilters = getFilteredFilters(SESSION_PAGE_FILTERS);
-
- return useInfiniteQuery<APIResponse<GetSessionsResponse>>({
- queryKey: ["sessions-infinite", time, site, filteredFilters, userId],
- queryFn: ({ pageParam = 1 }) => {
- // Use an object for request parameters so we can conditionally add fields
- const requestParams: Record<string, any> = {
- time_zone: timeZone,
- filters: filteredFilters,
- page: pageParam,
- };
-
- // Add userId if provided
- if (userId) {
- requestParams.user_id = userId;
- }
-
- // Add time parameters
- if (time.mode === "past-minutes") {
- Object.assign(requestParams, timeParams);
- } else if (!userId) {
- // Only add date parameters if not filtering by userId
- requestParams.start_date = timeParams.start_date;
- requestParams.end_date = timeParams.end_date;
- }
-
- return authedFetch<APIResponse<GetSessionsResponse>>(`/sessions/${site}`, requestParams);
- },
- initialPageParam: 1,
- getNextPageParam: (lastPage: APIResponse<GetSessionsResponse>, allPages) => {
- // If we have data and it's a full page (100 items), there might be more
- if (lastPage?.data && lastPage.data.length === 100) {
- return allPages.length + 1;
- }
- return undefined;
- },
- staleTime: Infinity,
- });
-}
-
-export interface SessionDetails {
- session_id: string;
- user_id: string;
- country: string;
- region: string;
- city: string;
- language: string;
- device_type: string;
- browser: string;
- browser_version: string;
- operating_system: string;
- operating_system_version: string;
- screen_width: number;
- screen_height: number;
- referrer: string;
- channel: string;
- session_end: string;
- session_start: string;
- pageviews: number;
- entry_page: string;
- exit_page: string;
- ip: string;
-}
-
-export interface SessionEventProps {
- [key: string]: unknown;
-
- // Error-specific props
- message?: string;
- stack?: string;
-}
-
-export interface SessionEvent {
- timestamp: string;
- pathname: string;
- hostname: string;
- querystring: string;
- page_title: string;
- referrer: string;
- type: string;
- event_name?: string;
- props?: SessionEventProps;
-}
-
-export interface SessionPageviewsAndEvents {
- session: SessionDetails;
- events: SessionEvent[];
- pagination: {
- total: number;
- limit: number;
- offset: number;
- hasMore: boolean;
- };
-}
-
-export function useGetSessionDetailsInfinite(sessionId: string | null) {
- const { site, time } = useStore();
- const pastMinutesMode = time.mode === "past-minutes";
-
- // Get minutes based on the time mode
- let minutes: number | undefined;
- if (pastMinutesMode) {
- if (time.mode === "past-minutes") {
- minutes = time.pastMinutesStart; // Use the dynamic value
- }
- }
-
- return useInfiniteQuery<APIResponse<SessionPageviewsAndEvents>>({
- queryKey: ["session-details-infinite", sessionId, site, minutes],
- queryFn: ({ pageParam = 0 }) => {
- if (!sessionId) throw new Error("Session ID is required");
- const limit = 100;
-
- // Build query parameters object
- const queryParams: Record<string, any> = {
- limit,
- offset: pageParam,
- };
-
- if (pastMinutesMode && minutes) {
- queryParams.minutes = minutes;
- }
-
- return authedFetch<APIResponse<SessionPageviewsAndEvents>>(`/sessions/${sessionId}/${site}`, queryParams);
- },
- initialPageParam: 0,
- getNextPageParam: lastPage => {
- if (lastPage?.data?.pagination?.hasMore) {
- return lastPage.data.pagination.offset + lastPage.data.pagination.limit;
- }
- return undefined;
- },
- enabled: !!sessionId && !!site,
- staleTime: Infinity,
- });
-}
-
-export interface UserSessionCountResponse {
- date: string;
- sessions: number;
-}
-
-export function useGetUserSessionCount(userId: string) {
- const { site } = useStore();
-
- return useQuery<APIResponse<UserSessionCountResponse[]>>({
- queryKey: ["user-session-count", userId, site],
- queryFn: () => {
- return authedFetch<APIResponse<UserSessionCountResponse[]>>(`/users/session-count/${site}`, {
- user_id: userId,
- time_zone: timeZone,
- });
- },
- staleTime: Infinity,
- });
-}
diff --git a/client/src/api/analytics/useGetUsers.ts b/client/src/api/analytics/useGetUsers.ts
deleted file mode 100644
index f7858aff8..000000000
--- a/client/src/api/analytics/useGetUsers.ts
+++ /dev/null
@@ -1,84 +0,0 @@
-import { Filter } from "@rybbit/shared";
-import { useQuery } from "@tanstack/react-query";
-import { timeZone } from "../../lib/dateTimeUtils";
-import { getFilteredFilters, useStore } from "../../lib/store";
-import { USER_PAGE_FILTERS } from "../../lib/filterGroups";
-import { APIResponse } from "../types";
-import { authedFetch, getQueryParams } from "../utils";
-
-export type UsersResponse = {
- user_id: string; // Device fingerprint
- identified_user_id: string; // Custom user ID when identified, empty string otherwise
- traits: Record<string, unknown> | null;
- country: string;
- region: string;
- city: string;
- language: string;
- browser: string;
- operating_system: string;
- device_type: string;
- referrer: string;
- channel: string;
- pageviews: number;
- events: number;
- sessions: number;
- last_seen: string;
- first_seen: string;
-};
-
-export interface GetUsersOptions {
- page: number;
- pageSize: number;
- sortBy: string;
- sortOrder: string;
- filters?: Filter[];
- identifiedOnly?: boolean;
-}
-
-export function useGetUsers(options: GetUsersOptions) {
- const { time, site } = useStore();
- // Get the appropriate time parameters using getQueryParams
- const timeParams = getQueryParams(time);
-
- const { page, pageSize, sortBy, sortOrder, identifiedOnly = false } = options;
- const filteredFilters = getFilteredFilters(USER_PAGE_FILTERS);
-
- return useQuery<
- APIResponse<UsersResponse[]> & {
- totalCount: number;
- page: number;
- pageSize: number;
- }
- >({
- queryKey: ["users", site, time, page, pageSize, sortBy, sortOrder, filteredFilters, identifiedOnly],
- queryFn: async () => {
- // Build request parameters
- const requestParams: Record<string, any> = {
- time_zone: timeZone,
- filters: filteredFilters,
- page,
- page_size: pageSize,
- sort_by: sortBy,
- sort_order: sortOrder,
- identified_only: identifiedOnly,
- };
-
- // Add time parameters (getQueryParams handles both past-minutes and regular modes)
- Object.assign(requestParams, timeParams);
-
- return authedFetch<
- APIResponse<UsersResponse[]> & {
- totalCount: number;
- page: number;
- pageSize: number;
- }
- >(`/users/${site}`, requestParams);
- },
- // Use default staleTime (0) for real-time data
- staleTime: 0,
- // Enable refetching when the window regains focus
- refetchOnWindowFocus: true,
- // Add a background refetch interval (every 30 seconds)
- // refetchInterval: 30000,
- });
-}
diff --git a/client/src/api/analytics/userGetInfo.ts b/client/src/api/analytics/userGetInfo.ts
deleted file mode 100644
index 2584072dd..000000000
--- a/client/src/api/analytics/userGetInfo.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-import { useQuery } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-
-export type LinkedDevice = {
- anonymous_id: string;
- created_at: string;
-};
-
-export type UserInfo = {
- duration: number;
- sessions: number;
- user_id: string; // Device fingerprint
- identified_user_id: string; // Custom user ID when identified, empty string otherwise
- country: string;
- region: string;
- city: string;
- language: string;
- device_type: string;
- browser: string;
- browser_version: string;
- operating_system: string;
- operating_system_version: string;
- screen_height: number;
- screen_width: number;
- last_seen: string;
- first_seen: string;
- pageviews: number;
- events: number;
- ip?: string;
- traits: Record<string, unknown> | null;
- linked_devices: LinkedDevice[];
-};
-
-export function useUserInfo(siteId: number, userId: string) {
- return useQuery<UserInfo>({
- queryKey: ["user-info", userId, siteId],
- queryFn: async () => {
- const response = await authedFetch<{ data: UserInfo }>(`/users/${userId}/${siteId}`);
- return response.data;
- },
- });
-}
diff --git a/client/src/api/utils.ts b/client/src/api/utils.ts
index 9a7ef2343..754ade780 100644
--- a/client/src/api/utils.ts
+++ b/client/src/api/utils.ts
@@ -1,36 +1,44 @@
+import { Filter } from "@rybbit/shared";
import { DateTime } from "luxon";
import { Time } from "../components/DateSelector/types";
import axios, { AxiosRequestConfig } from "axios";
import { BACKEND_URL } from "../lib/const";
import { timeZone } from "../lib/dateTimeUtils";
import { useStore } from "../lib/store";
+import { CommonApiParams } from "./analytics/endpoints/types";
-function getStartAndEndDate(time: Time) {
+export function getStartAndEndDate(time: Time): { startDate: string | null; endDate: string | null } {
if (time.mode === "range") {
- return { start_date: time.startDate, end_date: time.endDate };
+ return { startDate: time.startDate, endDate: time.endDate };
}
if (time.mode === "week") {
return {
- start_date: time.week,
- end_date: DateTime.fromISO(time.week).endOf("week").toISODate(),
+ startDate: time.week,
+ endDate: DateTime.fromISO(time.week).endOf("week").toISODate(),
};
}
if (time.mode === "month") {
return {
- start_date: time.month,
- end_date: DateTime.fromISO(time.month).endOf("month").toISODate(),
+ startDate: time.month,
+ endDate: DateTime.fromISO(time.month).endOf("month").toISODate(),
};
}
if (time.mode === "year") {
return {
- start_date: time.year,
- end_date: DateTime.fromISO(time.year).endOf("year").toISODate(),
+ startDate: time.year,
+ endDate: DateTime.fromISO(time.year).endOf("year").toISODate(),
};
}
if (time.mode === "all-time" || time.mode === "past-minutes") {
- return { start_date: null, end_date: null };
+ return { startDate: null, endDate: null };
}
- return { start_date: time.day, end_date: time.day };
+ return { startDate: time.day, endDate: time.day };
+}
+
+// Internal version that uses snake_case for getQueryParams
+function getStartAndEndDateSnake(time: Time) {
+ const { startDate, endDate } = getStartAndEndDate(time);
+ return { start_date: startDate, end_date: endDate };
}
export function getQueryParams(time: Time, additionalParams: Record<string, any> = {}): Record<string, any> {
@@ -45,12 +53,43 @@ export function getQueryParams(time: Time, additionalParams: Record<string, any>
// Regular date-based approach
return {
- ...getStartAndEndDate(time),
+ ...getStartAndEndDateSnake(time),
time_zone: timeZone,
...additionalParams,
};
}
+// Re-export timeZone for convenience
+export { timeZone };
+
+/**
+ * Build CommonApiParams from a Time object, handling all time modes including past-minutes.
+ * This centralizes the logic for converting Time to API params across all hooks.
+ */
+export function buildApiParams(
+ time: Time,
+ options: { filters?: Filter[] } = {}
+): CommonApiParams {
+ if (time.mode === "past-minutes") {
+ return {
+ startDate: "",
+ endDate: "",
+ timeZone,
+ filters: options.filters,
+ pastMinutesStart: time.pastMinutesStart,
+ pastMinutesEnd: time.pastMinutesEnd,
+ };
+ }
+
+ const { startDate, endDate } = getStartAndEndDate(time);
+ return {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters: options.filters,
+ };
+}
+
export async function authedFetch<T>(
url: string,
params?: Record<string, any>,
diff --git a/client/src/app/[site]/api-playground/components/ApiPlayground.tsx b/client/src/app/[site]/api-playground/components/ApiPlayground.tsx
new file mode 100644
index 000000000..1598cbbb9
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/ApiPlayground.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { EndpointList } from "./EndpointList";
+import { ParameterControls } from "./ParameterControls";
+import { ResponsePanel } from "./ResponsePanel";
+
+export function ApiPlayground() {
+ return (
+ <div className="h-[calc(100vh-100px)] flex border border-neutral-100 dark:border-neutral-850 rounded-lg overflow-hidden bg-white dark:bg-neutral-900">
+ {/* Left Column - Endpoint List */}
+ <div className="w-64 shrink-0">
+ <EndpointList />
+ </div>
+
+ {/* Center Column - Parameter Controls */}
+ <div className="w-[600px] shrink-0 border-neutral-200 dark:border-neutral-800">
+ <ParameterControls />
+ </div>
+
+ {/* Right Column - Response Panel */}
+ <div className="flex-1 min-w-0 border-l border-neutral-100 dark:border-neutral-850 overflow-hidden">
+ <ResponsePanel />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/CodeExamples.tsx b/client/src/app/[site]/api-playground/components/CodeExamples.tsx
new file mode 100644
index 000000000..de8846fa9
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/CodeExamples.tsx
@@ -0,0 +1,59 @@
+"use client";
+
+import { memo, useState, useMemo } from "react";
+import { cn } from "@/lib/utils";
+import { CodeSnippet } from "@/components/CodeSnippet";
+import { codeGenerators, languageOrder, CodeGenConfig } from "../utils/codeGenerators";
+
+interface CodeExamplesProps {
+ config: CodeGenConfig;
+}
+
+export const CodeExamples = memo(function CodeExamples({ config }: CodeExamplesProps) {
+ const [selectedLang, setSelectedLang] = useState("cURL");
+
+ // Memoize the code generation
+ const code = useMemo(() => codeGenerators[selectedLang]?.(config) || "", [selectedLang, config]);
+
+ const language = useMemo(() => getLanguageForHighlight(selectedLang), [selectedLang]);
+
+ return (
+ <div className="space-y-2">
+ {/* Language tabs */}
+ <div className="flex flex-wrap gap-1">
+ {languageOrder.map(lang => (
+ <button
+ key={lang}
+ onClick={() => setSelectedLang(lang)}
+ className={cn(
+ "px-2 py-1 text-xs rounded transition-colors",
+ selectedLang === lang
+ ? "bg-neutral-100 dark:bg-neutral-700 text-neutral-900 dark:text-neutral-100"
+ : "text-neutral-600 dark:text-neutral-400 hover:bg-neutral-50 dark:hover:bg-neutral-800"
+ )}
+ >
+ {lang}
+ </button>
+ ))}
+ </div>
+
+ {/* Code display */}
+ <CodeSnippet code={code} language={language} />
+ </div>
+ );
+});
+
+function getLanguageForHighlight(lang: string): string {
+ const map: Record<string, string> = {
+ cURL: "bash",
+ JavaScript: "javascript",
+ Python: "python",
+ PHP: "php",
+ Ruby: "ruby",
+ Go: "go",
+ Rust: "rust",
+ Java: "java",
+ ".NET": "csharp",
+ };
+ return map[lang] || "text";
+}
diff --git a/client/src/app/[site]/api-playground/components/EndpointList.tsx b/client/src/app/[site]/api-playground/components/EndpointList.tsx
new file mode 100644
index 000000000..eb7cce6d8
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/EndpointList.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import { cn } from "@/lib/utils";
+import { endpointCategories, EndpointConfig, methodColors } from "../utils/endpointConfig";
+import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
+
+export function EndpointList() {
+ const { selectedEndpoint, setSelectedEndpoint } = usePlaygroundStore();
+
+ return (
+ <div className="h-full overflow-y-auto border-r border-neutral-100 dark:border-neutral-850">
+ <div className="p-3 border-b border-neutral-100 dark:border-neutral-850">
+ <h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100">Endpoints</h2>
+ </div>
+ <div className="p-2">
+ {endpointCategories.map(category => (
+ <div key={category.name} className="mb-4">
+ <h3 className="px-2 py-1 text-xs font-medium text-neutral-500 dark:text-neutral-400 uppercase tracking-wider">
+ {category.name}
+ </h3>
+ <div className="space-y-1 mt-1">
+ {category.endpoints.map(endpoint => (
+ <EndpointItem
+ key={`${endpoint.method}-${endpoint.path}`}
+ endpoint={endpoint}
+ isSelected={selectedEndpoint?.path === endpoint.path && selectedEndpoint?.method === endpoint.method}
+ onClick={() => setSelectedEndpoint(endpoint)}
+ />
+ ))}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
+interface EndpointItemProps {
+ endpoint: EndpointConfig;
+ isSelected: boolean;
+ onClick: () => void;
+}
+
+function EndpointItem({ endpoint, isSelected, onClick }: EndpointItemProps) {
+ return (
+ <button
+ onClick={onClick}
+ className={cn(
+ "w-full flex items-center gap-2 px-2 py-1.5 rounded-md text-left transition-colors",
+ "hover:bg-neutral-100 dark:hover:bg-neutral-800",
+ isSelected && "bg-neutral-100 dark:bg-neutral-800"
+ )}
+ >
+ <span className={cn("shrink-0 px-1 py-0.5 text-[10px] font-bold rounded", methodColors[endpoint.method])}>
+ {endpoint.method}
+ </span>
+ <span className="text-sm text-neutral-700 dark:text-neutral-300 truncate">{endpoint.name}</span>
+ </button>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/FilterBuilder.tsx b/client/src/app/[site]/api-playground/components/FilterBuilder.tsx
new file mode 100644
index 000000000..ef6de1670
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/FilterBuilder.tsx
@@ -0,0 +1,82 @@
+"use client";
+
+import { Button } from "@/components/ui/button";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Plus, X } from "lucide-react";
+import { filterOperators, filterParameters, usePlaygroundStore } from "../hooks/usePlaygroundStore";
+
+export function FilterBuilder() {
+ const { filters, addFilter, updateFilter, removeFilter } = usePlaygroundStore();
+
+ return (
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">Filters</label>
+ <Button variant="ghost" size="sm" onClick={addFilter} className="h-7 px-2 text-xs">
+ <Plus className="h-3 w-3 mr-1" />
+ Add Filter
+ </Button>
+ </div>
+
+ {filters.length === 0 ? (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">
+ No filters applied. Click &quot;Add Filter&quot; to add one.
+ </p>
+ ) : (
+ <div className="space-y-2">
+ {filters.map((filter, index) => (
+ <div key={index} className="flex items-center gap-2">
+ <Select
+ value={filter.parameter}
+ onValueChange={value => updateFilter(index, { ...filter, parameter: value })}
+ >
+ <SelectTrigger className="w-[140px] h-8 text-xs">
+ <SelectValue placeholder="Parameter" />
+ </SelectTrigger>
+ <SelectContent>
+ {filterParameters.map(param => (
+ <SelectItem key={param.value} value={param.value} className="text-xs">
+ {param.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Select
+ value={filter.operator}
+ onValueChange={value => updateFilter(index, { ...filter, operator: value })}
+ >
+ <SelectTrigger className="w-[120px] h-8 text-xs">
+ <SelectValue placeholder="Operator" />
+ </SelectTrigger>
+ <SelectContent>
+ {filterOperators.map(op => (
+ <SelectItem key={op.value} value={op.value} className="text-xs">
+ {op.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+
+ <Input
+ value={filter.value}
+ onChange={e => updateFilter(index, { ...filter, value: e.target.value })}
+ placeholder="Value"
+ className="flex-1 h-8 text-xs"
+ />
+
+ <Button
+ variant="ghost"
+ onClick={() => removeFilter(index)}
+ className="h-5 w-5 p-0 text-neutral-500 hover:text-red-500"
+ >
+ <X className="h-3 w-3" />
+ </Button>
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/ParameterControls.tsx b/client/src/app/[site]/api-playground/components/ParameterControls.tsx
new file mode 100644
index 000000000..1a7338942
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/ParameterControls.tsx
@@ -0,0 +1,332 @@
+"use client";
+
+import { authedFetch } from "@/api/utils";
+import { Input } from "@/components/ui/input";
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { Loader2, Play } from "lucide-react";
+import { useParams } from "next/navigation";
+import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
+import { methodColors, parameterMetadata } from "../utils/endpointConfig";
+import { FilterBuilder } from "./FilterBuilder";
+import { TimezoneSelect } from "./TimezoneSelect";
+import { RequestBodyEditor } from "./RequestBodyEditor";
+
+export function ParameterControls() {
+ const params = useParams();
+ const siteId = params.site as string;
+
+ const {
+ selectedEndpoint,
+ startDate,
+ endDate,
+ timeZone,
+ filters,
+ setStartDate,
+ setEndDate,
+ endpointParams,
+ setEndpointParam,
+ pathParams,
+ setPathParam,
+ requestBody,
+ isLoading,
+ setResponse,
+ setResponseError,
+ setIsLoading,
+ } = usePlaygroundStore();
+
+ // Handle execute request
+ const handleExecute = async () => {
+ if (!selectedEndpoint) return;
+
+ // Validate path params
+ if (selectedEndpoint.pathParams) {
+ for (const param of selectedEndpoint.pathParams) {
+ if (!pathParams[param]) {
+ setResponseError(`Missing required path parameter: ${param}`);
+ return;
+ }
+ }
+ }
+
+ // Validate required query params
+ if (selectedEndpoint.requiredParams) {
+ for (const param of selectedEndpoint.requiredParams) {
+ if (!endpointParams[param]) {
+ setResponseError(`Missing required parameter: ${param}`);
+ return;
+ }
+ }
+ }
+
+ // Parse request body
+ let parsedBody: any;
+ if (selectedEndpoint.hasRequestBody && requestBody) {
+ try {
+ parsedBody = JSON.parse(requestBody);
+ } catch {
+ setResponseError("Invalid JSON in request body");
+ return;
+ }
+ }
+
+ setIsLoading(true);
+ const startTime = performance.now();
+
+ try {
+ // Build the path
+ let path = selectedEndpoint.path.replace(":site", siteId);
+ if (selectedEndpoint.pathParams) {
+ for (const param of selectedEndpoint.pathParams) {
+ path = path.replace(`:${param}`, pathParams[param]);
+ }
+ }
+
+ // Build query params
+ const queryParams: Record<string, any> = {};
+
+ if (selectedEndpoint.hasCommonParams) {
+ queryParams.start_date = startDate;
+ queryParams.end_date = endDate;
+ queryParams.time_zone = timeZone;
+
+ const apiFilters = filters
+ .filter(f => f.value.trim() !== "")
+ .map(f => ({
+ parameter: f.parameter,
+ type: f.operator,
+ value: [f.value],
+ }));
+ if (apiFilters.length > 0) {
+ queryParams.filters = JSON.stringify(apiFilters);
+ }
+ }
+
+ // Add endpoint-specific params
+ if (selectedEndpoint.specificParams) {
+ for (const param of selectedEndpoint.specificParams) {
+ if (endpointParams[param]) {
+ queryParams[param] = endpointParams[param];
+ }
+ }
+ }
+
+ // Make the request
+ const result = await authedFetch<any>(
+ path,
+ queryParams,
+ selectedEndpoint.method !== "GET"
+ ? {
+ method: selectedEndpoint.method,
+ data: parsedBody,
+ }
+ : undefined
+ );
+
+ const endTime = performance.now();
+ setResponse(result, Math.round(endTime - startTime));
+ } catch (err: any) {
+ setResponseError(err.message || "Request failed");
+ }
+ };
+
+ if (!selectedEndpoint) {
+ return (
+ <div className="h-full flex items-center justify-center text-neutral-500 dark:text-neutral-400 p-4">
+ <p className="text-sm text-center">Select an endpoint from the list to configure parameters</p>
+ </div>
+ );
+ }
+
+ // Format path with highlighted parameters
+ const formatPath = (path: string) => {
+ // Replace :site with actual siteId
+ let displayPath = path.replace(":site", siteId);
+
+ // Split by path parameters (e.g., :param) and render them differently
+ const parts = displayPath.split(/(:[\w]+)/g);
+
+ return parts.map((part, index) => {
+ if (part.startsWith(":")) {
+ const paramName = part.slice(1);
+ const value = pathParams[paramName];
+ return (
+ <span
+ key={index}
+ className="px-1.5 py-0.5 mx-0.5 rounded border border-emerald-500/50 bg-emerald-500/10 text-emerald-400 font-mono"
+ >
+ {value || `{${paramName}}`}
+ </span>
+ );
+ }
+ return <span key={index}>{part}</span>;
+ });
+ };
+
+ return (
+ <div className="h-full overflow-y-auto p-4 space-y-6">
+ {/* Header */}
+ <div className="space-y-3">
+ <div>
+ <h2 className="text-sm font-semibold text-neutral-900 dark:text-neutral-100 mb-1">{selectedEndpoint.name}</h2>
+ {selectedEndpoint.description && (
+ <p className="text-xs text-neutral-500 dark:text-neutral-400">{selectedEndpoint.description}</p>
+ )}
+ </div>
+
+ {/* Method + Path + Try it button */}
+ <div className="flex items-center gap-2 p-1 border border-neutral-100 rounded-[8px] dark:border-neutral-800">
+ <div className="flex items-center gap-2 border border-neutral-100 dark:border-neutral-800 rounded-[6px] p-1 flex-1">
+ {/* Method Badge */}
+ <span className={`shrink-0 px-1.5 py-1 text-xs font-bold rounded ${methodColors[selectedEndpoint.method]}`}>
+ {selectedEndpoint.method}
+ </span>
+
+ {/* Path */}
+ <div className="flex-1 min-w-0 text-sm text-neutral-900 dark:text-neutral-100 font-mono truncate">
+ {formatPath(selectedEndpoint.path)}
+ </div>
+ </div>
+
+ {/* Try it button */}
+ <button
+ onClick={handleExecute}
+ disabled={isLoading}
+ className="flex items-center gap-1.5 px-3 py-1.5 bg-emerald-500 hover:bg-emerald-600 disabled:bg-emerald-400 text-white text-sm font-medium rounded-lg transition-colors shrink-0"
+ >
+ {isLoading ? (
+ <Loader2 className="h-4 w-4 animate-spin" />
+ ) : (
+ <>
+ Run
+ <Play className="h-3.5 w-3.5 fill-current" />
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+
+ {/* Path Parameters */}
+ {selectedEndpoint.pathParams && selectedEndpoint.pathParams.length > 0 && (
+ <div className="space-y-3">
+ <h3 className="text-xs font-medium text-neutral-500 dark:text-neutral-400 uppercase tracking-wider">
+ Path Parameters
+ </h3>
+ {selectedEndpoint.pathParams.map(param => {
+ const meta = parameterMetadata[param];
+ return (
+ <div key={param} className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
+ {meta?.label || param}
+ </label>
+ <Input
+ value={pathParams[param] || ""}
+ onChange={e => setPathParam(param, e.target.value)}
+ placeholder={meta?.placeholder || `Enter ${param}`}
+ className="h-8 text-xs"
+ type={meta?.type === "number" ? "number" : "text"}
+ />
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Common Parameters */}
+ {selectedEndpoint.hasCommonParams && (
+ <div className="space-y-3">
+ <h3 className="text-xs font-medium text-neutral-500 dark:text-neutral-400 uppercase tracking-wider">
+ Time Range
+ </h3>
+ <div className="grid grid-cols-2 gap-3">
+ <div className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">Start Date</label>
+ <Input
+ type="date"
+ value={startDate}
+ onChange={e => setStartDate(e.target.value)}
+ className="h-8 text-xs"
+ />
+ </div>
+ <div className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">End Date</label>
+ <Input type="date" value={endDate} onChange={e => setEndDate(e.target.value)} className="h-8 text-xs" />
+ </div>
+ </div>
+ <TimezoneSelect />
+ <FilterBuilder />
+ </div>
+ )}
+
+ {/* Endpoint-Specific Parameters */}
+ {selectedEndpoint.specificParams && selectedEndpoint.specificParams.length > 0 && (
+ <div className="space-y-3">
+ <h3 className="text-xs font-medium text-neutral-500 dark:text-neutral-400 uppercase tracking-wider">
+ {selectedEndpoint.hasCommonParams ? "Additional Parameters" : "Parameters"}
+ </h3>
+ {selectedEndpoint.specificParams.map(param => {
+ const meta = parameterMetadata[param];
+ const isRequired = selectedEndpoint.requiredParams?.includes(param);
+ if (!meta) {
+ return (
+ <div key={param} className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
+ {param}
+ {isRequired && <span className="text-red-500 ml-1">*</span>}
+ </label>
+ <Input
+ value={endpointParams[param] || ""}
+ onChange={e => setEndpointParam(param, e.target.value)}
+ placeholder={`Enter ${param}`}
+ className="h-8 text-xs"
+ />
+ </div>
+ );
+ }
+
+ if (meta.type === "select" && meta.options) {
+ return (
+ <div key={param} className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
+ {meta.label}
+ {isRequired && <span className="text-red-500 ml-1">*</span>}
+ </label>
+ <Select value={endpointParams[param] || ""} onValueChange={value => setEndpointParam(param, value)}>
+ <SelectTrigger className="h-8 text-xs">
+ <SelectValue placeholder={`Select ${meta.label}`} />
+ </SelectTrigger>
+ <SelectContent>
+ {meta.options.map(opt => (
+ <SelectItem key={opt} value={opt} className="text-xs">
+ {opt}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+ }
+
+ return (
+ <div key={param} className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">
+ {meta.label}
+ {isRequired && <span className="text-red-500 ml-1">*</span>}
+ </label>
+ <Input
+ type={meta.type === "number" ? "number" : "text"}
+ value={endpointParams[param] || ""}
+ onChange={e => setEndpointParam(param, e.target.value)}
+ placeholder={meta.placeholder || `Enter ${meta.label}`}
+ className="h-8 text-xs"
+ />
+ </div>
+ );
+ })}
+ </div>
+ )}
+
+ {/* Request Body */}
+ {selectedEndpoint.hasRequestBody && <RequestBodyEditor />}
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/RequestBodyEditor.tsx b/client/src/app/[site]/api-playground/components/RequestBodyEditor.tsx
new file mode 100644
index 000000000..21296c63c
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/RequestBodyEditor.tsx
@@ -0,0 +1,68 @@
+"use client";
+
+import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
+import { useState, useRef } from "react";
+import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
+import json from "react-syntax-highlighter/dist/esm/languages/hljs/json";
+import { vs2015, vs } from "react-syntax-highlighter/dist/esm/styles/hljs";
+import { useTheme } from "next-themes";
+
+SyntaxHighlighter.registerLanguage("json", json);
+
+export function RequestBodyEditor() {
+ const { requestBody, setRequestBody } = usePlaygroundStore();
+ const [error, setError] = useState<string | null>(null);
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
+ const { resolvedTheme } = useTheme();
+ const isDark = resolvedTheme === "dark";
+
+ const handleChange = (value: string) => {
+ setRequestBody(value);
+ if (value.trim() === "") {
+ setError(null);
+ return;
+ }
+ try {
+ JSON.parse(value);
+ setError(null);
+ } catch {
+ setError("Invalid JSON");
+ }
+ };
+
+ return (
+ <div className="space-y-1">
+ <div className="flex items-center justify-between">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">Request Body (JSON)</label>
+ {error && <span className="text-xs text-red-500">{error}</span>}
+ </div>
+ <div
+ className="relative min-h-[120px] rounded border border-neutral-150 dark:border-neutral-800 overflow-hidden"
+ onClick={() => textareaRef.current?.focus()}
+ >
+ <SyntaxHighlighter
+ language="json"
+ style={isDark ? vs2015 : vs}
+ customStyle={{
+ margin: 0,
+ padding: "10px",
+ fontSize: "12px",
+ minHeight: "120px",
+ background: "transparent",
+ }}
+ wrapLongLines
+ >
+ {requestBody || " "}
+ </SyntaxHighlighter>
+ <textarea
+ ref={textareaRef}
+ value={requestBody}
+ onChange={e => handleChange(e.target.value)}
+ placeholder='{"key": "value"}'
+ className="absolute inset-0 w-full h-full resize-none bg-transparent text-transparent caret-black dark:caret-white p-[10px] font-mono text-xs outline-none placeholder:text-neutral-500"
+ spellCheck={false}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/ResponsePanel.tsx b/client/src/app/[site]/api-playground/components/ResponsePanel.tsx
new file mode 100644
index 000000000..c54f2355e
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/ResponsePanel.tsx
@@ -0,0 +1,147 @@
+"use client";
+
+import { CodeSnippet } from "@/components/CodeSnippet";
+import { XCircle } from "lucide-react";
+import { useParams } from "next/navigation";
+import { useMemo } from "react";
+import { usePlaygroundStore } from "../hooks/usePlaygroundStore";
+import { CodeGenConfig } from "../utils/codeGenerators";
+import { CodeExamples } from "./CodeExamples";
+import { BACKEND_URL } from "../../../../lib/const";
+
+export function ResponsePanel() {
+ const params = useParams();
+ const siteId = params.site as string;
+
+ const {
+ selectedEndpoint,
+ startDate,
+ endDate,
+ timeZone,
+ filters,
+ endpointParams,
+ pathParams,
+ requestBody,
+ response,
+ responseError,
+ responseTime,
+ } = usePlaygroundStore();
+
+ // Build the full URL and query params for code generation
+ const { queryParams, parsedBody } = useMemo(() => {
+ if (!selectedEndpoint) {
+ return { queryParams: {}, parsedBody: undefined };
+ }
+
+ // Build query params
+ const qp: Record<string, any> = {};
+
+ if (selectedEndpoint.hasCommonParams) {
+ qp.start_date = startDate;
+ qp.end_date = endDate;
+ qp.time_zone = timeZone;
+
+ // Convert filters to API format inline
+ const apiFilters = filters
+ .filter(f => f.value.trim() !== "")
+ .map(f => ({
+ parameter: f.parameter,
+ type: f.operator,
+ value: [f.value],
+ }));
+ if (apiFilters.length > 0) {
+ qp.filters = JSON.stringify(apiFilters);
+ }
+ }
+
+ // Add endpoint-specific params
+ if (selectedEndpoint.specificParams) {
+ for (const param of selectedEndpoint.specificParams) {
+ if (endpointParams[param]) {
+ qp[param] = endpointParams[param];
+ }
+ }
+ }
+
+ // Parse request body
+ let body: any;
+ if (selectedEndpoint.hasRequestBody && requestBody) {
+ try {
+ body = JSON.parse(requestBody);
+ } catch {
+ // Invalid JSON, will be handled during request
+ }
+ }
+
+ return { queryParams: qp, parsedBody: body };
+ }, [selectedEndpoint, startDate, endDate, timeZone, filters, endpointParams, requestBody]);
+
+ // Code generation config
+ const codeConfig: CodeGenConfig = useMemo(() => {
+ if (!selectedEndpoint) {
+ return {
+ method: "GET",
+ url: "",
+ queryParams: {},
+ };
+ }
+
+ let path = selectedEndpoint.path.replace(":site", siteId);
+ if (selectedEndpoint.pathParams) {
+ for (const param of selectedEndpoint.pathParams) {
+ path = path.replace(`:${param}`, pathParams[param] || `{${param}}`);
+ }
+ }
+
+ return {
+ method: selectedEndpoint.method,
+ url: `${BACKEND_URL}${path}`,
+ queryParams,
+ body: parsedBody,
+ };
+ }, [selectedEndpoint, siteId, pathParams, queryParams, parsedBody]);
+
+ if (!selectedEndpoint) {
+ return (
+ <div className="h-full flex items-center justify-center text-neutral-500 dark:text-neutral-400 p-4">
+ <p className="text-sm text-center">Select an endpoint to see the request URL and code examples</p>
+ </div>
+ );
+ }
+
+ return (
+ <div className="h-full overflow-y-auto overflow-x-hidden p-4 space-y-4 min-w-0">
+ {/* Code Examples */}
+ <CodeExamples config={codeConfig} />
+
+ {/* Response */}
+ <div className="space-y-2">
+ <div className="flex items-center justify-between">
+ <h3 className="text-xs font-medium text-neutral-500 dark:text-neutral-400 uppercase tracking-wider">
+ Response
+ </h3>
+ {responseTime !== null && (
+ <span className="text-xs text-neutral-500 dark:text-neutral-400">{responseTime}ms</span>
+ )}
+ </div>
+
+ {responseError ? (
+ <div className="p-3 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded">
+ <div className="flex items-start gap-2">
+ <XCircle className="h-4 w-4 text-red-500 mt-0.5 shrink-0" />
+ <p className="text-sm text-red-700 dark:text-red-300">{responseError}</p>
+ </div>
+ </div>
+ ) : response ? (
+ <div className="max-h-[400px] overflow-auto rounded-lg">
+ <CodeSnippet code={JSON.stringify(response, null, 2)} language="json" />
+ </div>
+ ) : (
+ <div className="p-3 bg-neutral-100 dark:bg-neutral-800 rounded text-xs text-neutral-500 dark:text-neutral-400">
+ Click &quot;Execute Request&quot; to see the response
+ </div>
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/components/TimezoneSelect.tsx b/client/src/app/[site]/api-playground/components/TimezoneSelect.tsx
new file mode 100644
index 000000000..334829b87
--- /dev/null
+++ b/client/src/app/[site]/api-playground/components/TimezoneSelect.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
+import { commonTimezones, usePlaygroundStore } from "../hooks/usePlaygroundStore";
+
+export function TimezoneSelect() {
+ const { timeZone, setTimeZone } = usePlaygroundStore();
+
+ return (
+ <div className="space-y-1">
+ <label className="text-sm font-medium text-neutral-700 dark:text-neutral-300">Time Zone</label>
+ <Select value={timeZone} onValueChange={setTimeZone}>
+ <SelectTrigger className="h-8 text-xs">
+ <SelectValue placeholder="Select timezone" />
+ </SelectTrigger>
+ <SelectContent>
+ {commonTimezones.map(tz => (
+ <SelectItem key={tz.value} value={tz.value} className="text-xs">
+ {tz.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts b/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts
new file mode 100644
index 000000000..b1cea51dd
--- /dev/null
+++ b/client/src/app/[site]/api-playground/hooks/usePlaygroundStore.ts
@@ -0,0 +1,235 @@
+import { Filter } from "@rybbit/shared";
+import { DateTime } from "luxon";
+import { create } from "zustand";
+import { EndpointConfig } from "../utils/endpointConfig";
+
+interface PlaygroundFilter {
+ parameter: string;
+ operator: string;
+ value: string;
+}
+
+interface PlaygroundState {
+ // Selected endpoint
+ selectedEndpoint: EndpointConfig | null;
+ setSelectedEndpoint: (endpoint: EndpointConfig | null) => void;
+
+ // Common parameters (independent from store.ts)
+ startDate: string;
+ endDate: string;
+ timeZone: string;
+ setStartDate: (date: string) => void;
+ setEndDate: (date: string) => void;
+ setTimeZone: (tz: string) => void;
+
+ // Filters
+ filters: PlaygroundFilter[];
+ addFilter: () => void;
+ updateFilter: (index: number, filter: PlaygroundFilter) => void;
+ removeFilter: (index: number) => void;
+ clearFilters: () => void;
+
+ // Convert playground filters to API format
+ getApiFilters: () => Filter[];
+
+ // Endpoint-specific params (dynamic)
+ endpointParams: Record<string, string>;
+ setEndpointParam: (key: string, value: string) => void;
+ clearEndpointParams: () => void;
+
+ // Path params (e.g., sessionId, goalId)
+ pathParams: Record<string, string>;
+ setPathParam: (key: string, value: string) => void;
+ clearPathParams: () => void;
+
+ // Request body for POST/PUT
+ requestBody: string;
+ setRequestBody: (body: string) => void;
+
+ // Response state
+ response: any;
+ responseError: string | null;
+ isLoading: boolean;
+ responseTime: number | null;
+ setResponse: (response: any, time: number) => void;
+ setResponseError: (error: string) => void;
+ setIsLoading: (loading: boolean) => void;
+ clearResponse: () => void;
+
+ // Reset all state
+ reset: () => void;
+}
+
+// Get browser timezone or default to UTC
+const getDefaultTimezone = () => {
+ if (typeof window !== "undefined") {
+ return Intl.DateTimeFormat().resolvedOptions().timeZone;
+ }
+ return "UTC";
+};
+
+// Get today's date in YYYY-MM-DD format
+const getToday = () => DateTime.now().toISODate() ?? "";
+
+export const usePlaygroundStore = create<PlaygroundState>((set, get) => ({
+ // Selected endpoint
+ selectedEndpoint: null,
+ setSelectedEndpoint: (endpoint) =>
+ set({
+ selectedEndpoint: endpoint,
+ endpointParams: {},
+ pathParams: {},
+ requestBody: endpoint?.requestBodyExample
+ ? JSON.stringify(endpoint.requestBodyExample, null, 2)
+ : "",
+ response: null,
+ responseError: null,
+ responseTime: null,
+ }),
+
+ // Common parameters
+ startDate: getToday(),
+ endDate: getToday(),
+ timeZone: getDefaultTimezone(),
+ setStartDate: (date) => set({ startDate: date }),
+ setEndDate: (date) => set({ endDate: date }),
+ setTimeZone: (tz) => set({ timeZone: tz }),
+
+ // Filters
+ filters: [],
+ addFilter: () =>
+ set((state) => ({
+ filters: [
+ ...state.filters,
+ { parameter: "country", operator: "equals", value: "" },
+ ],
+ })),
+ updateFilter: (index, filter) =>
+ set((state) => ({
+ filters: state.filters.map((f, i) => (i === index ? filter : f)),
+ })),
+ removeFilter: (index) =>
+ set((state) => ({
+ filters: state.filters.filter((_, i) => i !== index),
+ })),
+ clearFilters: () => set({ filters: [] }),
+
+ getApiFilters: () => {
+ const { filters } = get();
+ return filters
+ .filter((f) => f.value.trim() !== "")
+ .map((f) => ({
+ parameter: f.parameter as Filter["parameter"],
+ type: f.operator as Filter["type"],
+ value: [f.value] as (string | number)[],
+ }));
+ },
+
+ // Endpoint params
+ endpointParams: {},
+ setEndpointParam: (key, value) =>
+ set((state) => ({
+ endpointParams: { ...state.endpointParams, [key]: value },
+ })),
+ clearEndpointParams: () => set({ endpointParams: {} }),
+
+ // Path params
+ pathParams: {},
+ setPathParam: (key, value) =>
+ set((state) => ({
+ pathParams: { ...state.pathParams, [key]: value },
+ })),
+ clearPathParams: () => set({ pathParams: {} }),
+
+ // Request body
+ requestBody: "",
+ setRequestBody: (body) => set({ requestBody: body }),
+
+ // Response
+ response: null,
+ responseError: null,
+ isLoading: false,
+ responseTime: null,
+ setResponse: (response, time) =>
+ set({
+ response,
+ responseTime: time,
+ responseError: null,
+ isLoading: false,
+ }),
+ setResponseError: (error) =>
+ set({
+ responseError: error,
+ response: null,
+ isLoading: false,
+ }),
+ setIsLoading: (loading) => set({ isLoading: loading }),
+ clearResponse: () =>
+ set({ response: null, responseError: null, responseTime: null }),
+
+ // Reset
+ reset: () =>
+ set({
+ selectedEndpoint: null,
+ startDate: getToday(),
+ endDate: getToday(),
+ timeZone: getDefaultTimezone(),
+ filters: [],
+ endpointParams: {},
+ pathParams: {},
+ requestBody: "",
+ response: null,
+ responseError: null,
+ isLoading: false,
+ responseTime: null,
+ }),
+}));
+
+// Filter parameter options (hardcoded, no dynamic fetching)
+export const filterParameters = [
+ { value: "country", label: "Country" },
+ { value: "region", label: "Region" },
+ { value: "city", label: "City" },
+ { value: "browser", label: "Browser" },
+ { value: "operating_system", label: "Operating System" },
+ { value: "device_type", label: "Device Type" },
+ { value: "pathname", label: "Path" },
+ { value: "referrer", label: "Referrer" },
+ { value: "utm_source", label: "UTM Source" },
+ { value: "utm_medium", label: "UTM Medium" },
+ { value: "utm_campaign", label: "UTM Campaign" },
+ { value: "channel", label: "Channel" },
+ { value: "entry_page", label: "Entry Page" },
+ { value: "exit_page", label: "Exit Page" },
+ { value: "language", label: "Language" },
+];
+
+export const filterOperators = [
+ { value: "equals", label: "Equals" },
+ { value: "not_equals", label: "Not Equals" },
+ { value: "contains", label: "Contains" },
+ { value: "not_contains", label: "Not Contains" },
+ { value: "regex", label: "Regex" },
+];
+
+// Common timezones for the dropdown
+export const commonTimezones = [
+ { value: "UTC", label: "UTC" },
+ { value: "America/New_York", label: "Eastern Time (US)" },
+ { value: "America/Chicago", label: "Central Time (US)" },
+ { value: "America/Denver", label: "Mountain Time (US)" },
+ { value: "America/Los_Angeles", label: "Pacific Time (US)" },
+ { value: "America/Anchorage", label: "Alaska Time" },
+ { value: "Pacific/Honolulu", label: "Hawaii Time" },
+ { value: "Europe/London", label: "London" },
+ { value: "Europe/Paris", label: "Paris" },
+ { value: "Europe/Berlin", label: "Berlin" },
+ { value: "Europe/Moscow", label: "Moscow" },
+ { value: "Asia/Dubai", label: "Dubai" },
+ { value: "Asia/Kolkata", label: "India (IST)" },
+ { value: "Asia/Singapore", label: "Singapore" },
+ { value: "Asia/Tokyo", label: "Tokyo" },
+ { value: "Asia/Shanghai", label: "Shanghai" },
+ { value: "Australia/Sydney", label: "Sydney" },
+ { value: "Pacific/Auckland", label: "Auckland" },
+];
diff --git a/client/src/app/[site]/api-playground/page.tsx b/client/src/app/[site]/api-playground/page.tsx
new file mode 100644
index 000000000..ec9dafe1d
--- /dev/null
+++ b/client/src/app/[site]/api-playground/page.tsx
@@ -0,0 +1,26 @@
+"use client";
+
+import Link from "next/link";
+import { ApiPlayground } from "./components/ApiPlayground";
+
+export default function ApiPlaygroundPage() {
+ return (
+ <div className="p-4">
+ <div className="mb-4">
+ <h1 className="text-xl font-semibold text-neutral-900 dark:text-neutral-100">
+ API Playground
+ </h1>
+ <p className="text-sm text-neutral-500 dark:text-neutral-400 mt-1">
+ Test API endpoints and view code examples in multiple languages.{" "}
+ <Link
+ href="/settings/account"
+ className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
+ >
+ Get your API key
+ </Link>
+ </p>
+ </div>
+ <ApiPlayground />
+ </div>
+ );
+}
diff --git a/client/src/app/[site]/api-playground/utils/codeGenerators.ts b/client/src/app/[site]/api-playground/utils/codeGenerators.ts
new file mode 100644
index 000000000..f0c73b976
--- /dev/null
+++ b/client/src/app/[site]/api-playground/utils/codeGenerators.ts
@@ -0,0 +1,349 @@
+import { HttpMethod } from "./endpointConfig";
+
+export interface CodeGenConfig {
+ method: HttpMethod;
+ url: string;
+ queryParams: Record<string, any>;
+ body?: any;
+ apiKey?: string;
+}
+
+function buildQueryString(params: Record<string, any>): string {
+ const filtered = Object.entries(params).filter(
+ ([, v]) => v !== undefined && v !== null && v !== ""
+ );
+ if (filtered.length === 0) return "";
+ return (
+ "?" +
+ filtered
+ .map(([k, v]) => {
+ // For arrays and plain objects, JSON.stringify before encoding
+ const value =
+ Array.isArray(v) || (typeof v === "object" && v !== null)
+ ? JSON.stringify(v)
+ : String(v);
+ return `${encodeURIComponent(k)}=${encodeURIComponent(value)}`;
+ })
+ .join("&")
+ );
+}
+
+function formatJsonForCode(obj: any, indent: number = 2): string {
+ return JSON.stringify(obj, null, indent);
+}
+
+export function generateCurl(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ let curl = `curl -X ${method} "${fullUrl}" \\
+ -H "Authorization: Bearer ${apiKey}"`;
+
+ if (body && (method === "POST" || method === "PUT")) {
+ curl += ` \\
+ -H "Content-Type: application/json" \\
+ -d '${formatJsonForCode(body)}'`;
+ }
+
+ return curl;
+}
+
+export function generateJavaScript(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET" || !body) {
+ return `const response = await fetch(
+ '${fullUrl}',
+ {
+ headers: {
+ 'Authorization': 'Bearer ${apiKey}'
+ }
+ }
+);
+
+const data = await response.json();`;
+ }
+
+ return `const response = await fetch(
+ '${fullUrl}',
+ {
+ method: '${method}',
+ headers: {
+ 'Authorization': 'Bearer ${apiKey}',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify(${formatJsonForCode(body, 4)})
+ }
+);
+
+const data = await response.json();`;
+}
+
+export function generatePython(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+
+ const paramsStr =
+ Object.keys(queryParams).length > 0
+ ? `\n params=${formatJsonForCode(queryParams, 8)},`
+ : "";
+
+ if (method === "GET") {
+ return `import requests
+
+response = requests.get(
+ '${url}',${paramsStr}
+ headers={
+ 'Authorization': 'Bearer ${apiKey}'
+ }
+)
+
+data = response.json()`;
+ }
+
+ const methodLower = method.toLowerCase();
+ const bodyStr = body ? `\n json=${formatJsonForCode(body, 8)},` : "";
+
+ return `import requests
+
+response = requests.${methodLower}(
+ '${url}',${paramsStr}${bodyStr}
+ headers={
+ 'Authorization': 'Bearer ${apiKey}'
+ }
+)
+
+data = response.json()`;
+}
+
+export function generatePHP(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET" || !body) {
+ return `$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, '${fullUrl}');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer ${apiKey}'
+]);
+
+$response = curl_exec($ch);
+curl_close($ch);
+
+$data = json_decode($response, true);`;
+ }
+
+ // Escape for PHP single-quoted string: backslashes first, then single quotes
+ const escapedBody = formatJsonForCode(body)
+ .replace(/\\/g, "\\\\")
+ .replace(/'/g, "\\'");
+
+ return `$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, '${fullUrl}');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, '${method}');
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer ${apiKey}',
+ 'Content-Type: application/json'
+]);
+curl_setopt($ch, CURLOPT_POSTFIELDS, '${escapedBody}');
+
+$response = curl_exec($ch);
+curl_close($ch);
+
+$data = json_decode($response, true);`;
+}
+
+export function generateRuby(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET" || !body) {
+ return `require 'net/http'
+require 'json'
+
+uri = URI('${fullUrl}')
+req = Net::HTTP::Get.new(uri)
+req['Authorization'] = 'Bearer ${apiKey}'
+
+res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
+data = JSON.parse(res.body)`;
+ }
+
+ const reqClass = method === "POST" ? "Post" : method === "PUT" ? "Put" : "Delete";
+ return `require 'net/http'
+require 'json'
+
+uri = URI('${fullUrl}')
+req = Net::HTTP::${reqClass}.new(uri)
+req['Authorization'] = 'Bearer ${apiKey}'
+req['Content-Type'] = 'application/json'
+req.body = ${formatJsonForCode(body)}.to_json
+
+res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
+data = JSON.parse(res.body)`;
+}
+
+export function generateGo(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET" || !body) {
+ return `req, _ := http.NewRequest("${method}", "${fullUrl}", nil)
+req.Header.Set("Authorization", "Bearer ${apiKey}")
+
+client := &http.Client{}
+resp, _ := client.Do(req)
+defer resp.Body.Close()
+
+var data map[string]interface{}
+json.NewDecoder(resp.Body).Decode(&data)`;
+ }
+
+ return `payload := []byte(\`${formatJsonForCode(body)}\`)
+req, _ := http.NewRequest("${method}", "${fullUrl}", bytes.NewBuffer(payload))
+req.Header.Set("Authorization", "Bearer ${apiKey}")
+req.Header.Set("Content-Type", "application/json")
+
+client := &http.Client{}
+resp, _ := client.Do(req)
+defer resp.Body.Close()
+
+var data map[string]interface{}
+json.NewDecoder(resp.Body).Decode(&data)`;
+}
+
+export function generateRust(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+ const methodLower = method.toLowerCase();
+
+ if (method === "GET" || !body) {
+ return `let client = reqwest::Client::new();
+let res = client
+ .${methodLower}("${fullUrl}")
+ .header("Authorization", "Bearer ${apiKey}")
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;`;
+ }
+
+ return `let client = reqwest::Client::new();
+let res = client
+ .${methodLower}("${fullUrl}")
+ .header("Authorization", "Bearer ${apiKey}")
+ .json(&serde_json::json!(${formatJsonForCode(body)}))
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;`;
+}
+
+export function generateJava(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET" || !body) {
+ return `HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("${fullUrl}"))
+ .header("Authorization", "Bearer ${apiKey}")
+ .GET()
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());`;
+ }
+
+ return `HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("${fullUrl}"))
+ .header("Authorization", "Bearer ${apiKey}")
+ .header("Content-Type", "application/json")
+ .method("${method}", HttpRequest.BodyPublishers.ofString("${formatJsonForCode(body).replace(/"/g, '\\"')}"))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());`;
+}
+
+export function generateDotNet(config: CodeGenConfig): string {
+ const { method, url, queryParams, body, apiKey = "YOUR_API_KEY" } = config;
+ const queryString = buildQueryString(queryParams);
+ const fullUrl = `${url}${queryString}`;
+
+ if (method === "GET") {
+ return `using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer ${apiKey}");
+
+var response = await client.GetAsync("${fullUrl}");
+var data = await response.Content.ReadAsStringAsync();`;
+ }
+
+ if (!body) {
+ if (method === "DELETE") {
+ return `using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer ${apiKey}");
+
+var response = await client.DeleteAsync("${fullUrl}");
+var data = await response.Content.ReadAsStringAsync();`;
+ }
+ const methodName = method === "POST" ? "PostAsync" : "PutAsync";
+ return `using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer ${apiKey}");
+
+var response = await client.${methodName}("${fullUrl}", null);
+var data = await response.Content.ReadAsStringAsync();`;
+ }
+
+ const httpMethod = method === "POST" ? "Post" : method === "PUT" ? "Put" : "Delete";
+
+ return `using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer ${apiKey}");
+
+var content = new StringContent(
+ @"${formatJsonForCode(body).replace(/"/g, '""')}",
+ Encoding.UTF8,
+ "application/json"
+);
+
+var request = new HttpRequestMessage(HttpMethod.${httpMethod}, "${fullUrl}")
+{
+ Content = content
+};
+
+var response = await client.SendAsync(request);
+var data = await response.Content.ReadAsStringAsync();`;
+}
+
+// All generators mapped by language name
+export const codeGenerators: Record<string, (config: CodeGenConfig) => string> = {
+ cURL: generateCurl,
+ JavaScript: generateJavaScript,
+ Python: generatePython,
+ PHP: generatePHP,
+ Ruby: generateRuby,
+ Go: generateGo,
+ Rust: generateRust,
+ Java: generateJava,
+ ".NET": generateDotNet,
+};
+
+export const languageOrder = [
+ "cURL",
+ "JavaScript",
+ "Python",
+ "PHP",
+ "Ruby",
+ "Go",
+ "Rust",
+ "Java",
+ ".NET",
+];
diff --git a/client/src/app/[site]/api-playground/utils/endpointConfig.ts b/client/src/app/[site]/api-playground/utils/endpointConfig.ts
new file mode 100644
index 000000000..c7520283e
--- /dev/null
+++ b/client/src/app/[site]/api-playground/utils/endpointConfig.ts
@@ -0,0 +1,457 @@
+export type HttpMethod = "GET" | "POST" | "PUT" | "DELETE";
+
+export interface EndpointConfig {
+ method: HttpMethod;
+ path: string;
+ name: string;
+ description?: string;
+ hasCommonParams: boolean;
+ specificParams?: string[];
+ requiredParams?: string[];
+ pathParams?: string[];
+ hasRequestBody?: boolean;
+ requestBodyExample?: object;
+}
+
+export interface EndpointCategory {
+ name: string;
+ endpoints: EndpointConfig[];
+}
+
+export const endpointCategories: EndpointCategory[] = [
+ {
+ name: "Overview",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/overview/:site",
+ name: "Get Overview",
+ description: "Returns high-level analytics metrics for a site",
+ hasCommonParams: true,
+ },
+ {
+ method: "GET",
+ path: "/overview-bucketed/:site",
+ name: "Get Overview (Time Series)",
+ description: "Returns time-series analytics data broken down by time buckets",
+ hasCommonParams: true,
+ specificParams: ["bucket"],
+ },
+ {
+ method: "GET",
+ path: "/metric/:site",
+ name: "Get Metric",
+ description: "Returns dimensional analytics broken down by a specific parameter",
+ hasCommonParams: true,
+ specificParams: ["parameter", "limit", "page"],
+ requiredParams: ["parameter"],
+ },
+ {
+ method: "GET",
+ path: "/live-user-count/:site",
+ name: "Get Live Visitors",
+ description: "Returns the count of active sessions within the specified time window",
+ hasCommonParams: false,
+ specificParams: ["minutes"],
+ },
+ ],
+ },
+ {
+ name: "Events",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/events/:site",
+ name: "Get Events",
+ description: "Returns a paginated list of events",
+ hasCommonParams: true,
+ specificParams: ["page", "page_size"],
+ },
+ {
+ method: "GET",
+ path: "/events/names/:site",
+ name: "Get Event Names",
+ description: "Returns list of unique custom event names with counts",
+ hasCommonParams: true,
+ },
+ {
+ method: "GET",
+ path: "/events/properties/:site",
+ name: "Get Event Properties",
+ description: "Returns property key-value pairs for a specific event",
+ hasCommonParams: true,
+ specificParams: ["event_name"],
+ requiredParams: ["event_name"],
+ },
+ {
+ method: "GET",
+ path: "/events/outbound/:site",
+ name: "Get Outbound Links",
+ description: "Returns outbound link clicks with occurrence counts",
+ hasCommonParams: true,
+ },
+ ],
+ },
+ {
+ name: "Errors",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/error-names/:site",
+ name: "Get Error Names",
+ description: "Returns unique error messages with occurrence and session counts",
+ hasCommonParams: true,
+ specificParams: ["page", "limit"],
+ },
+ {
+ method: "GET",
+ path: "/error-events/:site",
+ name: "Get Error Events",
+ description: "Returns individual error occurrences with context and stack traces",
+ hasCommonParams: true,
+ requiredParams: ["errorMessage"],
+ specificParams: ["errorMessage", "page", "limit"],
+ },
+ {
+ method: "GET",
+ path: "/error-bucketed/:site",
+ name: "Get Error Time Series",
+ description: "Returns error occurrence counts over time",
+ hasCommonParams: true,
+ requiredParams: ["errorMessage"],
+ specificParams: ["errorMessage", "bucket"],
+ },
+ ],
+ },
+ {
+ name: "Goals",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/goals/:site",
+ name: "Get Goals",
+ description: "Returns paginated list of goals with conversion metrics",
+ hasCommonParams: true,
+ specificParams: ["page", "page_size", "sort", "order"],
+ },
+ {
+ method: "GET",
+ path: "/goals/:goalId/sessions/:site",
+ name: "Get Goal Sessions",
+ description: "Returns sessions that completed a specific goal",
+ hasCommonParams: true,
+ pathParams: ["goalId"],
+ specificParams: ["page", "limit"],
+ },
+ {
+ method: "POST",
+ path: "/goals/:site",
+ name: "Create Goal",
+ description: "Creates a new goal",
+ hasCommonParams: false,
+ hasRequestBody: true,
+ requestBodyExample: {
+ name: "My Goal",
+ goalType: "path",
+ config: {
+ pathPattern: "/checkout/success",
+ },
+ },
+ },
+ {
+ method: "PUT",
+ path: "/goals/:goalId/:site",
+ name: "Update Goal",
+ description: "Updates an existing goal",
+ hasCommonParams: false,
+ pathParams: ["goalId"],
+ hasRequestBody: true,
+ requestBodyExample: {
+ name: "Updated Goal",
+ goalType: "event",
+ config: {
+ eventName: "purchase",
+ },
+ },
+ },
+ {
+ method: "DELETE",
+ path: "/goals/:goalId/:site",
+ name: "Delete Goal",
+ description: "Deletes a goal",
+ hasCommonParams: false,
+ pathParams: ["goalId"],
+ },
+ ],
+ },
+ {
+ name: "Funnels",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/funnels/:site",
+ name: "Get Funnels",
+ description: "Returns all saved funnels for a site",
+ hasCommonParams: false,
+ },
+ {
+ method: "POST",
+ path: "/funnels/analyze/:site",
+ name: "Analyze Funnel",
+ description: "Analyzes funnel conversion data step-by-step",
+ hasCommonParams: true,
+ hasRequestBody: true,
+ requestBodyExample: {
+ steps: [
+ { type: "page", value: "/", name: "Homepage" },
+ { type: "page", value: "/pricing", name: "Pricing" },
+ { type: "page", value: "/signup", name: "Signup" },
+ ],
+ },
+ },
+ {
+ method: "POST",
+ path: "/funnels/:stepNumber/sessions/:site",
+ name: "Get Funnel Step Sessions",
+ description: "Returns sessions that reached or dropped at a specific funnel step",
+ hasCommonParams: true,
+ pathParams: ["stepNumber"],
+ specificParams: ["mode", "page", "limit"],
+ hasRequestBody: true,
+ requestBodyExample: {
+ steps: [
+ { type: "page", value: "/", name: "Homepage" },
+ { type: "page", value: "/pricing", name: "Pricing" },
+ ],
+ },
+ },
+ {
+ method: "POST",
+ path: "/funnels/:site",
+ name: "Create Funnel",
+ description: "Creates a saved funnel",
+ hasCommonParams: false,
+ hasRequestBody: true,
+ requestBodyExample: {
+ name: "Conversion Funnel",
+ steps: [
+ { type: "page", value: "/", name: "Homepage" },
+ { type: "page", value: "/signup", name: "Signup" },
+ ],
+ },
+ },
+ {
+ method: "DELETE",
+ path: "/funnels/:funnelId/:site",
+ name: "Delete Funnel",
+ description: "Deletes a saved funnel",
+ hasCommonParams: false,
+ pathParams: ["funnelId"],
+ },
+ ],
+ },
+ {
+ name: "Performance",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/performance/overview/:site",
+ name: "Get Performance Overview",
+ description: "Returns aggregate Core Web Vitals metrics",
+ hasCommonParams: true,
+ },
+ {
+ method: "GET",
+ path: "/performance/time-series/:site",
+ name: "Get Performance Time Series",
+ description: "Returns performance metrics over time",
+ hasCommonParams: true,
+ specificParams: ["bucket"],
+ },
+ {
+ method: "GET",
+ path: "/performance/by-dimension/:site",
+ name: "Get Performance by Dimension",
+ description: "Returns performance breakdown by dimension",
+ hasCommonParams: true,
+ requiredParams: ["dimension"],
+ specificParams: ["dimension", "page", "limit", "sort_by", "sort_order"],
+ },
+ ],
+ },
+ {
+ name: "Sessions",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/sessions/:site",
+ name: "Get Sessions",
+ description: "Returns a paginated list of sessions",
+ hasCommonParams: true,
+ specificParams: ["page", "limit", "user_id", "identified_only"],
+ },
+ {
+ method: "GET",
+ path: "/sessions/:sessionId/:site",
+ name: "Get Session",
+ description: "Returns detailed session information with events",
+ hasCommonParams: false,
+ pathParams: ["sessionId"],
+ specificParams: ["limit", "offset"],
+ },
+ {
+ method: "GET",
+ path: "/session-locations/:site",
+ name: "Get Session Locations",
+ description: "Returns aggregated session locations for map visualization",
+ hasCommonParams: true,
+ },
+ ],
+ },
+ {
+ name: "Users",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/users/:site",
+ name: "Get Users",
+ description: "Returns a paginated list of users",
+ hasCommonParams: true,
+ specificParams: ["page", "page_size", "sort_by", "sort_order", "identified_only"],
+ },
+ {
+ method: "GET",
+ path: "/users/session-count/:site",
+ name: "Get User Session Count",
+ description: "Returns daily session counts for a specific user",
+ hasCommonParams: false,
+ specificParams: ["user_id", "time_zone"],
+ },
+ {
+ method: "GET",
+ path: "/users/:userId/:site",
+ name: "Get User Info",
+ description: "Returns detailed user profile information",
+ hasCommonParams: false,
+ pathParams: ["userId"],
+ },
+ ],
+ },
+ {
+ name: "Misc",
+ endpoints: [
+ {
+ method: "GET",
+ path: "/retention/:site",
+ name: "Get Retention",
+ description: "Returns cohort-based retention analysis",
+ hasCommonParams: false,
+ specificParams: ["mode", "range"],
+ },
+ {
+ method: "GET",
+ path: "/journeys/:site",
+ name: "Get Journeys",
+ description: "Returns most common page navigation paths",
+ hasCommonParams: true,
+ specificParams: ["steps", "limit"],
+ },
+ ],
+ },
+];
+
+// Flatten all endpoints for easy lookup
+export const allEndpoints: EndpointConfig[] = endpointCategories.flatMap(cat => cat.endpoints);
+
+// Parameter metadata for dynamic form generation
+export const parameterMetadata: Record<
+ string,
+ { label: string; type: "text" | "number" | "select"; options?: string[]; placeholder?: string }
+> = {
+ bucket: {
+ label: "Bucket",
+ type: "select",
+ options: ["minute", "five_minutes", "ten_minutes", "fifteen_minutes", "hour", "day", "week", "month", "year"],
+ },
+ parameter: {
+ label: "Parameter",
+ type: "select",
+ options: [
+ "pathname",
+ "page_title",
+ "country",
+ "region",
+ "city",
+ "browser",
+ "operating_system",
+ "device_type",
+ "referrer",
+ "channel",
+ "utm_source",
+ "utm_medium",
+ "utm_campaign",
+ "utm_term",
+ "utm_content",
+ "language",
+ "entry_page",
+ "exit_page",
+ "event_name",
+ ],
+ },
+ dimension: {
+ label: "Dimension",
+ type: "select",
+ options: ["pathname", "country", "browser", "operating_system", "device_type"],
+ },
+ mode: {
+ label: "Mode",
+ type: "select",
+ options: ["day", "week", "reached", "dropped"],
+ },
+ sort: {
+ label: "Sort By",
+ type: "select",
+ options: ["goalId", "name", "goalType", "createdAt"],
+ },
+ sort_by: {
+ label: "Sort By",
+ type: "select",
+ options: ["first_seen", "last_seen", "pageviews", "sessions", "events"],
+ },
+ sort_order: {
+ label: "Sort Order",
+ type: "select",
+ options: ["asc", "desc"],
+ },
+ order: {
+ label: "Order",
+ type: "select",
+ options: ["asc", "desc"],
+ },
+ page: { label: "Page", type: "number", placeholder: "1" },
+ limit: { label: "Limit", type: "number", placeholder: "10" },
+ page_size: { label: "Page Size", type: "number", placeholder: "10" },
+ minutes: { label: "Minutes", type: "number", placeholder: "5" },
+ steps: { label: "Steps", type: "number", placeholder: "3" },
+ range: { label: "Range (days)", type: "number", placeholder: "90" },
+ offset: { label: "Offset", type: "number", placeholder: "0" },
+ event_name: { label: "Event Name", type: "text", placeholder: "e.g., purchase" },
+ errorMessage: { label: "Error Message", type: "text", placeholder: "Error message to filter by" },
+ user_id: { label: "User ID", type: "text", placeholder: "User ID" },
+ time_zone: { label: "Time Zone", type: "text", placeholder: "America/New_York" },
+ identified_only: { label: "Identified Only", type: "select", options: ["true", "false"] },
+ // Path params
+ goalId: { label: "Goal ID", type: "number", placeholder: "Goal ID" },
+ funnelId: { label: "Funnel ID", type: "number", placeholder: "Funnel ID" },
+ sessionId: { label: "Session ID", type: "text", placeholder: "Session ID" },
+ userId: { label: "User ID", type: "text", placeholder: "User ID" },
+ stepNumber: { label: "Step Number", type: "number", placeholder: "Step number (1-indexed)" },
+};
+
+// Method colors for UI
+export const methodColors: Record<HttpMethod, string> = {
+ GET: "bg-green-500/20 text-green-600 dark:text-green-400",
+ POST: "bg-blue-500/20 text-blue-600 dark:text-blue-400",
+ PUT: "bg-yellow-500/20 text-yellow-600 dark:text-yellow-400",
+ DELETE: "bg-red-500/20 text-red-600 dark:text-red-400",
+};
diff --git a/client/src/app/[site]/components/Sidebar/Sidebar.tsx b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
index 6cfe8144f..9a005c17c 100644
--- a/client/src/app/[site]/components/Sidebar/Sidebar.tsx
+++ b/client/src/app/[site]/components/Sidebar/Sidebar.tsx
@@ -2,6 +2,7 @@
import {
AlertTriangle,
ChartColumnDecreasing,
+ Code,
File,
Funnel,
Gauge,
@@ -104,6 +105,14 @@ function SidebarContent() {
href={getTabPath("goals")}
icon={<Target className="w-4 h-4" />}
/>
+ <div className="hidden md:block">
+ <SidebarComponents.Item
+ label="API Playground"
+ active={isActiveTab("api-playground")}
+ href={getTabPath("api-playground")}
+ icon={<Code className="w-4 h-4" />}
+ />
+ </div>
<SidebarComponents.SectionHeader>Product Analytics</SidebarComponents.SectionHeader>
<div className="hidden md:block">
{!subscription?.planName?.startsWith("appsumo") && !isSubscriptionLoading && (
diff --git a/client/src/app/[site]/components/SubHeader/Filters/ValueSelect.tsx b/client/src/app/[site]/components/SubHeader/Filters/ValueSelect.tsx
index 7eff51b84..d7e16721b 100644
--- a/client/src/app/[site]/components/SubHeader/Filters/ValueSelect.tsx
+++ b/client/src/app/[site]/components/SubHeader/Filters/ValueSelect.tsx
@@ -2,7 +2,7 @@
import { FilterParameter } from "@rybbit/shared";
import { useMemo } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { MultiSelect } from "../../../../../components/MultiSelect";
import { useGetRegionName } from "../../../../../lib/geo";
import { getCountryName, getLanguageName } from "../../../../../lib/utils";
diff --git a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
index f29a456bc..e250cfd4d 100644
--- a/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
+++ b/client/src/app/[site]/components/SubHeader/LiveUserCount.tsx
@@ -1,9 +1,9 @@
-import { useGetLiveUsercount } from "../../../../api/analytics/useGetLiveUserCount";
+import { useGetLiveUserCount } from "../../../../api/analytics/hooks/useGetLiveUserCount";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
import NumberFlow from "@number-flow/react";
export function LiveUserCount() {
- const { data } = useGetLiveUsercount(5);
+ const { data } = useGetLiveUserCount(5);
return (
<div className="flex items-center gap-1 text-base text-neutral-700 dark:text-neutral-200 mr-1">
diff --git a/client/src/app/[site]/components/shared/Map/MapComponent.tsx b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
index ad0ba630d..95c96057d 100644
--- a/client/src/app/[site]/components/shared/Map/MapComponent.tsx
+++ b/client/src/app/[site]/components/shared/Map/MapComponent.tsx
@@ -3,7 +3,7 @@
import { useMeasure } from "@uidotdev/usehooks";
import "ol/ol.css";
import { useEffect, useState } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { useCountries, useSubdivisions } from "../../../../../lib/geo";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
import { CountryFlag } from "../icons/CountryFlag";
@@ -123,7 +123,9 @@ export function MapComponent({ height, mapView: controlledMapView }: MapComponen
</div>
<div>
<span className="font-bold text-accent-400">{tooltipContent.count.toLocaleString()}</span>{" "}
- <span className="text-neutral-500 dark:text-neutral-300">({tooltipContent.percentage.toFixed(1)}%) sessions</span>
+ <span className="text-neutral-500 dark:text-neutral-300">
+ ({tooltipContent.percentage.toFixed(1)}%) sessions
+ </span>
</div>
</div>
</ChartTooltip>
diff --git a/client/src/app/[site]/components/shared/StandardSection/Row.tsx b/client/src/app/[site]/components/shared/StandardSection/Row.tsx
index 93efd5a52..c537e87fb 100644
--- a/client/src/app/[site]/components/shared/StandardSection/Row.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/Row.tsx
@@ -3,8 +3,8 @@ import NumberFlow from "@number-flow/react";
import { round } from "lodash";
import { ChevronDown, ChevronRight, SquareArrowOutUpRight } from "lucide-react";
import { ReactNode, useState, useCallback } from "react";
-import { usePaginatedMetric } from "../../../../../api/analytics/useGetMetric";
-import { MetricResponse } from "../../../../../api/analytics/useGetMetric";
+import { usePaginatedMetric } from "../../../../../api/analytics/hooks/useGetMetric";
+import { MetricResponse } from "../../../../../api/analytics/endpoints";
import { addFilter, removeFilter, useStore } from "../../../../../lib/store";
// Custom hook for filter handling logic
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
index 72c6e4845..c46ad0e5b 100644
--- a/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSection.tsx
@@ -4,7 +4,8 @@ import { Filter, FilterParameter } from "@rybbit/shared";
import { Info } from "lucide-react";
import Link from "next/link";
import { ReactNode } from "react";
-import { MetricResponse, usePaginatedMetric } from "../../../../../api/analytics/useGetMetric";
+import { usePaginatedMetric } from "../../../../../api/analytics/hooks/useGetMetric";
+import { MetricResponse } from "../../../../../api/analytics/endpoints";
import { ErrorState } from "../../../../../components/ErrorState";
import { CardLoader } from "../../../../../components/ui/card";
import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../../components/ui/tooltip";
diff --git a/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx b/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
index 0165ee0a3..d7cecf3f9 100644
--- a/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
+++ b/client/src/app/[site]/components/shared/StandardSection/StandardSectionDialog.tsx
@@ -15,7 +15,8 @@ import {
import { useDebounce, useIntersectionObserver } from "@uidotdev/usehooks";
import { Loader2, SquareArrowOutUpRight } from "lucide-react";
import { ReactNode, useEffect, useMemo, useState } from "react";
-import { MetricResponse, useInfiniteMetric } from "../../../../../api/analytics/useGetMetric";
+import { useInfiniteMetric } from "../../../../../api/analytics/hooks/useGetMetric";
+import { MetricResponse } from "../../../../../api/analytics/endpoints";
import { addFilter } from "../../../../../lib/store";
import { cn, formatSecondsAsMinutesAndSeconds } from "../../../../../lib/utils";
diff --git a/client/src/app/[site]/errors/components/ErrorDetails.tsx b/client/src/app/[site]/errors/components/ErrorDetails.tsx
index 9a5cf210d..42e52e2c9 100644
--- a/client/src/app/[site]/errors/components/ErrorDetails.tsx
+++ b/client/src/app/[site]/errors/components/ErrorDetails.tsx
@@ -1,6 +1,7 @@
"use client";
-import { ErrorEvent, useGetErrorEventsInfinite } from "@/api/analytics/errors/useGetErrorEvents";
+import { useGetErrorEventsInfinite } from "@/api/analytics/hooks/errors/useGetErrorEvents";
+import { ErrorEvent } from "@/api/analytics/endpoints";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { Skeleton } from "@/components/ui/skeleton";
diff --git a/client/src/app/[site]/errors/components/ErrorListItem.tsx b/client/src/app/[site]/errors/components/ErrorListItem.tsx
index 2c989e0f5..c2685629f 100644
--- a/client/src/app/[site]/errors/components/ErrorListItem.tsx
+++ b/client/src/app/[site]/errors/components/ErrorListItem.tsx
@@ -5,8 +5,8 @@ import { ChevronDown, ChevronRight } from "lucide-react";
import { useState } from "react";
import { ErrorDetails } from "./ErrorDetails";
import { ErrorSparklineChart } from "./ErrorSparklineChart";
-import { useGetErrorBucketed } from "@/api/analytics/errors/useGetErrorBucketed";
-import { ErrorNameItem } from "../../../../api/analytics/errors/useGetErrorNames";
+import { useGetErrorBucketed } from "@/api/analytics/hooks/errors/useGetErrorBucketed";
+import { ErrorNameItem } from "../../../../api/analytics/endpoints";
// Maximum length for error messages
const MAX_ERROR_MESSAGE_LENGTH = 150;
@@ -26,7 +26,6 @@ export function ErrorListItem({ errorData }: ErrorListItemProps) {
// Get error bucketed data for sparkline
const { data: errorBucketedData, isLoading: isLoadingBucketed } = useGetErrorBucketed({
errorMessage: errorData.value,
- enabled: true,
});
return (
diff --git a/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
index 5a511af2f..7069ec131 100644
--- a/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
+++ b/client/src/app/[site]/errors/components/ErrorSparklineChart.tsx
@@ -1,6 +1,6 @@
"use client";
-import { GetErrorBucketedResponse } from "@/api/analytics/errors/useGetErrorBucketed";
+import { GetErrorBucketedResponse } from "@/api/analytics/endpoints";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
import { useNivoTheme } from "@/lib/nivo";
import { ResponsiveBar } from "@nivo/bar";
diff --git a/client/src/app/[site]/errors/page.tsx b/client/src/app/[site]/errors/page.tsx
index 2075f5e2e..7bfbc18ca 100644
--- a/client/src/app/[site]/errors/page.tsx
+++ b/client/src/app/[site]/errors/page.tsx
@@ -1,6 +1,7 @@
"use client";
-import { ErrorNameItem, useGetErrorNamesPaginated } from "@/api/analytics/errors/useGetErrorNames";
+import { useGetErrorNamesPaginated } from "@/api/analytics/hooks/errors/useGetErrorNames";
+import { ErrorNameItem } from "@/api/analytics/endpoints";
import { Pagination } from "@/components/pagination";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { useStore } from "@/lib/store";
diff --git a/client/src/app/[site]/events/components/EventList.tsx b/client/src/app/[site]/events/components/EventList.tsx
index 6df71dc6d..d3d99922b 100644
--- a/client/src/app/[site]/events/components/EventList.tsx
+++ b/client/src/app/[site]/events/components/EventList.tsx
@@ -3,8 +3,8 @@
import NumberFlow from "@number-flow/react";
import { BookOpen, ChevronDown, ChevronRight, Info } from "lucide-react";
import { memo, useState } from "react";
-import { EventName } from "../../../../api/analytics/events/useGetEventNames";
-import { useGetEventProperties } from "../../../../api/analytics/events/useGetEventProperties";
+import { EventName } from "../../../../api/analytics/endpoints";
+import { useGetEventProperties } from "../../../../api/analytics/hooks/events/useGetEventProperties";
import { NothingFound } from "../../../../components/NothingFound";
import { cn } from "../../../../lib/utils";
import { EventProperties } from "./EventProperties";
diff --git a/client/src/app/[site]/events/components/EventLog.tsx b/client/src/app/[site]/events/components/EventLog.tsx
index 31b9a0cda..f5e1a27a1 100644
--- a/client/src/app/[site]/events/components/EventLog.tsx
+++ b/client/src/app/[site]/events/components/EventLog.tsx
@@ -1,7 +1,7 @@
"use client";
import { useCallback, useEffect, useRef } from "react";
-import { useGetEventsInfinite } from "../../../../api/analytics/events/useGetEvents";
+import { useGetEventsInfinite } from "../../../../api/analytics/hooks/events/useGetEvents";
import { NothingFound } from "../../../../components/NothingFound";
import { formatter } from "../../../../lib/utils";
import { EventLogItem, EventLogItemSkeleton } from "./EventLogItem";
diff --git a/client/src/app/[site]/events/components/EventLogItem.tsx b/client/src/app/[site]/events/components/EventLogItem.tsx
index 25202e304..8d0878adb 100644
--- a/client/src/app/[site]/events/components/EventLogItem.tsx
+++ b/client/src/app/[site]/events/components/EventLogItem.tsx
@@ -7,7 +7,7 @@ import { DateTime } from "luxon";
import Link from "next/link";
import { useParams } from "next/navigation";
import { memo } from "react";
-import { Event } from "../../../../api/analytics/events/useGetEvents";
+import { Event } from "../../../../api/analytics/endpoints";
import { getCountryName } from "../../../../lib/utils";
import { Browser } from "../../components/shared/icons/Browser";
import { CountryFlag } from "../../components/shared/icons/CountryFlag";
@@ -166,7 +166,9 @@ export function EventLogItem({ event }: EventLogItemProps) {
</div>
{/* Timestamp (right-aligned) */}
- <div className="text-sm shrink-0 text-neutral-500 dark:text-neutral-400 ml-auto">{eventTime.toRelative()}</div>
+ <div className="text-sm shrink-0 text-neutral-500 dark:text-neutral-400 ml-auto">
+ {eventTime.toRelative()}
+ </div>
</div>
{/* Bottom row with event properties */}
diff --git a/client/src/app/[site]/events/components/EventProperties.tsx b/client/src/app/[site]/events/components/EventProperties.tsx
index ff4124f6f..a16931992 100644
--- a/client/src/app/[site]/events/components/EventProperties.tsx
+++ b/client/src/app/[site]/events/components/EventProperties.tsx
@@ -3,7 +3,7 @@
import NumberFlow from "@number-flow/react";
import { Info } from "lucide-react";
import { memo } from "react";
-import { EventProperty } from "../../../../api/analytics/events/useGetEventProperties";
+import { EventProperty } from "../../../../api/analytics/endpoints";
import { cn } from "../../../../lib/utils";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
@@ -65,7 +65,9 @@ export function EventProperties({ properties, isLoading, selectedEvent, size = "
return (
<div key={key} className={cn("flex flex-col gap-1", size === "small" ? "text-xs" : "text-sm")}>
{/* Property Key Header */}
- <div className="font-semibold text-primary py-1 border-b border-neutral-100 dark:border-neutral-800">{key}</div>
+ <div className="font-semibold text-primary py-1 border-b border-neutral-100 dark:border-neutral-800">
+ {key}
+ </div>
{/* Property Values */}
<div className="pl-4 flex flex-col gap-2">
@@ -166,7 +168,10 @@ const EventPropertiesSkeleton = memo(({ size = "small" }: { size?: "small" | "la
></div>
</div>
<div className="flex gap-2">
- <div className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse" style={{ width: "40px" }}></div>
+ <div
+ className="h-4 bg-neutral-200 dark:bg-neutral-800 rounded animate-pulse"
+ style={{ width: "40px" }}
+ ></div>
</div>
</div>
</div>
diff --git a/client/src/app/[site]/events/components/OutboundLinksList.tsx b/client/src/app/[site]/events/components/OutboundLinksList.tsx
index 93475b4d5..47101ce38 100644
--- a/client/src/app/[site]/events/components/OutboundLinksList.tsx
+++ b/client/src/app/[site]/events/components/OutboundLinksList.tsx
@@ -4,7 +4,7 @@ import NumberFlow from "@number-flow/react";
import { Info } from "lucide-react";
import { DateTime } from "luxon";
import { memo } from "react";
-import { OutboundLink } from "../../../../api/analytics/events/useGetOutboundLinks";
+import { OutboundLink } from "../../../../api/analytics/endpoints";
import { Favicon } from "../../../../components/Favicon";
import { cn } from "../../../../lib/utils";
diff --git a/client/src/app/[site]/events/page.tsx b/client/src/app/[site]/events/page.tsx
index 5b39feef7..71c8b8ce2 100644
--- a/client/src/app/[site]/events/page.tsx
+++ b/client/src/app/[site]/events/page.tsx
@@ -2,7 +2,7 @@
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { EVENT_FILTERS } from "@/lib/filterGroups";
-import { useGetEventNames } from "../../../api/analytics/events/useGetEventNames";
+import { useGetEventNames } from "../../../api/analytics/hooks/events/useGetEventNames";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SubHeader } from "../components/SubHeader/SubHeader";
diff --git a/client/src/app/[site]/funnels/components/CreateFunnel.tsx b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
index d022ce784..127998e10 100644
--- a/client/src/app/[site]/funnels/components/CreateFunnel.tsx
+++ b/client/src/app/[site]/funnels/components/CreateFunnel.tsx
@@ -5,7 +5,8 @@ import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from
import { Plus } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
-import { FunnelStep, useGetFunnel, useSaveFunnel } from "../../../../api/analytics/funnels/useGetFunnel";
+import { useGetFunnel, useSaveFunnel } from "../../../../api/analytics/hooks/funnels/useGetFunnel";
+import { FunnelStep } from "../../../../api/analytics/endpoints";
import { FunnelForm } from "./FunnelForm";
export function CreateFunnelDialog() {
diff --git a/client/src/app/[site]/funnels/components/EditFunnel.tsx b/client/src/app/[site]/funnels/components/EditFunnel.tsx
index d1ee40845..6a92a522f 100644
--- a/client/src/app/[site]/funnels/components/EditFunnel.tsx
+++ b/client/src/app/[site]/funnels/components/EditFunnel.tsx
@@ -3,8 +3,8 @@
import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog";
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { FunnelStep, useGetFunnel, useSaveFunnel } from "../../../../api/analytics/funnels/useGetFunnel";
-import { SavedFunnel } from "../../../../api/analytics/funnels/useGetFunnels";
+import { useGetFunnel, useSaveFunnel } from "../../../../api/analytics/hooks/funnels/useGetFunnel";
+import { FunnelStep, SavedFunnel } from "../../../../api/analytics/endpoints";
import { FunnelForm } from "./FunnelForm";
interface EditFunnelDialogProps {
diff --git a/client/src/app/[site]/funnels/components/Funnel.tsx b/client/src/app/[site]/funnels/components/Funnel.tsx
index 55b122035..39bb94dfc 100644
--- a/client/src/app/[site]/funnels/components/Funnel.tsx
+++ b/client/src/app/[site]/funnels/components/Funnel.tsx
@@ -3,8 +3,8 @@
import { round } from "lodash";
import { ChevronDown, ChevronUp } from "lucide-react";
import { useState } from "react";
-import { FunnelResponse, FunnelStep } from "../../../../api/analytics/funnels/useGetFunnel";
-import { useGetFunnelStepSessions } from "../../../../api/analytics/funnels/useGetFunnelStepSessions";
+import { FunnelResponse, FunnelStep } from "../../../../api/analytics/endpoints";
+import { useGetFunnelStepSessions } from "../../../../api/analytics/hooks/funnels/useGetFunnelStepSessions";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
import { SessionsList } from "../../../../components/Sessions/SessionsList";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../components/ui/tabs";
diff --git a/client/src/app/[site]/funnels/components/FunnelForm.tsx b/client/src/app/[site]/funnels/components/FunnelForm.tsx
index e542185f7..b677614a4 100644
--- a/client/src/app/[site]/funnels/components/FunnelForm.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelForm.tsx
@@ -5,8 +5,8 @@ import { InputWithSuggestions, SuggestionOption } from "@/components/ui/input-wi
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Plus, Save, Trash2 } from "lucide-react";
import { useState } from "react";
-import { FunnelResponse, FunnelStep } from "../../../../api/analytics/funnels/useGetFunnel";
-import { useMetric } from "../../../../api/analytics/useGetMetric";
+import { FunnelResponse, FunnelStep } from "../../../../api/analytics/endpoints";
+import { useMetric } from "../../../../api/analytics/hooks/useGetMetric";
import { ThreeDotLoader } from "../../../../components/Loaders";
import { Label } from "../../../../components/ui/label";
import { Switch } from "../../../../components/ui/switch";
diff --git a/client/src/app/[site]/funnels/components/FunnelRow.tsx b/client/src/app/[site]/funnels/components/FunnelRow.tsx
index 22e007488..0d32ca939 100644
--- a/client/src/app/[site]/funnels/components/FunnelRow.tsx
+++ b/client/src/app/[site]/funnels/components/FunnelRow.tsx
@@ -7,9 +7,9 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { ArrowRight, ChevronDown, ChevronUp, Copy, Edit, Eye, MousePointerClick, Trash2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
-import { useDeleteFunnel } from "../../../../api/analytics/funnels/useDeleteFunnel";
-import { useGetFunnel } from "../../../../api/analytics/funnels/useGetFunnel";
-import { SavedFunnel } from "../../../../api/analytics/funnels/useGetFunnels";
+import { useDeleteFunnel } from "../../../../api/analytics/hooks/funnels/useDeleteFunnel";
+import { useGetFunnel } from "../../../../api/analytics/hooks/funnels/useGetFunnel";
+import { SavedFunnel } from "../../../../api/analytics/endpoints";
import { ThreeDotLoader } from "../../../../components/Loaders";
import { EditFunnelDialog } from "./EditFunnel";
import { Funnel } from "./Funnel";
diff --git a/client/src/app/[site]/funnels/page.tsx b/client/src/app/[site]/funnels/page.tsx
index 5ec8ed287..ababd8025 100644
--- a/client/src/app/[site]/funnels/page.tsx
+++ b/client/src/app/[site]/funnels/page.tsx
@@ -5,7 +5,8 @@ import { GOALS_PAGE_FILTERS } from "@/lib/filterGroups";
import { useStore } from "@/lib/store";
import { ArrowRight, Funnel } from "lucide-react";
import { useMemo, useState } from "react";
-import { SavedFunnel, useGetFunnels } from "../../../api/analytics/funnels/useGetFunnels";
+import { useGetFunnels } from "../../../api/analytics/hooks/funnels/useGetFunnels";
+import { SavedFunnel } from "../../../api/analytics/endpoints";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { ErrorState } from "../../../components/ErrorState";
import { NothingFound } from "../../../components/NothingFound";
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
index ad7a12f1d..84aa762ee 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCoordinatesLayer.ts
@@ -8,7 +8,7 @@ import Feature, { FeatureLike } from "ol/Feature";
import Point from "ol/geom/Point";
import { Circle, Fill, Stroke, Style } from "ol/style";
import { fromLonLat } from "ol/proj";
-import { useGetSessionLocations } from "../../../../../api/analytics/useGetSessionLocations";
+import { useGetSessionLocations } from "../../../../../api/analytics/hooks/useGetSessionLocations";
import { addFilter, removeFilter, useStore } from "../../../../../lib/store";
import { renderCountryFlag } from "../../utils/renderCountryFlag";
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
index 76a07ccac..e9b42a719 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersCountriesLayer.ts
@@ -5,7 +5,7 @@ import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Fill, Stroke, Style } from "ol/style";
import { MutableRefObject, useEffect, useMemo, useRef, useState } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { useCountries } from "../../../../../lib/geo";
import { addFilter } from "../../../../../lib/store";
import { createColorScale } from "../../utils/colorScale";
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
index 7df70a423..be6138b95 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersSubdivisionsLayer.ts
@@ -5,7 +5,7 @@ import VectorLayer from "ol/layer/Vector";
import VectorSource from "ol/source/Vector";
import { Fill, Stroke, Style } from "ol/style";
import { MutableRefObject, useEffect, useMemo, useRef, useState } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { useSubdivisions } from "../../../../../lib/geo";
import { addFilter } from "../../../../../lib/store";
import { createColorScale } from "../../utils/colorScale";
diff --git a/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
index 136dda4cf..09d90713f 100644
--- a/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
+++ b/client/src/app/[site]/globe/2d/hooks/useOpenLayersTimelineLayer.ts
@@ -1,18 +1,18 @@
-import { useEffect, useRef, useState } from "react";
+import Feature, { FeatureLike } from "ol/Feature";
import OLMap from "ol/Map";
import Overlay from "ol/Overlay";
-import VectorLayer from "ol/layer/Vector";
-import VectorSource from "ol/source/Vector";
-import Cluster from "ol/source/Cluster";
-import Feature, { FeatureLike } from "ol/Feature";
import Point from "ol/geom/Point";
-import { Circle, Fill, Stroke, Style, Text } from "ol/style";
+import VectorLayer from "ol/layer/Vector";
import { fromLonLat } from "ol/proj";
-import type { GetSessionsResponse } from "../../../../../api/analytics/useGetUserSessions";
-import { useTimelineStore, useActiveSessions } from "../../timelineStore";
+import Cluster from "ol/source/Cluster";
+import VectorSource from "ol/source/Vector";
+import { Circle, Fill, Style, Text } from "ol/style";
+import { useEffect, useRef, useState } from "react";
+import type { GetSessionsResponse } from "../../../../../api/analytics/endpoints";
import { generateAvatarSVG } from "../../3d/hooks/timelineLayer/timelineMarkerHelpers";
+import { useActiveSessions, useTimelineStore } from "../../timelineStore";
+import { CLUSTER_MAX_ZOOM, CLUSTERING_THRESHOLD, MIN_CLUSTER_SIZE } from "../../utils/clusteringConstants";
import { buildTooltipHTML } from "../../utils/timelineTooltipBuilder";
-import { CLUSTER_MAX_ZOOM, MIN_CLUSTER_SIZE, CLUSTERING_THRESHOLD } from "../../utils/clusteringConstants";
// OpenLayers-specific clustering constants
const CLUSTER_RADIUS = 50; // pixels (OpenLayers specific)
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
index 3a931b852..41a2dddaf 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineClusterUtils.ts
@@ -1,6 +1,6 @@
import mapboxgl from "mapbox-gl";
import { isNil, round } from "lodash";
-import type { GetSessionsResponse } from "../../../../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { SOURCE_ID, MIN_CLUSTER_SIZE } from "./timelineLayerConstants";
import { spreadOverlappingPoints } from "./timelineLayerManager";
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
index 7f68410cc..f5d9052b8 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineLayerManager.ts
@@ -1,6 +1,6 @@
import mapboxgl from "mapbox-gl";
import { isNil, round } from "lodash";
-import type { GetSessionsResponse } from "../../../../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { CLUSTER_LAYER_ID, CLUSTER_COUNT_LAYER_ID, SOURCE_ID, SPREAD_RADIUS_DEGREES } from "./timelineLayerConstants";
/**
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
index 31af22354..0cdedfd42 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/timelineMarkerManager.ts
@@ -1,5 +1,5 @@
import mapboxgl from "mapbox-gl";
-import type { GetSessionsResponse } from "../../../../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { generateAvatarSVG } from "./timelineMarkerHelpers";
import { getUnclusteredFeatures } from "./timelineClusterUtils";
import { buildTooltipHTML } from "../../../utils/timelineTooltipBuilder";
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
index e27f51dbe..4fd49c454 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineLayer.ts
@@ -1,7 +1,7 @@
import mapboxgl from "mapbox-gl";
import { useEffect, useRef, useState, useCallback } from "react";
import { throttle } from "lodash";
-import type { GetSessionsResponse } from "../../../../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { useTimelineStore, useActiveSessions } from "../../../timelineStore";
import { initializeClusterSource, setupClusterClickHandler } from "./timelineClusterUtils";
import {
diff --git a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
index 73df2c247..40c33ee55 100644
--- a/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
+++ b/client/src/app/[site]/globe/3d/hooks/timelineLayer/useTimelineSessions.ts
@@ -1,7 +1,7 @@
import { useQuery } from "@tanstack/react-query";
import { DateTime } from "luxon";
import { useEffect, useMemo } from "react";
-import { GetSessionsResponse } from "../../../../../../api/analytics/useGetUserSessions";
+import { GetSessionsResponse } from "../../../../../../api/analytics/endpoints";
import { APIResponse } from "../../../../../../api/types";
import { authedFetch, getQueryParams } from "../../../../../../api/utils";
import { getFilteredFilters, useStore } from "../../../../../../lib/store";
diff --git a/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
index 6e21b91c2..e2b4b8a98 100644
--- a/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCoordinatesLayer.ts
@@ -2,7 +2,7 @@ import { FilterParameter } from "@rybbit/shared/dist/filters";
import { round } from "lodash";
import mapboxgl from "mapbox-gl";
import { useEffect, useRef } from "react";
-import { useGetSessionLocations } from "../../../../../api/analytics/useGetSessionLocations";
+import { useGetSessionLocations } from "../../../../../api/analytics/hooks/useGetSessionLocations";
import { addFilter, removeFilter, useStore } from "../../../../../lib/store";
import { renderCountryFlag } from "../../utils/renderCountryFlag";
diff --git a/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
index 79bfb724e..cb0f88f37 100644
--- a/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useCountriesLayer.ts
@@ -1,7 +1,7 @@
import { FilterParameter } from "@rybbit/shared";
import mapboxgl from "mapbox-gl";
import { useEffect, useMemo, useRef } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { useCountries } from "../../../../../lib/geo";
import { addFilter } from "../../../../../lib/store";
import { createColorScale } from "../../utils/colorScale";
diff --git a/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
index bc4f867d0..0c87ff173 100644
--- a/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
+++ b/client/src/app/[site]/globe/3d/hooks/useSubdivisionsLayer.ts
@@ -1,7 +1,7 @@
import { FilterParameter } from "@rybbit/shared";
import mapboxgl from "mapbox-gl";
import { useEffect, useMemo, useRef } from "react";
-import { useMetric } from "../../../../../api/analytics/useGetMetric";
+import { useMetric } from "../../../../../api/analytics/hooks/useGetMetric";
import { useSubdivisions } from "../../../../../lib/geo";
import { addFilter } from "../../../../../lib/store";
import { createColorScale } from "../../utils/colorScale";
diff --git a/client/src/app/[site]/globe/components/GlobeSessions.tsx b/client/src/app/[site]/globe/components/GlobeSessions.tsx
index 0e13a5b17..ca04adf51 100644
--- a/client/src/app/[site]/globe/components/GlobeSessions.tsx
+++ b/client/src/app/[site]/globe/components/GlobeSessions.tsx
@@ -3,7 +3,8 @@ import { ArrowRight, ChevronDown, ChevronUp } from "lucide-react";
import { DateTime } from "luxon";
import { useMemo, useState } from "react";
import { useCurrentSite } from "../../../../api/admin/sites";
-import { GetSessionsResponse, useGetSessionsInfinite } from "../../../../api/analytics/useGetUserSessions";
+import { useGetSessionsInfinite } from "../../../../api/analytics/hooks/useGetUserSessions";
+import { GetSessionsResponse } from "../../../../api/analytics/endpoints";
import { Avatar, generateName } from "../../../../components/Avatar";
import { Channel } from "../../../../components/Channel";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
diff --git a/client/src/app/[site]/globe/timelineStore.ts b/client/src/app/[site]/globe/timelineStore.ts
index e25c18fcd..d89f0182b 100644
--- a/client/src/app/[site]/globe/timelineStore.ts
+++ b/client/src/app/[site]/globe/timelineStore.ts
@@ -1,7 +1,7 @@
import { DateTime } from "luxon";
import { create } from "zustand";
import { useMemo } from "react";
-import type { GetSessionsResponse } from "../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../api/analytics/endpoints";
import { getActiveSessions } from "./timelineUtils";
interface TimelineStore {
diff --git a/client/src/app/[site]/globe/timelineUtils.ts b/client/src/app/[site]/globe/timelineUtils.ts
index f07e9e7e0..a792ccd22 100644
--- a/client/src/app/[site]/globe/timelineUtils.ts
+++ b/client/src/app/[site]/globe/timelineUtils.ts
@@ -1,5 +1,5 @@
import { DateTime } from "luxon";
-import { GetSessionsResponse } from "../../../api/analytics/useGetUserSessions";
+import { GetSessionsResponse } from "../../../api/analytics/endpoints";
/**
* Calculate the appropriate window size in minutes based on the total time range
diff --git a/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
index 03e16c79b..ba543e4f4 100644
--- a/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
+++ b/client/src/app/[site]/globe/utils/timelineTooltipBuilder.ts
@@ -5,7 +5,7 @@ import { renderToStaticMarkup } from "react-dom/server";
import { Eye, MousePointerClick } from "lucide-react";
import { generateName } from "../../../../components/Avatar";
import { formatShortDuration, hour12, userLocale } from "../../../../lib/dateTimeUtils";
-import type { GetSessionsResponse } from "../../../../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../../../../api/analytics/endpoints";
import { extractDomain, getDisplayName } from "../../../../components/Channel";
import {
generateAvatarSVG,
diff --git a/client/src/app/[site]/goals/components/GoalCard.tsx b/client/src/app/[site]/goals/components/GoalCard.tsx
index 0b1ae2b28..b88bf5128 100644
--- a/client/src/app/[site]/goals/components/GoalCard.tsx
+++ b/client/src/app/[site]/goals/components/GoalCard.tsx
@@ -2,9 +2,9 @@
import { ChevronDown, ChevronUp, Copy, Edit, Trash2 } from "lucide-react";
import { useState } from "react";
-import { useDeleteGoal } from "../../../../api/analytics/goals/useDeleteGoal";
-import { Goal } from "../../../../api/analytics/goals/useGetGoals";
-import { useGetGoalSessions } from "../../../../api/analytics/goals/useGetGoalSessions";
+import { useDeleteGoal } from "../../../../api/analytics/hooks/goals/useDeleteGoal";
+import { Goal } from "../../../../api/analytics/endpoints";
+import { useGetGoalSessions } from "../../../../api/analytics/hooks/goals/useGetGoalSessions";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
import { SessionsList } from "../../../../components/Sessions/SessionsList";
import {
diff --git a/client/src/app/[site]/goals/components/GoalFormModal.tsx b/client/src/app/[site]/goals/components/GoalFormModal.tsx
index c26088ee2..05f2e6f49 100644
--- a/client/src/app/[site]/goals/components/GoalFormModal.tsx
+++ b/client/src/app/[site]/goals/components/GoalFormModal.tsx
@@ -4,10 +4,10 @@ import { zodResolver } from "@hookform/resolvers/zod";
import { useEffect, useState } from "react";
import { useForm } from "react-hook-form";
import * as z from "zod";
-import { useCreateGoal } from "../../../../api/analytics/goals/useCreateGoal";
-import { Goal } from "../../../../api/analytics/goals/useGetGoals";
-import { useUpdateGoal } from "../../../../api/analytics/goals/useUpdateGoal";
-import { useMetric } from "../../../../api/analytics/useGetMetric";
+import { useCreateGoal } from "../../../../api/analytics/hooks/goals/useCreateGoal";
+import { Goal } from "../../../../api/analytics/endpoints";
+import { useUpdateGoal } from "../../../../api/analytics/hooks/goals/useUpdateGoal";
+import { useMetric } from "../../../../api/analytics/hooks/useGetMetric";
import { EventIcon, PageviewIcon } from "../../../../components/EventIcons";
import { Button } from "../../../../components/ui/button";
import {
diff --git a/client/src/app/[site]/goals/components/GoalsList.tsx b/client/src/app/[site]/goals/components/GoalsList.tsx
index 025559f3e..2a9d0d543 100644
--- a/client/src/app/[site]/goals/components/GoalsList.tsx
+++ b/client/src/app/[site]/goals/components/GoalsList.tsx
@@ -1,7 +1,7 @@
"use client";
import GoalCard from "./GoalCard";
-import { Goal } from "../../../../api/analytics/goals/useGetGoals";
+import { Goal } from "../../../../api/analytics/endpoints";
interface GoalsListProps {
goals: Goal[];
diff --git a/client/src/app/[site]/goals/page.tsx b/client/src/app/[site]/goals/page.tsx
index 8db1ca666..733c7f0d5 100644
--- a/client/src/app/[site]/goals/page.tsx
+++ b/client/src/app/[site]/goals/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo, useState } from "react";
-import { useGetGoals } from "../../../api/analytics/goals/useGetGoals";
+import { useGetGoals } from "../../../api/analytics/hooks/goals/useGetGoals";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { NothingFound } from "../../../components/NothingFound";
import { Pagination } from "../../../components/pagination";
diff --git a/client/src/app/[site]/journeys/page.tsx b/client/src/app/[site]/journeys/page.tsx
index 534c9a670..253f163d8 100644
--- a/client/src/app/[site]/journeys/page.tsx
+++ b/client/src/app/[site]/journeys/page.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useJourneys } from "@/api/analytics/useGetJourneys";
+import { useJourneys } from "@/api/analytics/hooks/useGetJourneys";
import { Alert, AlertDescription, AlertTitle } from "@/components/ui/alert";
import { Input } from "@/components/ui/input";
import { Slider } from "@/components/ui/slider";
diff --git a/client/src/app/[site]/layout.tsx b/client/src/app/[site]/layout.tsx
index 6625cafd7..76bfd0a64 100644
--- a/client/src/app/[site]/layout.tsx
+++ b/client/src/app/[site]/layout.tsx
@@ -62,7 +62,8 @@ export default function SiteLayout({ children }: { children: React.ReactNode })
{!pathname.includes("/map") &&
!pathname.includes("/realtime") &&
!pathname.includes("/replay") &&
- !pathname.includes("/globe") && <Footer />}
+ !pathname.includes("/globe") &&
+ !pathname.includes("/api-playground") && <Footer />}
</div>
</div>
</div>
diff --git a/client/src/app/[site]/main/components/ExportButton.tsx b/client/src/app/[site]/main/components/ExportButton.tsx
index be9064755..ed99b034a 100644
--- a/client/src/app/[site]/main/components/ExportButton.tsx
+++ b/client/src/app/[site]/main/components/ExportButton.tsx
@@ -4,18 +4,17 @@ import { FilterParameter } from "@rybbit/shared";
import { Download, Loader2 } from "lucide-react";
import { useState } from "react";
import { toast } from "sonner";
-import { fetchEventNames } from "../../../../api/analytics/events/useGetEventNames";
-import { fetchOutboundLinks } from "../../../../api/analytics/events/useGetOutboundLinks";
-import { fetchMetric } from "../../../../api/analytics/useGetMetric";
-import { fetchOverviewBucketed } from "../../../../api/analytics/useGetOverviewBucketed";
+import {
+ fetchEventNames,
+ fetchMetric,
+ fetchOutboundLinks,
+ fetchOverviewBucketed,
+} from "../../../../api/analytics/endpoints";
+import { getStartAndEndDate, timeZone } from "../../../../api/utils";
import { fetchGSCConnectionStatus } from "../../../../api/gsc/useGSCConnection";
import { fetchGSCData, GSCDimension } from "../../../../api/gsc/useGSCData";
import { Button } from "../../../../components/ui/button";
-import {
- Tooltip,
- TooltipContent,
- TooltipTrigger,
-} from "../../../../components/ui/tooltip";
+import { Tooltip, TooltipContent, TooltipTrigger } from "../../../../components/ui/tooltip";
import { IS_CLOUD } from "../../../../lib/const";
import { CSVFile, downloadZip, formatDateForFilename } from "../../../../lib/export";
import { useStore } from "../../../../lib/store";
@@ -86,6 +85,15 @@ export function ExportButton() {
setIsExporting(true);
const csvFiles: CSVFile[] = [];
+ // Convert time to API params
+ const { startDate, endDate } = getStartAndEndDate(time);
+ const commonParams = {
+ startDate: startDate ?? "",
+ endDate: endDate ?? "",
+ timeZone,
+ filters,
+ };
+
try {
// Fetch all metrics in parallel
const allMetrics = [
@@ -98,8 +106,8 @@ export function ExportButton() {
const metricPromises = allMetrics.map(async ({ param, filename }) => {
try {
- const data = await fetchMetric(site, param, time, filters);
- return { filename, data: data as Record<string, unknown>[] };
+ const result = await fetchMetric(site, { ...commonParams, parameter: param });
+ return { filename, data: result.data as Record<string, unknown>[] };
} catch {
console.warn(`Failed to fetch ${param}`);
return { filename, data: [] };
@@ -109,7 +117,7 @@ export function ExportButton() {
// Fetch overview bucketed data
const overviewPromise = (async () => {
try {
- const data = await fetchOverviewBucketed(site, time, "day", filters);
+ const data = await fetchOverviewBucketed(site, { ...commonParams, bucket: "day" });
return {
filename: "overview-timeseries.csv",
data: data as unknown as Record<string, unknown>[],
@@ -123,7 +131,7 @@ export function ExportButton() {
// Fetch weekdays heatmap data (hourly bucketed)
const weekdaysPromise = (async () => {
try {
- const data = await fetchOverviewBucketed(site, time, "hour", filters);
+ const data = await fetchOverviewBucketed(site, { ...commonParams, bucket: "hour" });
return {
filename: "weekdays-heatmap.csv",
data: data as unknown as Record<string, unknown>[],
@@ -137,7 +145,7 @@ export function ExportButton() {
// Fetch events data
const eventsPromise = (async () => {
try {
- const data = await fetchEventNames(site, time, filters);
+ const data = await fetchEventNames(site, commonParams);
return {
filename: "events.csv",
data: data as unknown as Record<string, unknown>[],
@@ -151,7 +159,7 @@ export function ExportButton() {
// Fetch outbound links
const outboundPromise = (async () => {
try {
- const data = await fetchOutboundLinks(site, time, filters);
+ const data = await fetchOutboundLinks(site, commonParams);
return {
filename: "outbound-links.csv",
data: data as unknown as Record<string, unknown>[],
@@ -192,15 +200,14 @@ export function ExportButton() {
})();
// Wait for all fetches to complete
- const [metricResults, overview, weekdays, events, outbound, gscResults] =
- await Promise.all([
- Promise.all(metricPromises),
- overviewPromise,
- weekdaysPromise,
- eventsPromise,
- outboundPromise,
- gscPromises,
- ]);
+ const [metricResults, overview, weekdays, events, outbound, gscResults] = await Promise.all([
+ Promise.all(metricPromises),
+ overviewPromise,
+ weekdaysPromise,
+ eventsPromise,
+ outboundPromise,
+ gscPromises,
+ ]);
// Collect all CSV files
csvFiles.push(...metricResults);
@@ -211,7 +218,7 @@ export function ExportButton() {
csvFiles.push(...gscResults);
// Filter out empty files
- const nonEmptyFiles = csvFiles.filter((f) => f.data.length > 0);
+ const nonEmptyFiles = csvFiles.filter(f => f.data.length > 0);
if (nonEmptyFiles.length === 0) {
toast.error("No data to export");
@@ -237,17 +244,8 @@ export function ExportButton() {
return (
<Tooltip>
<TooltipTrigger asChild>
- <Button
- variant="ghost"
- size="smIcon"
- onClick={handleExport}
- disabled={isExporting}
- >
- {isExporting ? (
- <Loader2 className="h-4 w-4 animate-spin" />
- ) : (
- <Download className="h-4 w-4" />
- )}
+ <Button variant="ghost" size="smIcon" onClick={handleExport} disabled={isExporting}>
+ {isExporting ? <Loader2 className="h-4 w-4 animate-spin" /> : <Download className="h-4 w-4" />}
</Button>
</TooltipTrigger>
<TooltipContent>
diff --git a/client/src/app/[site]/main/components/MainSection/Chart.tsx b/client/src/app/[site]/main/components/MainSection/Chart.tsx
index 5ff39502f..2b7b86d36 100644
--- a/client/src/app/[site]/main/components/MainSection/Chart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Chart.tsx
@@ -5,7 +5,7 @@ import { StatType, useStore } from "@/lib/store";
import { LineCustomSvgLayer, LineCustomSvgLayerProps, LineSeries, ResponsiveLine } from "@nivo/line";
import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
-import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
import { formatSecondsAsMinutesAndSeconds, formatter } from "../../../../../lib/utils";
diff --git a/client/src/app/[site]/main/components/MainSection/MainSection.tsx b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
index 514387a9e..b95054557 100644
--- a/client/src/app/[site]/main/components/MainSection/MainSection.tsx
+++ b/client/src/app/[site]/main/components/MainSection/MainSection.tsx
@@ -2,8 +2,8 @@
import { Card, CardContent, CardLoader } from "@/components/ui/card";
import { Tilt_Warp } from "next/font/google";
import Link from "next/link";
-import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
+import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { BucketSelection } from "../../../../../components/BucketSelection";
import { RybbitLogo } from "../../../../../components/RybbitLogo";
import { authClient } from "../../../../../lib/auth";
diff --git a/client/src/app/[site]/main/components/MainSection/Overview.tsx b/client/src/app/[site]/main/components/MainSection/Overview.tsx
index 1892536b7..6af145108 100644
--- a/client/src/app/[site]/main/components/MainSection/Overview.tsx
+++ b/client/src/app/[site]/main/components/MainSection/Overview.tsx
@@ -5,8 +5,8 @@ import { cn, formatSecondsAsMinutesAndSeconds } from "@/lib/utils";
import NumberFlow from "@number-flow/react";
import { TrendingDown, TrendingUp } from "lucide-react";
import { useState } from "react";
-import { useGetOverview } from "../../../../../api/analytics/useGetOverview";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { useGetOverview } from "../../../../../api/analytics/hooks/useGetOverview";
+import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { StatType, useStore } from "../../../../../lib/store";
import { SparklinesChart } from "./SparklinesChart";
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
diff --git a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
index 6d37363bb..93e45df1a 100644
--- a/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
+++ b/client/src/app/[site]/main/components/MainSection/PreviousChart.tsx
@@ -4,7 +4,7 @@ import { useStore } from "@/lib/store";
import { useTheme } from "next-themes";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
-import { GetOverviewBucketedResponse } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { GetOverviewBucketedResponse } from "../../../../../api/analytics/endpoints";
import { APIResponse } from "../../../../../api/types";
import { Time } from "../../../../../components/DateSelector/types";
import { TimeBucket } from "@rybbit/shared";
diff --git a/client/src/app/[site]/main/components/sections/Events.tsx b/client/src/app/[site]/main/components/sections/Events.tsx
index 1d3278cf4..aa404f41c 100644
--- a/client/src/app/[site]/main/components/sections/Events.tsx
+++ b/client/src/app/[site]/main/components/sections/Events.tsx
@@ -2,11 +2,11 @@ import { useState } from "react";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
import { Button } from "../../../../../components/ui/button";
-import { useGetEventNames } from "../../../../../api/analytics/events/useGetEventNames";
+import { useGetEventNames } from "../../../../../api/analytics/hooks/events/useGetEventNames";
import { EventList } from "../../../events/components/EventList";
import { OutboundLinksList } from "../../../events/components/OutboundLinksList";
import { OutboundLinksDialog } from "./OutboundLinksDialog";
-import { useGetOutboundLinks } from "../../../../../api/analytics/events/useGetOutboundLinks";
+import { useGetOutboundLinks } from "../../../../../api/analytics/hooks/events/useGetOutboundLinks";
import { Expand } from "lucide-react";
type Tab = "events" | "outbound";
diff --git a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
index daf0534a4..d8675c80c 100644
--- a/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
+++ b/client/src/app/[site]/main/components/sections/OutboundLinksDialog.tsx
@@ -6,7 +6,7 @@ import { useDebounce, useIntersectionObserver } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
import { ChevronDown, ChevronUp, Loader2, Search, SquareArrowOutUpRight } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
-import { OutboundLink } from "../../../../../api/analytics/events/useGetOutboundLinks";
+import { OutboundLink } from "../../../../../api/analytics/endpoints";
import { cn } from "../../../../../lib/utils";
interface OutboundLinksDialogProps {
@@ -199,7 +199,9 @@ export function OutboundLinksDialog({ outboundLinks, expanded, close }: Outbound
</div>
</div>
)}
- {!hasMore && <div className="py-4 text-center text-neutral-500 dark:text-neutral-500 text-xs">All items loaded</div>}
+ {!hasMore && (
+ <div className="py-4 text-center text-neutral-500 dark:text-neutral-500 text-xs">All items loaded</div>
+ )}
</div>
</div>
</DialogContent>
diff --git a/client/src/app/[site]/main/components/sections/Weekdays.tsx b/client/src/app/[site]/main/components/sections/Weekdays.tsx
index baf7c3ff5..fdb7198db 100644
--- a/client/src/app/[site]/main/components/sections/Weekdays.tsx
+++ b/client/src/app/[site]/main/components/sections/Weekdays.tsx
@@ -1,6 +1,6 @@
import { DateTime } from "luxon";
import { useMemo, useState } from "react";
-import { useGetOverviewBucketed } from "../../../../../api/analytics/useGetOverviewBucketed";
+import { useGetOverviewBucketed } from "../../../../../api/analytics/hooks/useGetOverviewBucketed";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
import { Tabs, TabsList, TabsTrigger } from "../../../../../components/ui/basic-tabs";
import { Card, CardContent, CardLoader } from "../../../../../components/ui/card";
@@ -173,7 +173,10 @@ export function Weekdays() {
{Array(24)
.fill(0)
.map((_, hour) => (
- <div key={hour} className="h-4 text-xs flex items-center justify-end pr-2 text-neutral-600 dark:text-neutral-400">
+ <div
+ key={hour}
+ className="h-4 text-xs flex items-center justify-end pr-2 text-neutral-600 dark:text-neutral-400"
+ >
{hour % 2 === 1 ? hourLabels[hour] : ""}
</div>
))}
@@ -223,7 +226,9 @@ export function Weekdays() {
</div>
<div className="flex items-center gap-2">
<span className="font-semibold">{formatMetricValue(value)}</span>
- <span className="text-neutral-500 dark:text-neutral-400 text-xs">{getMetricDisplayName(metric)}</span>
+ <span className="text-neutral-500 dark:text-neutral-400 text-xs">
+ {getMetricDisplayName(metric)}
+ </span>
</div>
</div>
</ChartTooltip>
diff --git a/client/src/app/[site]/pages/components/PageListItem.tsx b/client/src/app/[site]/pages/components/PageListItem.tsx
index 6e075a9c0..fa5e32d2e 100644
--- a/client/src/app/[site]/pages/components/PageListItem.tsx
+++ b/client/src/app/[site]/pages/components/PageListItem.tsx
@@ -1,8 +1,8 @@
"use client";
import { useGetSite } from "@/api/admin/sites";
-import { useGetOverviewBucketed } from "@/api/analytics/useGetOverviewBucketed";
-import { MetricResponse } from "@/api/analytics/useGetMetric";
+import { useGetOverviewBucketed } from "@/api/analytics/hooks/useGetOverviewBucketed";
+import { MetricResponse } from "@/api/analytics/endpoints";
import { usePageMetadata } from "@/api/usePageMetadata";
import { Card, CardContent } from "@/components/ui/card";
import { Filter } from "@rybbit/shared";
diff --git a/client/src/app/[site]/pages/components/PageSparklineChart.tsx b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
index eccdc3a26..8d17b3cc9 100644
--- a/client/src/app/[site]/pages/components/PageSparklineChart.tsx
+++ b/client/src/app/[site]/pages/components/PageSparklineChart.tsx
@@ -1,6 +1,6 @@
"use client";
-import { GetOverviewBucketedResponse } from "@/api/analytics/useGetOverviewBucketed";
+import { GetOverviewBucketedResponse } from "@/api/analytics/endpoints";
import { APIResponse } from "@/api/types";
import { ChartTooltip } from "@/components/charts/ChartTooltip";
import { hour12, userLocale } from "@/lib/dateTimeUtils";
diff --git a/client/src/app/[site]/pages/page.tsx b/client/src/app/[site]/pages/page.tsx
index 6faed036c..e8f8a789b 100644
--- a/client/src/app/[site]/pages/page.tsx
+++ b/client/src/app/[site]/pages/page.tsx
@@ -1,6 +1,7 @@
"use client";
-import { PageTitleItem, useGetPageTitlesPaginated } from "@/api/analytics/useGetPageTitles";
+import { useGetPageTitlesPaginated } from "@/api/analytics/hooks/useGetPageTitles";
+import { PageTitleItem } from "@/api/analytics/endpoints";
import { Pagination } from "@/components/pagination";
import { useSetPageTitle } from "@/hooks/useSetPageTitle";
import { useStore } from "@/lib/store";
diff --git a/client/src/app/[site]/performance/components/PerformanceChart.tsx b/client/src/app/[site]/performance/components/PerformanceChart.tsx
index 9f25b32d7..513d80c3e 100644
--- a/client/src/app/[site]/performance/components/PerformanceChart.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceChart.tsx
@@ -8,7 +8,7 @@ import { DateTime } from "luxon";
import { Tilt_Warp } from "next/font/google";
import Link from "next/link";
import { useState } from "react";
-import { useGetPerformanceTimeSeries } from "../../../../api/analytics/performance/useGetPerformanceTimeSeries";
+import { useGetPerformanceTimeSeries } from "../../../../api/analytics/hooks/performance/useGetPerformanceTimeSeries";
import { BucketSelection } from "../../../../components/BucketSelection";
import { RybbitLogo } from "../../../../components/RybbitLogo";
import { authClient } from "../../../../lib/auth";
diff --git a/client/src/app/[site]/performance/components/PerformanceMap.tsx b/client/src/app/[site]/performance/components/PerformanceMap.tsx
index a369db5b4..29c45137c 100644
--- a/client/src/app/[site]/performance/components/PerformanceMap.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceMap.tsx
@@ -1,6 +1,6 @@
"use client";
-import { useGetPerformanceByDimension } from "@/api/analytics/performance/useGetPerformanceByDimension";
+import { useGetPerformanceByDimension } from "@/api/analytics/hooks/performance/useGetPerformanceByDimension";
import { useMeasure } from "@uidotdev/usehooks";
import { Feature } from "geojson";
import "ol/ol.css";
@@ -149,13 +149,13 @@ export function PerformanceMap({ height }: { height: string }) {
mapInstanceRef.current = map;
// Handle pointer move for hover effects
- map.on("pointermove", (evt) => {
+ map.on("pointermove", evt => {
if (evt.dragging) {
return;
}
const pixel = map.getEventPixel(evt.originalEvent);
- const feature = map.forEachFeatureAtPixel(pixel, (feature) => feature);
+ const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
if (feature) {
const countryCode = feature.get("ISO_A2");
@@ -199,9 +199,9 @@ export function PerformanceMap({ height }: { height: string }) {
});
// Handle click for filtering
- map.on("click", (evt) => {
+ map.on("click", evt => {
const pixel = map.getEventPixel(evt.originalEvent);
- const feature = map.forEachFeatureAtPixel(pixel, (feature) => feature);
+ const feature = map.forEachFeatureAtPixel(pixel, feature => feature);
if (feature) {
const countryCode = feature.get("ISO_A2");
@@ -250,7 +250,7 @@ export function PerformanceMap({ height }: { height: string }) {
// Create new vector layer with inline style function
const vectorLayer = new VectorLayer({
source: vectorSource,
- style: (feature) => {
+ style: feature => {
const countryCode = feature.get("ISO_A2");
const foundData = processedPerformanceDataRef.current?.find((item: any) => item.country === countryCode);
@@ -294,7 +294,14 @@ export function PerformanceMap({ height }: { height: string }) {
vectorLayerRef.current = vectorLayer;
mapInstanceRef.current.addLayer(vectorLayer);
- }, [countriesGeoData, dataVersion, selectedPercentile, selectedPerformanceMetric, colorScale, processedPerformanceData]);
+ }, [
+ countriesGeoData,
+ dataVersion,
+ selectedPercentile,
+ selectedPerformanceMetric,
+ colorScale,
+ processedPerformanceData,
+ ]);
// Update styles when hoveredId changes (without recreating the layer)
useEffect(() => {
diff --git a/client/src/app/[site]/performance/components/PerformanceOverview.tsx b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
index 57fab4992..178ff56d4 100644
--- a/client/src/app/[site]/performance/components/PerformanceOverview.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceOverview.tsx
@@ -4,7 +4,7 @@ import { Skeleton } from "@/components/ui/skeleton";
import { cn } from "@/lib/utils";
import NumberFlow from "@number-flow/react";
import { TrendingDown, TrendingUp } from "lucide-react";
-import { useGetPerformanceOverview } from "../../../../api/analytics/performance/useGetPerformanceOverview";
+import { useGetPerformanceOverview } from "../../../../api/analytics/hooks/performance/useGetPerformanceOverview";
import { Card, CardContent, CardLoader } from "../../../../components/ui/card";
import { useStore } from "../../../../lib/store";
import { PerformanceMetric, usePerformanceStore } from "../performanceStore";
diff --git a/client/src/app/[site]/performance/components/PerformanceTable.tsx b/client/src/app/[site]/performance/components/PerformanceTable.tsx
index 15fe5a85a..65110ef91 100644
--- a/client/src/app/[site]/performance/components/PerformanceTable.tsx
+++ b/client/src/app/[site]/performance/components/PerformanceTable.tsx
@@ -1,7 +1,15 @@
"use client";
import { Skeleton } from "@/components/ui/skeleton";
-import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow, TableSortIndicator } from "@/components/ui/table";
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+ TableSortIndicator,
+} from "@/components/ui/table";
import {
createColumnHelper,
flexRender,
@@ -10,18 +18,11 @@ import {
SortingState,
useReactTable,
} from "@tanstack/react-table";
-import {
- Monitor,
- Smartphone,
- Tablet,
- SquareArrowOutUpRight,
-} from "lucide-react";
+import { Monitor, Smartphone, Tablet, SquareArrowOutUpRight } from "lucide-react";
import { useMemo, useState, useCallback } from "react";
import { useGetSite } from "../../../../api/admin/sites";
-import {
- PerformanceByDimensionItem,
- useGetPerformanceByDimension,
-} from "../../../../api/analytics/performance/useGetPerformanceByDimension";
+import { useGetPerformanceByDimension } from "../../../../api/analytics/hooks/performance/useGetPerformanceByDimension";
+import { PerformanceByDimensionItem } from "../../../../api/analytics/endpoints";
import { Pagination } from "../../../../components/pagination";
import { FilterParameter } from "@rybbit/shared";
import { useStore, addFilter, removeFilter } from "../../../../lib/store";
diff --git a/client/src/app/[site]/replay/components/ReplayBreadcrumbs.tsx b/client/src/app/[site]/replay/components/ReplayBreadcrumbs.tsx
index e074f87b4..8a3ab7f8a 100644
--- a/client/src/app/[site]/replay/components/ReplayBreadcrumbs.tsx
+++ b/client/src/app/[site]/replay/components/ReplayBreadcrumbs.tsx
@@ -28,7 +28,7 @@ import { Duration } from "luxon";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo } from "react";
-import { useGetSessionReplayEvents } from "../../../../api/analytics/sessionReplay/useGetSessionReplayEvents";
+import { useGetSessionReplayEvents } from "../../../../api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";
import { Avatar } from "../../../../components/Avatar";
import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
import { Button } from "../../../../components/ui/button";
diff --git a/client/src/app/[site]/replay/components/ReplayCard.tsx b/client/src/app/[site]/replay/components/ReplayCard.tsx
index 0b35657bb..3b4b7362b 100644
--- a/client/src/app/[site]/replay/components/ReplayCard.tsx
+++ b/client/src/app/[site]/replay/components/ReplayCard.tsx
@@ -1,7 +1,7 @@
import { Clock, MousePointerClick, Trash2 } from "lucide-react";
import { DateTime } from "luxon";
import { useState } from "react";
-import { useDeleteSessionReplay } from "../../../../api/analytics/sessionReplay/useDeleteSessionReplay";
+import { useDeleteSessionReplay } from "../../../../api/analytics/hooks/sessionReplay/useDeleteSessionReplay";
import { Avatar } from "../../../../components/Avatar";
import { IdentifiedBadge } from "../../../../components/IdentifiedBadge";
import {
diff --git a/client/src/app/[site]/replay/components/ReplayList.tsx b/client/src/app/[site]/replay/components/ReplayList.tsx
index dfd1e2804..3eb65f79e 100644
--- a/client/src/app/[site]/replay/components/ReplayList.tsx
+++ b/client/src/app/[site]/replay/components/ReplayList.tsx
@@ -3,10 +3,8 @@ import { useIntersectionObserver } from "@uidotdev/usehooks";
import { Loader2, Video } from "lucide-react";
import { NothingFound } from "../../../../components/NothingFound";
import { ReplayCard, ReplayCardSkeleton } from "./ReplayCard";
-import {
- useGetSessionReplays,
- SessionReplayListItem,
-} from "../../../../api/analytics/sessionReplay/useGetSessionReplays";
+import { useGetSessionReplays } from "../../../../api/analytics/hooks/sessionReplay/useGetSessionReplays";
+import { SessionReplayListItem } from "../../../../api/analytics/endpoints";
import { useReplayStore } from "./replayStore";
import { ScrollArea } from "../../../../components/ui/scroll-area";
import { Input } from "../../../../components/ui/input";
diff --git a/client/src/app/[site]/replay/components/player/ReplayPlayer.tsx b/client/src/app/[site]/replay/components/player/ReplayPlayer.tsx
index 206903019..090b40c44 100644
--- a/client/src/app/[site]/replay/components/player/ReplayPlayer.tsx
+++ b/client/src/app/[site]/replay/components/player/ReplayPlayer.tsx
@@ -1,7 +1,7 @@
import { useParams } from "next/navigation";
import { useEffect } from "react";
import "rrweb-player/dist/style.css";
-import { useGetSessionReplayEvents } from "../../../../../api/analytics/sessionReplay/useGetSessionReplayEvents";
+import { useGetSessionReplayEvents } from "../../../../../api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";
import { ThreeDotLoader } from "../../../../../components/Loaders";
import { useReplayStore } from "../replayStore";
import { useActivityPeriods } from "./hooks/useActivityPeriods";
diff --git a/client/src/app/[site]/replay/components/player/ReplayPlayerTopbar.tsx b/client/src/app/[site]/replay/components/player/ReplayPlayerTopbar.tsx
index bb4c83794..40e2d9885 100644
--- a/client/src/app/[site]/replay/components/player/ReplayPlayerTopbar.tsx
+++ b/client/src/app/[site]/replay/components/player/ReplayPlayerTopbar.tsx
@@ -1,7 +1,7 @@
import Link from "next/link";
import { useParams } from "next/navigation";
import { useMemo } from "react";
-import { useGetSessionReplayEvents } from "../../../../../api/analytics/sessionReplay/useGetSessionReplayEvents";
+import { useGetSessionReplayEvents } from "../../../../../api/analytics/hooks/sessionReplay/useGetSessionReplayEvents";
import {
BrowserTooltipIcon,
CountryFlagTooltipIcon,
diff --git a/client/src/app/[site]/replay/page.tsx b/client/src/app/[site]/replay/page.tsx
index 4d44ae7ce..4ceb9bc7d 100644
--- a/client/src/app/[site]/replay/page.tsx
+++ b/client/src/app/[site]/replay/page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMeasure } from "@uidotdev/usehooks";
-import { useGetSessionReplays } from "../../../api/analytics/sessionReplay/useGetSessionReplays";
+import { useGetSessionReplays } from "../../../api/analytics/hooks/sessionReplay/useGetSessionReplays";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SESSION_REPLAY_PAGE_FILTERS } from "../../../lib/filterGroups";
diff --git a/client/src/app/[site]/retention/RetentionChart.tsx b/client/src/app/[site]/retention/RetentionChart.tsx
index bfc42381c..763223ec1 100644
--- a/client/src/app/[site]/retention/RetentionChart.tsx
+++ b/client/src/app/[site]/retention/RetentionChart.tsx
@@ -5,7 +5,7 @@ import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
import { useTheme } from "next-themes";
import { useMemo } from "react";
-import { ProcessedRetentionData, RetentionMode } from "../../../api/analytics/useGetRetention";
+import { ProcessedRetentionData, RetentionMode } from "../../../api/analytics/endpoints";
import { ChartTooltip } from "../../../components/charts/ChartTooltip";
import { Skeleton } from "../../../components/ui/skeleton";
diff --git a/client/src/app/[site]/retention/page.tsx b/client/src/app/[site]/retention/page.tsx
index 21d3b6665..a1d932beb 100644
--- a/client/src/app/[site]/retention/page.tsx
+++ b/client/src/app/[site]/retention/page.tsx
@@ -3,7 +3,8 @@
import { ChartColumnDecreasing } from "lucide-react";
import { DateTime } from "luxon"; // Import Luxon for date formatting
import { Fragment, useMemo, useState } from "react";
-import { RetentionMode, useGetRetention } from "../../../api/analytics/useGetRetention";
+import { useGetRetention } from "../../../api/analytics/hooks/useGetRetention";
+import { RetentionMode } from "../../../api/analytics/endpoints";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { ThreeDotLoader } from "../../../components/Loaders";
import { NothingFound } from "../../../components/NothingFound";
diff --git a/client/src/app/[site]/sessions/page.tsx b/client/src/app/[site]/sessions/page.tsx
index 3409de094..4d784d876 100644
--- a/client/src/app/[site]/sessions/page.tsx
+++ b/client/src/app/[site]/sessions/page.tsx
@@ -2,7 +2,7 @@
import { SessionsList } from "@/components/Sessions/SessionsList";
import { useState } from "react";
-import { useGetSessions } from "../../../api/analytics/useGetUserSessions";
+import { useGetSessions } from "../../../api/analytics/hooks/useGetUserSessions";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
import { useSetPageTitle } from "../../../hooks/useSetPageTitle";
import { SESSION_PAGE_FILTERS } from "../../../lib/filterGroups";
diff --git a/client/src/app/[site]/user/[userId]/components/Calendar.tsx b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
index 58e35574e..fdfbfa93f 100644
--- a/client/src/app/[site]/user/[userId]/components/Calendar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/Calendar.tsx
@@ -2,7 +2,7 @@ import { ResponsiveTimeRange } from "@nivo/calendar";
import _ from "lodash";
import { DateTime } from "luxon";
import { useTheme } from "next-themes";
-import { UserSessionCountResponse } from "../../../../../api/analytics/useGetUserSessions";
+import { UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
import { useNivoTheme } from "../../../../../lib/nivo";
import { ChartTooltip } from "../../../../../components/charts/ChartTooltip";
diff --git a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
index b571df95e..8d545e0a8 100644
--- a/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
+++ b/client/src/app/[site]/user/[userId]/components/UserSidebar.tsx
@@ -13,8 +13,7 @@ import { CountryFlag } from "../../../components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../../components/shared/icons/OperatingSystem";
import { VisitCalendar } from "./Calendar";
import { EventIcon, PageviewIcon } from "../../../../../components/EventIcons";
-import { UserInfo } from "../../../../../api/analytics/userGetInfo";
-import { UserSessionCountResponse } from "../../../../../api/analytics/useGetUserSessions";
+import { UserInfo, UserSessionCountResponse } from "../../../../../api/analytics/endpoints";
interface UserSidebarProps {
data: UserInfo | undefined;
diff --git a/client/src/app/[site]/user/[userId]/page.tsx b/client/src/app/[site]/user/[userId]/page.tsx
index c5b160832..5795fe85f 100644
--- a/client/src/app/[site]/user/[userId]/page.tsx
+++ b/client/src/app/[site]/user/[userId]/page.tsx
@@ -4,8 +4,8 @@ import { SessionsList } from "@/components/Sessions/SessionsList";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
-import { useUserInfo } from "../../../../api/analytics/userGetInfo";
-import { useGetSessions, useGetUserSessionCount } from "../../../../api/analytics/useGetUserSessions";
+import { useUserInfo } from "../../../../api/analytics/hooks/userGetInfo";
+import { useGetSessions, useGetUserSessionCount } from "../../../../api/analytics/hooks/useGetUserSessions";
import {
Breadcrumb,
BreadcrumbItem,
diff --git a/client/src/app/[site]/users/page.tsx b/client/src/app/[site]/users/page.tsx
index e380948d0..8e57737a4 100644
--- a/client/src/app/[site]/users/page.tsx
+++ b/client/src/app/[site]/users/page.tsx
@@ -14,7 +14,8 @@ import { DateTime } from "luxon";
import Link from "next/link";
import { useParams } from "next/navigation";
import { useState } from "react";
-import { useGetUsers, UsersResponse } from "../../../api/analytics/useGetUsers";
+import { useGetUsers } from "../../../api/analytics/hooks/useGetUsers";
+import { UsersResponse } from "../../../api/analytics/endpoints";
import { Avatar } from "../../../components/Avatar";
import { extractDomain, getChannelIcon, getDisplayName } from "../../../components/Channel";
import { DisabledOverlay } from "../../../components/DisabledOverlay";
diff --git a/client/src/components/CodeSnippet.tsx b/client/src/components/CodeSnippet.tsx
index a789b369e..1984a0362 100644
--- a/client/src/components/CodeSnippet.tsx
+++ b/client/src/components/CodeSnippet.tsx
@@ -2,17 +2,50 @@
import { Check, Copy } from "lucide-react";
import * as React from "react";
+import { Light as SyntaxHighlighter } from "react-syntax-highlighter";
+import js from "react-syntax-highlighter/dist/esm/languages/hljs/javascript";
+import python from "react-syntax-highlighter/dist/esm/languages/hljs/python";
+import bash from "react-syntax-highlighter/dist/esm/languages/hljs/bash";
+import php from "react-syntax-highlighter/dist/esm/languages/hljs/php";
+import ruby from "react-syntax-highlighter/dist/esm/languages/hljs/ruby";
+import go from "react-syntax-highlighter/dist/esm/languages/hljs/go";
+import rust from "react-syntax-highlighter/dist/esm/languages/hljs/rust";
+import java from "react-syntax-highlighter/dist/esm/languages/hljs/java";
+import csharp from "react-syntax-highlighter/dist/esm/languages/hljs/csharp";
+import json from "react-syntax-highlighter/dist/esm/languages/hljs/json";
+import { vs2015, vs } from "react-syntax-highlighter/dist/esm/styles/hljs";
+import { useTheme } from "next-themes";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
+// Register only the languages we need
+SyntaxHighlighter.registerLanguage("javascript", js);
+SyntaxHighlighter.registerLanguage("python", python);
+SyntaxHighlighter.registerLanguage("bash", bash);
+SyntaxHighlighter.registerLanguage("php", php);
+SyntaxHighlighter.registerLanguage("ruby", ruby);
+SyntaxHighlighter.registerLanguage("go", go);
+SyntaxHighlighter.registerLanguage("rust", rust);
+SyntaxHighlighter.registerLanguage("java", java);
+SyntaxHighlighter.registerLanguage("csharp", csharp);
+SyntaxHighlighter.registerLanguage("json", json);
+
interface CodeSnippetProps extends React.HTMLAttributes<HTMLPreElement> {
code: string;
language?: string;
+ showLanguageLabel?: boolean;
}
-export function CodeSnippet({ code, language, className, ...props }: CodeSnippetProps) {
+export const CodeSnippet = React.memo(function CodeSnippet({
+ code,
+ language,
+ showLanguageLabel = false,
+ className,
+}: CodeSnippetProps) {
const [hasCopied, setHasCopied] = React.useState(false);
+ const { resolvedTheme } = useTheme();
+ const isDark = resolvedTheme === "dark";
const copyToClipboard = React.useCallback(async () => {
await navigator.clipboard.writeText(code);
@@ -21,21 +54,32 @@ export function CodeSnippet({ code, language, className, ...props }: CodeSnippet
}, [code]);
return (
- <div className="relative">
- <pre
- className={cn(
- "overflow-x-auto rounded-lg border-neutral-500 bg-muted p-3 text-wrap font-mono text-sm",
- className
- )}
- {...props}
+ <div className={cn("relative border border-neutral-150 dark:border-neutral-800 rounded-md", className)}>
+ {showLanguageLabel && language && (
+ <div className="absolute left-3 top-2 text-xs text-neutral-400 z-10">{language}</div>
+ )}
+ <SyntaxHighlighter
+ language={language || "text"}
+ style={isDark ? vs2015 : vs}
+ customStyle={{
+ margin: 0,
+ borderRadius: "4px",
+ fontSize: "12px",
+ padding: showLanguageLabel ? "20px 10px 10px 10px" : "10px",
+ }}
+ wrapLongLines
+ >
+ {code}
+ </SyntaxHighlighter>
+ <Button
+ size="icon"
+ variant="ghost"
+ className="absolute right-2 top-2 h-6 w-6 text-neutral-400 hover:text-neutral-100 hover:bg-neutral-700"
+ onClick={copyToClipboard}
>
- {language && <div className="mb-1 text-xs text-muted-foreground">{language}</div>}
- <code className="relative rounded bg-muted p-0">{code}</code>
- </pre>
- <Button size="icon" variant="ghost" className="absolute right-3 top-3 h-6 w-6" onClick={copyToClipboard}>
{hasCopied ? <Check className="size-3" /> : <Copy className="size-3" />}
<span className="sr-only">Copy code</span>
</Button>
</div>
);
-}
+});
diff --git a/client/src/components/Sessions/SessionCard.tsx b/client/src/components/Sessions/SessionCard.tsx
index ec7132a25..90b11d8ef 100644
--- a/client/src/components/Sessions/SessionCard.tsx
+++ b/client/src/components/Sessions/SessionCard.tsx
@@ -3,7 +3,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip
import { ArrowRight, ChevronDown, ChevronRight } from "lucide-react";
import { DateTime } from "luxon";
import { memo, useState } from "react";
-import { GetSessionsResponse } from "../../api/analytics/useGetUserSessions";
+import { GetSessionsResponse } from "../../api/analytics/endpoints";
import { formatShortDuration, hour12, userLocale } from "../../lib/dateTimeUtils";
import { cn, formatter, getUserDisplayName } from "../../lib/utils";
import { Avatar } from "../Avatar";
diff --git a/client/src/components/Sessions/SessionDetails.tsx b/client/src/components/Sessions/SessionDetails.tsx
index 722d26963..1309de1e7 100644
--- a/client/src/components/Sessions/SessionDetails.tsx
+++ b/client/src/components/Sessions/SessionDetails.tsx
@@ -9,11 +9,8 @@ import { DateTime } from "luxon";
import Link from "next/link";
import { useParams } from "next/navigation";
import { memo, useMemo } from "react";
-import {
- GetSessionsResponse,
- SessionEvent,
- useGetSessionDetailsInfinite,
-} from "../../api/analytics/useGetUserSessions";
+import { useGetSessionDetailsInfinite } from "../../api/analytics/hooks/useGetUserSessions";
+import { GetSessionsResponse, SessionEvent } from "../../api/analytics/endpoints";
import { Browser } from "../../app/[site]/components/shared/icons/Browser";
import { CountryFlag } from "../../app/[site]/components/shared/icons/CountryFlag";
import { OperatingSystem } from "../../app/[site]/components/shared/icons/OperatingSystem";
diff --git a/client/src/components/Sessions/SessionsList.tsx b/client/src/components/Sessions/SessionsList.tsx
index be6ab06a5..f9c6870b6 100644
--- a/client/src/components/Sessions/SessionsList.tsx
+++ b/client/src/components/Sessions/SessionsList.tsx
@@ -1,5 +1,5 @@
import { ChevronLeft, ChevronRight, Rewind } from "lucide-react";
-import { GetSessionsResponse } from "../../api/analytics/useGetUserSessions";
+import { GetSessionsResponse } from "../../api/analytics/endpoints";
import { NothingFound } from "../NothingFound";
import { Button } from "../ui/button";
import { SessionCard, SessionCardSkeleton } from "./SessionCard";
diff --git a/client/src/components/SiteCard.tsx b/client/src/components/SiteCard.tsx
index d6a11f66f..790924c9c 100644
--- a/client/src/components/SiteCard.tsx
+++ b/client/src/components/SiteCard.tsx
@@ -1,10 +1,9 @@
import { ArrowRight } from "lucide-react";
import Link from "next/link";
import { useRef } from "react";
-import { useGetOverview } from "../api/analytics/useGetOverview";
-import { useGetOverviewBucketed } from "../api/analytics/useGetOverviewBucketed";
+import { useGetOverview } from "../api/analytics/hooks/useGetOverview";
+import { useGetOverviewBucketed } from "../api/analytics/hooks/useGetOverviewBucketed";
import { useInView } from "../hooks/useInView";
-import { MINUTES_IN_24_HOURS } from "../lib/const";
import { Favicon } from "./Favicon";
import { SiteSessionChart } from "./SiteSessionChart";
import { Button } from "./ui/button";
diff --git a/client/src/components/SiteSessionChart.tsx b/client/src/components/SiteSessionChart.tsx
index c82610645..10371fad3 100644
--- a/client/src/components/SiteSessionChart.tsx
+++ b/client/src/components/SiteSessionChart.tsx
@@ -2,7 +2,7 @@ import { useNivoTheme } from "@/lib/nivo";
import { ResponsiveLine } from "@nivo/line";
import { DateTime } from "luxon";
import { useMemo } from "react";
-import { GetOverviewBucketedResponse } from "../api/analytics/useGetOverviewBucketed";
+import { GetOverviewBucketedResponse } from "../api/analytics/endpoints";
import { hour12 } from "../lib/dateTimeUtils";
import { formatter } from "../lib/utils";
import { ChartTooltip } from "./charts/ChartTooltip";
diff --git a/client/src/components/SpinningGlobe.tsx b/client/src/components/SpinningGlobe.tsx
index 1f4226d52..ae24e62ea 100644
--- a/client/src/components/SpinningGlobe.tsx
+++ b/client/src/components/SpinningGlobe.tsx
@@ -5,7 +5,7 @@ import mapboxgl from "mapbox-gl";
import "mapbox-gl/dist/mapbox-gl.css";
import { useEffect, useRef, useState } from "react";
import { useQuery } from "@tanstack/react-query";
-import type { GetSessionsResponse } from "../api/analytics/useGetUserSessions";
+import type { GetSessionsResponse } from "../api/analytics/endpoints";
import { useConfigs } from "../lib/configs";
import "../app/[site]/globe/globe.css";
diff --git a/client/src/components/UsageChart.tsx b/client/src/components/UsageChart.tsx
index 2dd2cda59..dd7c5e6cd 100644
--- a/client/src/components/UsageChart.tsx
+++ b/client/src/components/UsageChart.tsx
@@ -3,7 +3,7 @@ import { useNivoTheme } from "@/lib/nivo";
import { ResponsiveLine } from "@nivo/line";
import { useWindowSize } from "@uidotdev/usehooks";
import { DateTime } from "luxon";
-import { useGetOrgEventCount } from "../api/analytics/useGetOrgEventCount";
+import { useGetOrgEventCount } from "../api/analytics/hooks/useGetOrgEventCount";
import { userLocale } from "../lib/dateTimeUtils";
import { formatter } from "../lib/utils";
import { Badge } from "./ui/badge";
@@ -26,7 +26,6 @@ export function UsageChart({ organizationId, startDate, endDate, timeZone = "UTC
startDate,
endDate,
timeZone,
- enabled: !!organizationId,
});
const maxTicks = Math.round((width ?? Infinity) / 200);
diff --git a/client/src/components/ui/input.tsx b/client/src/components/ui/input.tsx
index 18219257b..7238e71ac 100644
--- a/client/src/components/ui/input.tsx
+++ b/client/src/components/ui/input.tsx
@@ -5,7 +5,7 @@ import { Search } from "lucide-react";
import { cn } from "@/lib/utils";
const inputVariants = cva(
- "flex w-full rounded-md border border-neutral-200 bg-transparent shadow-sm transition-colors file:border-0 file:bg-transparent file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300",
+ "flex w-full rounded-lg border border-neutral-150 bg-transparent transition-colors file:border-0 file:bg-transparent file:font-medium file:text-neutral-950 placeholder:text-neutral-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-neutral-950 disabled:cursor-not-allowed disabled:opacity-50 dark:border-neutral-800 dark:file:text-neutral-50 dark:placeholder:text-neutral-400 dark:focus-visible:ring-neutral-300",
{
variants: {
inputSize: {
diff --git a/docs/content/docs/api/stats/users.mdx b/docs/content/docs/api/stats/users.mdx
index b8da00d34..9d1b36dc6 100644
--- a/docs/content/docs/api/stats/users.mdx
+++ b/docs/content/docs/api/stats/users.mdx
@@ -344,285 +344,6 @@ var data = await response.Content.ReadAsStringAsync();
---
-## Get User Sessions
-
-<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
-<div>
-
-```
-GET /api/users/:userId/sessions/:site
-```
-
-Returns all sessions for a specific user, grouped with their pageviews. Useful for viewing a user's browsing history and behavior patterns.
-
-### Path Parameters
-
-<TypeTable
- type={{
- userId: {
- description: 'User ID (device fingerprint or identified user ID)',
- type: 'string',
- required: true,
- },
- site: {
- description: 'Site ID or site identifier',
- type: 'string | number',
- required: true,
- },
- }}
-/>
-
-### Query Parameters
-
-Accepts all [Common Parameters](/docs/api/stats/getting-started#common-parameters) (time and filters).
-
-### Response
-
-<TypeTable
- type={{
- data: {
- description: 'Array of session objects',
- type: 'Session[]',
- },
- }}
-/>
-
-#### Session Object
-
-<TypeTable
- type={{
- session_id: {
- description: 'Unique session identifier',
- type: 'string',
- },
- browser: {
- description: 'Browser name',
- type: 'string',
- },
- operating_system: {
- description: 'Operating system name',
- type: 'string',
- },
- device_type: {
- description: 'Device type',
- type: 'string',
- },
- country: {
- description: 'Country code',
- type: 'string',
- },
- firstTimestamp: {
- description: 'Session start time',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
- },
- lastTimestamp: {
- description: 'Session end time',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
- },
- duration: {
- description: 'Session duration in seconds',
- type: 'number',
- },
- pageviews: {
- description: 'Array of pageviews in this session',
- type: 'Pageview[]',
- },
- }}
-/>
-
-#### Pageview Object
-
-<TypeTable
- type={{
- pathname: {
- description: 'Page path',
- type: 'string',
- },
- querystring: {
- description: 'Query string parameters',
- type: 'string',
- },
- title: {
- description: 'Page title',
- type: 'string',
- },
- timestamp: {
- description: 'Pageview timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
- },
- referrer: {
- description: 'Referrer URL',
- type: 'string',
- },
- }}
-/>
-
-</div>
-<div className="flex flex-col gap-4">
-
-<Tabs items={['cURL', 'JavaScript', 'Python', 'PHP', 'Ruby', 'Go', 'Rust', 'Java', '.NET']}>
- <Tab value="cURL">
-```bash title="Request"
-curl -X GET "https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31" \
- -H "Authorization: Bearer your_api_key_here"
-```
- </Tab>
- <Tab value="JavaScript">
-```javascript title="Request"
-const response = await fetch(
- 'https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31',
- {
- headers: {
- 'Authorization': 'Bearer your_api_key_here'
- }
- }
-);
-
-const data = await response.json();
-```
- </Tab>
- <Tab value="Python">
-```python title="Request"
-import requests
-
-response = requests.get(
- 'https://api.rybbit.io/api/users/abc123def456/sessions/123',
- params={
- 'start_date': '2024-01-01',
- 'end_date': '2024-01-31'
- },
- headers={
- 'Authorization': 'Bearer your_api_key_here'
- }
-)
-
-data = response.json()
-```
- </Tab>
- <Tab value="PHP">
-```php title="Request"
-$ch = curl_init();
-curl_setopt($ch, CURLOPT_URL, 'https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31');
-curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Authorization: Bearer your_api_key_here'
-]);
-
-$response = curl_exec($ch);
-curl_close($ch);
-
-$data = json_decode($response, true);
-```
- </Tab>
- <Tab value="Ruby">
-```ruby title="Request"
-require 'net/http'
-require 'json'
-
-uri = URI('https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31')
-req = Net::HTTP::Get.new(uri)
-req['Authorization'] = 'Bearer your_api_key_here'
-
-res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
-data = JSON.parse(res.body)
-```
- </Tab>
- <Tab value="Go">
-```go title="Request"
-req, _ := http.NewRequest("GET", "https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31", nil)
-req.Header.Set("Authorization", "Bearer your_api_key_here")
-
-client := &http.Client{}
-resp, _ := client.Do(req)
-defer resp.Body.Close()
-
-var data map[string]interface{}
-json.NewDecoder(resp.Body).Decode(&data)
-```
- </Tab>
- <Tab value="Rust">
-```rust title="Request"
-let client = reqwest::Client::new();
-let res = client
- .get("https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31")
- .header("Authorization", "Bearer your_api_key_here")
- .send()
- .await?;
-
-let data: serde_json::Value = res.json().await?;
-```
- </Tab>
- <Tab value="Java">
-```java title="Request"
-HttpClient client = HttpClient.newHttpClient();
-HttpRequest request = HttpRequest.newBuilder()
- .uri(URI.create("https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31"))
- .header("Authorization", "Bearer your_api_key_here")
- .GET()
- .build();
-
-HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
-```
- </Tab>
- <Tab value=".NET">
-```csharp title="Request"
-using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
-
-var response = await client.GetAsync("https://api.rybbit.io/api/users/abc123def456/sessions/123?start_date=2024-01-01&end_date=2024-01-31");
-var data = await response.Content.ReadAsStringAsync();
-```
- </Tab>
-</Tabs>
-
-```json title="Response"
-{
- "data": [
- {
- "session_id": "sess_abc123",
- "browser": "Chrome",
- "operating_system": "macOS",
- "device_type": "desktop",
- "country": "US",
- "firstTimestamp": "2024-01-31T14:00:00.000Z",
- "lastTimestamp": "2024-01-31T14:22:00.000Z",
- "duration": 1320,
- "pageviews": [
- {
- "pathname": "/pricing",
- "querystring": "",
- "title": "Pricing - Example",
- "timestamp": "2024-01-31T14:22:00.000Z",
- "referrer": ""
- },
- {
- "pathname": "/features",
- "querystring": "",
- "title": "Features - Example",
- "timestamp": "2024-01-31T14:10:00.000Z",
- "referrer": ""
- },
- {
- "pathname": "/",
- "querystring": "utm_source=google",
- "title": "Home - Example",
- "timestamp": "2024-01-31T14:00:00.000Z",
- "referrer": "https://google.com"
- }
- ]
- }
- ]
-}
-```
-
-</div>
-</div>
-
----
-
## Get User Session Count
<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
diff --git a/server/src/api/analytics/getOverviewBucketed.ts b/server/src/api/analytics/getOverviewBucketed.ts
index 4006ef3a6..1558a1bae 100644
--- a/server/src/api/analytics/getOverviewBucketed.ts
+++ b/server/src/api/analytics/getOverviewBucketed.ts
@@ -67,7 +67,7 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
}
const getQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const { start_date, end_date, time_zone, bucket, filters, past_minutes_start, past_minutes_end } = params;
+ const { start_date, end_date, time_zone, bucket = "hour", filters, past_minutes_start, past_minutes_end } = params;
const timeStatement = getTimeStatement(params);
const filterStatement = getFilterStatement(filters, siteId, timeStatement);
diff --git a/server/src/api/analytics/getSessions.ts b/server/src/api/analytics/getSessions.ts
index 3b72e3ac9..a287deba0 100644
--- a/server/src/api/analytics/getSessions.ts
+++ b/server/src/api/analytics/getSessions.ts
@@ -57,7 +57,7 @@ export interface GetSessionsRequest {
}
export async function getSessions(req: FastifyRequest<GetSessionsRequest>, res: FastifyReply) {
- const { filters, page, user_id: userId, limit, identified_only: identifiedOnly = "false" } = req.query;
+ const { filters, page = 1, user_id: userId, limit = 100, identified_only: identifiedOnly = "false" } = req.query;
const site = req.params.site;
const filterIdentified = identifiedOnly === "true";
diff --git a/server/src/api/analytics/getUserSessions.ts b/server/src/api/analytics/getUserSessions.ts
deleted file mode 100644
index 14fc17f34..000000000
--- a/server/src/api/analytics/getUserSessions.ts
+++ /dev/null
@@ -1,159 +0,0 @@
-import { FilterParams } from "@rybbit/shared";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { clickhouse } from "../../db/clickhouse/clickhouse.js";
-import { getTimeStatement, processResults } from "./utils/utils.js";
-import { getFilterStatement } from "./utils/getFilterStatement.js";
-
-// Individual pageview type
-type Pageview = {
- session_id: string;
- timestamp: string;
- pathname: string;
- querystring: string;
- page_title: string;
- referrer: string;
- browser: string;
- operating_system: string;
- device_type: string;
- country: string;
-};
-
-// Grouped session type to be returned to the client
-type GroupedSession = {
- session_id: string;
- browser: string;
- operating_system: string;
- device_type: string;
- country: string;
- firstTimestamp: string;
- lastTimestamp: string;
- duration: number; // Duration in seconds
- pageviews: {
- pathname: string;
- querystring: string;
- title: string;
- timestamp: string;
- referrer: string;
- }[];
-};
-
-export interface GetUserSessionsRequest {
- Querystring: FilterParams<{
- site: string;
- }>;
- Params: {
- userId: string;
- };
-}
-
-export async function getUserSessions(req: FastifyRequest<GetUserSessionsRequest>, res: FastifyReply) {
- const { site, filters } = req.query;
- const userId = req.params.userId;
-
- const timeStatement = getTimeStatement(req.query);
- const filterStatement = getFilterStatement(filters, Number(site), timeStatement);
-
- const query = `
-SELECT
- session_id,
- timestamp,
- pathname,
- querystring,
- page_title,
- referrer,
- browser,
- operating_system,
- device_type,
- country,
- region
-FROM events
-WHERE
- site_id = {siteId:Int32}
- AND (events.identified_user_id = {userId:String} OR events.user_id = {userId:String})
- ${filterStatement}
- ${timeStatement}
-ORDER BY timestamp ASC
- `;
-
- try {
- const result = await clickhouse.query({
- query,
- format: "JSONEachRow",
- query_params: {
- siteId: Number(site),
- userId,
- },
- });
-
- const pageviews = await processResults<Pageview>(result);
-
- // Group pageviews by session
- const sessions: Record<string, GroupedSession> = {};
-
- pageviews.forEach(pageview => {
- const {
- session_id,
- timestamp,
- pathname,
- querystring,
- page_title,
- referrer,
- browser,
- operating_system,
- device_type,
- country,
- } = pageview;
-
- if (!sessions[session_id]) {
- sessions[session_id] = {
- session_id,
- browser,
- operating_system,
- device_type,
- country,
- firstTimestamp: timestamp,
- lastTimestamp: timestamp,
- duration: 0, // Initialize duration
- pageviews: [],
- };
- }
-
- // Update timestamps
- if (timestamp < sessions[session_id].firstTimestamp) {
- sessions[session_id].firstTimestamp = timestamp;
- }
- if (timestamp > sessions[session_id].lastTimestamp) {
- sessions[session_id].lastTimestamp = timestamp;
- }
-
- // Add pageview with separate pathname and querystring
- sessions[session_id].pageviews.push({
- pathname,
- querystring,
- title: page_title,
- timestamp,
- referrer,
- });
-
- // Sort pageviews by timestamp in descending order
- sessions[session_id].pageviews.sort((a, b) => new Date(b.timestamp).getTime() - new Date(a.timestamp).getTime());
- });
-
- // Calculate duration for each session and convert to array
- const groupedSessions = Object.values(sessions)
- .map(session => {
- // Calculate duration in seconds
- const firstTime = new Date(session.firstTimestamp).getTime();
- const lastTime = new Date(session.lastTimestamp).getTime();
- session.duration = Math.round((lastTime - firstTime) / 1000);
-
- return session;
- })
- .sort((a, b) => new Date(b.lastTimestamp).getTime() - new Date(a.lastTimestamp).getTime());
-
- return res.send({ data: groupedSessions });
- } catch (error) {
- console.error("Error fetching user sessions:", error);
- return res.status(500).send({ error: "Failed to fetch user sessions" });
- }
-}
diff --git a/server/src/api/analytics/getUsers.ts b/server/src/api/analytics/getUsers.ts
index cc4e30380..397fedaca 100644
--- a/server/src/api/analytics/getUsers.ts
+++ b/server/src/api/analytics/getUsers.ts
@@ -40,7 +40,7 @@ export async function getUsers(req: FastifyRequest<GetUsersRequest>, res: Fastif
const {
filters,
page = "1",
- page_size: pageSize = "20",
+ page_size: pageSize = "100",
sort_by: sortBy = "last_seen",
sort_order: sortOrder = "desc",
identified_only: identifiedOnly = "false",
diff --git a/server/src/api/analytics/goals/createGoal.ts b/server/src/api/analytics/goals/createGoal.ts
index 6d4c28d7a..2405783af 100644
--- a/server/src/api/analytics/goals/createGoal.ts
+++ b/server/src/api/analytics/goals/createGoal.ts
@@ -30,10 +30,9 @@ const eventConfigSchema = z
}
);
-// Define validation schema for the goal request
-const goalSchema = z
+// Define validation schema for the goal request body
+const goalBodySchema = z
.object({
- siteId: z.number().int().positive("Site ID must be a positive integer"),
name: z.string().optional(),
goalType: z.enum(["path", "event"]),
config: z.object({
@@ -58,18 +57,25 @@ const goalSchema = z
}
);
-type CreateGoalRequest = z.infer<typeof goalSchema>;
+type CreateGoalBody = z.infer<typeof goalBodySchema>;
export async function createGoal(
request: FastifyRequest<{
- Body: CreateGoalRequest;
+ Params: { site: string };
+ Body: CreateGoalBody;
}>,
reply: FastifyReply
) {
try {
+ // Get siteId from URL params
+ const siteId = parseInt(request.params.site, 10);
+ if (isNaN(siteId) || siteId <= 0) {
+ return reply.status(400).send({ error: "Invalid site ID" });
+ }
+
// Validate the request body
- const validatedData = goalSchema.parse(request.body);
- const { siteId, name, goalType, config } = validatedData;
+ const validatedData = goalBodySchema.parse(request.body);
+ const { name, goalType, config } = validatedData;
// Check user access to site
const userHasAccessToSite = await getUserHasAccessToSite(request, siteId.toString());
diff --git a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
index c218184e8..89f77c8aa 100644
--- a/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
+++ b/server/src/api/analytics/performance/getPerformanceTimeSeries.ts
@@ -67,7 +67,7 @@ function getTimeStatementFill(params: FilterParams, bucket: TimeBucket) {
}
const getQuery = (params: FilterParams<{ bucket: TimeBucket }>, siteId: number) => {
- const { start_date, end_date, time_zone, bucket, filters, past_minutes_start, past_minutes_end } = params;
+ const { start_date, end_date, time_zone, bucket = "hour", filters, past_minutes_start, past_minutes_end } = params;
const timeStatement = getTimeStatement(params);
const filterStatement = getFilterStatement(filters, siteId, timeStatement);
diff --git a/server/src/index.ts b/server/src/index.ts
index f7b09e374..e0f6a3b6b 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -33,7 +33,6 @@ import { getSessions } from "./api/analytics/getSessions.js";
import { getMetric } from "./api/analytics/getMetric.js";
import { getUserInfo } from "./api/analytics/getUserInfo.js";
import { getUserSessionCount } from "./api/analytics/getUserSessionCount.js";
-import { getUserSessions } from "./api/analytics/getUserSessions.js";
import { getUsers } from "./api/analytics/getUsers.js";
import { createGoal } from "./api/analytics/goals/createGoal.js";
import { deleteGoal } from "./api/analytics/goals/deleteGoal.js";
@@ -340,7 +339,6 @@ server.get("/api/sessions/:site", getSessions);
server.get("/api/sessions/:sessionId/:site", getSession);
server.get("/api/events/:site", getEvents);
server.get("/api/users/:site", getUsers);
-server.get("/api/users/:userId/sessions/:site", getUserSessions);
server.get("/api/users/session-count/:site", getUserSessionCount);
server.get("/api/users/:userId/:site", getUserInfo);
server.get("/api/session-locations/:site", getSessionLocations);