Skip to content

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

docs(api): correct the API reference and add missing endpoints (#1341)

Goldflaga6b473356980
diff --git a/docs/content/docs/api/annotations/delete.mdx b/docs/content/docs/api/annotations/delete.mdx
index 27300a452..61b5e25b6 100644
--- a/docs/content/docs/api/annotations/delete.mdx
+++ b/docs/content/docs/api/annotations/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/annotations/:annotationId
```
-Deletes an annotation. Admins and owners can delete any annotation on their sites; members can delete only the annotations they created.
+Deletes an annotation. An editor or above can delete any annotation on the site, including through a per-site editor grant. Members and per-site members can delete only the annotations they created. Organization-wide annotations can only be deleted by someone with the editor role or above in the organization, even if they created the annotation. Returns `403` when you may not delete it and `404` when it does not exist on this site.
### Path Parameters
diff --git a/docs/content/docs/api/annotations/update.mdx b/docs/content/docs/api/annotations/update.mdx
index 10c7e9ddd..205d578b2 100644
--- a/docs/content/docs/api/annotations/update.mdx
+++ b/docs/content/docs/api/annotations/update.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:site/annotations/:annotationId
```
-Partial update: only the fields you send change. Editors, admins and owners can edit any annotation on their sites; members can edit only the annotations they created. Changing `scope` needs the editor role or above in the organization.
+Partial update: only the fields you send change. Editors and above can edit any annotation on the site, including through a per-site editor grant; members can edit only the annotations they created. Organization-wide annotations, and changing `scope`, need the editor role or above in the organization, even for the annotation's creator.
### Path Parameters
diff --git a/docs/content/docs/api/api-keys/create-org.mdx b/docs/content/docs/api/api-keys/create-org.mdx
index 5a8054e89..2ebb8a41d 100644
--- a/docs/content/docs/api/api-keys/create-org.mdx
+++ b/docs/content/docs/api/api-keys/create-org.mdx
@@ -18,7 +18,7 @@ POST /api/organizations/:organizationId/api-keys
Creates an API key **owned by the organization itself**, rather than by your user account. The key authenticates as the organization (org-admin authority over its sites), so it survives member departures, and its plan gating, [rate limits](/docs/api/getting-started#rate-limits-cloud-only), and key-count limit all follow the owning organization's subscription. Organization keys are issued with the `rb_org_` prefix.
-<Callout type="warn">You must be an **owner or admin** of the target organization. This endpoint accepts your dashboard **session** or an **unrestricted (full-access) user API key** β€” scoped keys and organization keys are rejected, so an organization key cannot mint other keys.</Callout>
+<Callout type="warn">You must be an **owner or admin** of the target organization. This endpoint accepts your dashboard **session** or an **unrestricted (full-access) personal API key**. Scoped keys and organization keys get `403` with `"Insufficient scope"`, so an organization key cannot mint other keys.</Callout>
### Path Parameters
@@ -37,23 +37,25 @@ Creates an API key **owned by the organization itself**, rather than by your use
<TypeTable
type={{
name: {
- description: 'A label for the key',
+ description: 'A label for the key, 1 to 32 characters',
type: 'string',
required: true,
},
expiresIn: {
- description: 'Seconds until the key expires. Omit for a key that never expires.',
+ description: 'Seconds until the key expires, from 86,400 (1 day) to 31,536,000 (365 days). Omit for a key that never expires.',
type: 'number',
required: false,
},
permissions: {
- description: 'Scope the key to specific `resource: action[]` pairs (e.g. `{ "analytics": ["read"], "goals": ["read", "write"] }`). Omit entirely for a full-access key.',
+ description: 'Scope the key to specific `resource: action[]` pairs (e.g. `{ "analytics": ["read"], "goals": ["read", "write"] }`); see the note below this table. Omit entirely for a full-access key; an empty object is rejected.',
type: 'object',
required: false,
},
}}
/>
+Scopes use the `resource:action` taxonomy listed under [Roles and Scopes](/docs/api/getting-started#scopes). Per-key limits don't apply; usage counts against the owner's [rate limits](/docs/api/getting-started#rate-limits-cloud-only).
+
### Response
Returns the created API key object. The full `key` value carries the `rb_org_` prefix.
@@ -73,7 +75,7 @@ Returns the created API key object. The full `key` value carries the `rb_org_` p
type: 'string',
},
start: {
- description: 'A non-secret prefix of the key for display',
+ description: 'The first 6 characters of the key ("rb_org"), for display',
type: 'string',
},
prefix: {
@@ -84,10 +86,18 @@ Returns the created API key object. The full `key` value carries the `rb_org_` p
description: 'The ID of the organization that owns the key',
type: 'string',
},
- userId: {
- description: 'The ID of the admin/owner who created the key',
+ configId: {
+ description: 'Key configuration: always "org" for organization keys',
type: 'string',
},
+ metadata: {
+ description: '`{ createdBy }`: the ID of the admin or owner who created the key',
+ type: 'object',
+ },
+ permissions: {
+ description: 'The scopes the key was given, or null for a full-access key',
+ type: 'object | null',
+ },
enabled: {
description: 'Whether the key is currently enabled',
type: 'boolean',
@@ -105,15 +115,15 @@ Returns the created API key object. The full `key` value carries the `rb_org_` p
type: 'string',
},
rateLimitEnabled: {
- description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only))',
+ description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see Rate Limits in Getting Started)',
type: 'boolean',
},
rateLimitMax: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number',
},
rateLimitTimeWindow: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number',
},
}}
@@ -128,7 +138,7 @@ Returns the created API key object. The full `key` value carries the `rb_org_` p
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/organizations/org_123/api-keys" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
-H "Content-Type: application/json" \
-d '{"name": "CI pipeline", "expiresIn": 2592000}'
```
@@ -164,7 +174,7 @@ response = requests.post(
'expiresIn': 2592000
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
}
)
@@ -182,7 +192,7 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'expiresIn' => 2592000
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
'Content-Type: application/json'
]);
@@ -199,7 +209,7 @@ require 'json'
uri = URI("https://app.rybbit.io/api/organizations/org_123/api-keys")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
req['Content-Type'] = 'application/json'
req.body = {
name: 'CI pipeline',
@@ -217,7 +227,7 @@ body := bytes.NewBuffer([]byte(`{
"expiresIn": 2592000
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/organizations/org_123/api-keys", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -233,7 +243,7 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/organizations/org_123/api-keys")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.json(&serde_json::json!({
"name": "CI pipeline",
"expiresIn": 2592000
@@ -250,7 +260,7 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"name\": \"CI pipeline\", \"expiresIn\": 2592000}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/organizations/org_123/api-keys"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -261,7 +271,7 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
var content = new StringContent(
"{\"name\": \"CI pipeline\", \"expiresIn\": 2592000}",
@@ -280,12 +290,14 @@ var data = await response.Content.ReadAsStringAsync();
```json title="Response"
{
"id": "key_8f3a1b2c4d5e6f7g",
- "key": "rb_org_xxxxxxxxxxxxxxxxxxxx",
+ "key": "rb_org_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"name": "CI pipeline",
- "start": "rb_org_xxxx",
+ "start": "rb_org",
"prefix": "rb_org_",
"referenceId": "org_123",
- "userId": "user_2a9b8c7d6e5f4g3h",
+ "configId": "org",
+ "metadata": { "createdBy": "user_2a9b8c7d6e5f4g3h" },
+ "permissions": null,
"enabled": true,
"expiresAt": "2026-07-25T12:00:00.000Z",
"createdAt": "2026-06-25T12:00:00.000Z",
diff --git a/docs/content/docs/api/api-keys/create.mdx b/docs/content/docs/api/api-keys/create.mdx
index 0cadbdbe3..7956ce638 100644
--- a/docs/content/docs/api/api-keys/create.mdx
+++ b/docs/content/docs/api/api-keys/create.mdx
@@ -18,25 +18,32 @@ POST /api/user/api-keys
Creates a new API key scoped to your user account (and its organizations). To create a key owned by an organization instead, see [Create Organization API Key](/docs/api/api-keys/create-org).
-<Callout type="warn">This endpoint accepts your logged-in dashboard **session** or an **unrestricted (full-access) user API key**. Scoped keys and organization keys are rejected β€” so a scoped key cannot mint new keys, but a session or full-access key can. Send your session cookie or `Authorization: Bearer` header with the request.</Callout>
+<Callout type="warn">This endpoint accepts only your logged-in dashboard **session**. API keys can't create keys: any API key gets `401`. Send your session cookie with the request. On Rybbit Cloud the session must have an active organization (the one you last opened in the dashboard), or the request returns `400` with `"No active organization"`; its plan decides whether you can create keys.</Callout>
### Request Body
<TypeTable
type={{
name: {
- description: 'A label for the key',
+ description: 'A label for the key, 1 to 32 characters',
type: 'string',
required: true,
},
expiresIn: {
- description: 'Seconds until the key expires. Omit for a key that never expires.',
+ description: 'Seconds until the key expires, from 86,400 (1 day) to 31,536,000 (365 days). Omit for a key that never expires.',
type: 'number',
required: false,
},
+ permissions: {
+ description: 'Scope the key to specific `resource: action[]` pairs (e.g. `{ "analytics": ["read"], "goals": ["read", "write"] }`); see the note below this table. Omit entirely for a full-access key; an empty object is rejected.',
+ type: 'object',
+ required: false,
+ },
}}
/>
+Scopes use the `resource:action` taxonomy listed under [Roles and Scopes](/docs/api/getting-started#scopes). Per-key limits don't apply; usage counts against the owner's [rate limits](/docs/api/getting-started#rate-limits-cloud-only).
+
### Response
Returns the created API key object.
@@ -56,17 +63,25 @@ Returns the created API key object.
type: 'string',
},
start: {
- description: 'A non-secret prefix of the key for display',
+ description: 'The first 6 characters of the key, for display',
type: 'string',
},
prefix: {
- description: 'The key prefix',
- type: 'string',
+ description: 'The key prefix. Personal keys have none, so this is null',
+ type: 'string | null',
},
- userId: {
+ referenceId: {
description: 'The ID of the user that owns the key',
type: 'string',
},
+ configId: {
+ description: 'Key configuration: "default" for personal keys',
+ type: 'string',
+ },
+ permissions: {
+ description: 'The scopes the key was given, or null for a full-access key',
+ type: 'object | null',
+ },
enabled: {
description: 'Whether the key is currently enabled',
type: 'boolean',
@@ -84,15 +99,15 @@ Returns the created API key object.
type: 'string',
},
rateLimitEnabled: {
- description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only))',
+ description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see Rate Limits in Getting Started)',
type: 'boolean',
},
rateLimitMax: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number',
},
rateLimitTimeWindow: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number',
},
}}
@@ -107,9 +122,9 @@ Returns the created API key object.
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/user/api-keys" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
-H "Content-Type: application/json" \
- -d '{"name": "CI pipeline", "expiresIn": 2592000}'
+ -d '{"name": "CI pipeline", "expiresIn": 2592000, "permissions": {"analytics": ["read"]}}'
```
</Tab>
<Tab value="JavaScript">
@@ -143,7 +158,7 @@ response = requests.post(
'expiresIn': 2592000
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
}
)
@@ -161,7 +176,7 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'expiresIn' => 2592000
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
'Content-Type: application/json'
]);
@@ -178,7 +193,7 @@ require 'json'
uri = URI("https://app.rybbit.io/api/user/api-keys")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
req['Content-Type'] = 'application/json'
req.body = {
name: 'CI pipeline',
@@ -196,7 +211,7 @@ body := bytes.NewBuffer([]byte(`{
"expiresIn": 2592000
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/user/api-keys", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -212,7 +227,7 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/user/api-keys")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.json(&serde_json::json!({
"name": "CI pipeline",
"expiresIn": 2592000
@@ -229,7 +244,7 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"name\": \"CI pipeline\", \"expiresIn\": 2592000}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/user/api-keys"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -240,7 +255,7 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
var content = new StringContent(
"{\"name\": \"CI pipeline\", \"expiresIn\": 2592000}",
@@ -259,11 +274,14 @@ var data = await response.Content.ReadAsStringAsync();
```json title="Response"
{
"id": "key_8f3a1b2c4d5e6f7g",
- "key": "rybbit_sk_live_xxxxxxxxxxxxxxxxxxxx",
+ "key": "aBcDeFxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
"name": "CI pipeline",
- "start": "rybbit_sk_live_xxxx",
- "prefix": "rybbit_sk_live_",
- "userId": "user_2a9b8c7d6e5f4g3h",
+ "start": "aBcDeF",
+ "prefix": null,
+ "referenceId": "user_2a9b8c7d6e5f4g3h",
+ "configId": "default",
+ "permissions": { "analytics": ["read"] },
+ "metadata": null,
"enabled": true,
"expiresAt": "2026-07-25T12:00:00.000Z",
"createdAt": "2026-06-25T12:00:00.000Z",
diff --git a/docs/content/docs/api/api-keys/delete.mdx b/docs/content/docs/api/api-keys/delete.mdx
index c0b3dcce7..489edfe02 100644
--- a/docs/content/docs/api/api-keys/delete.mdx
+++ b/docs/content/docs/api/api-keys/delete.mdx
@@ -20,7 +20,7 @@ Revokes (deletes) an existing API key. The key is identified by its `keyId`.
<Callout type="warn">This endpoint uses **POST**, not HTTP DELETE. Revoking a key is immediate and permanent β€” any client still using it will start receiving 401 responses.</Callout>
-<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie with the request.</Callout>
+<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie and an `Origin` header with the request. To delete an organization key, pass `"configId": "org"`; without it the key is not found (`404`). Managing organization keys requires the owner or admin role.</Callout>
### Request Body
@@ -31,6 +31,11 @@ Revokes (deletes) an existing API key. The key is identified by its `keyId`.
type: 'string',
required: true,
},
+ configId: {
+ description: 'Set to "org" for an organization key. Omit for a personal key.',
+ type: 'string',
+ required: false,
+ },
}}
/>
@@ -54,7 +59,8 @@ Returns a success flag.
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/auth/api-key/delete" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Origin: https://app.rybbit.io" \
-H "Content-Type: application/json" \
-d '{"keyId": "key_8f3a1b2c4d5e6f7g"}'
```
@@ -88,7 +94,8 @@ response = requests.post(
'keyId': 'key_8f3a1b2c4d5e6f7g'
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin': 'https://app.rybbit.io'
}
)
@@ -105,7 +112,8 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'keyId' => 'key_8f3a1b2c4d5e6f7g'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin: https://app.rybbit.io',
'Content-Type: application/json'
]);
@@ -122,7 +130,8 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/api-key/delete")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Origin'] = 'https://app.rybbit.io'
req['Content-Type'] = 'application/json'
req.body = {
keyId: 'key_8f3a1b2c4d5e6f7g'
@@ -138,7 +147,8 @@ body := bytes.NewBuffer([]byte(`{
"keyId": "key_8f3a1b2c4d5e6f7g"
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/auth/api-key/delete", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Origin", "https://app.rybbit.io")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -154,7 +164,8 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/auth/api-key/delete")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.json(&serde_json::json!({
"keyId": "key_8f3a1b2c4d5e6f7g"
}))
@@ -170,7 +181,8 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"keyId\": \"key_8f3a1b2c4d5e6f7g\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/api-key/delete"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -181,7 +193,8 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Origin", "https://app.rybbit.io");
var content = new StringContent(
"{\"keyId\": \"key_8f3a1b2c4d5e6f7g\"}",
diff --git a/docs/content/docs/api/api-keys/list.mdx b/docs/content/docs/api/api-keys/list.mdx
index e88e1073a..8cc7ff57a 100644
--- a/docs/content/docs/api/api-keys/list.mdx
+++ b/docs/content/docs/api/api-keys/list.mdx
@@ -25,7 +25,12 @@ Returns all API keys owned by the authenticated user, or by a specific organizat
<TypeTable
type={{
organizationId: {
- description: 'Organization ID. If provided, returns organization-owned keys instead of your user-owned keys.',
+ description: 'Organization ID. If provided, returns that organization\'s keys instead of your personal keys. Requires the owner or admin role in the organization.',
+ type: 'string',
+ required: false,
+ },
+ configId: {
+ description: 'Only return keys of this configuration: "default" (personal) or "org" (organization).',
type: 'string',
required: false,
},
@@ -95,8 +100,12 @@ Returns all API keys owned by the authenticated user, or by a specific organizat
description: 'The key prefix',
type: 'string | null',
},
- userId: {
- description: 'ID of the user that owns the key',
+ referenceId: {
+ description: 'Owner of the key: your user ID for personal keys, the organization ID for organization keys',
+ type: 'string',
+ },
+ configId: {
+ description: '"default" for personal keys, "org" for organization keys',
type: 'string',
},
enabled: {
@@ -116,15 +125,15 @@ Returns all API keys owned by the authenticated user, or by a specific organizat
type: 'string',
},
rateLimitEnabled: {
- description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only))',
+ description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see Rate Limits in Getting Started)',
type: 'boolean',
},
rateLimitMax: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number | null',
},
rateLimitTimeWindow: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number | null',
},
requestCount: {
@@ -140,16 +149,18 @@ Returns all API keys owned by the authenticated user, or by a specific organizat
type: 'string | null',
},
metadata: {
- description: 'Extra metadata stored on the key',
+ description: 'Organization keys: `{ createdBy }`, the user who created the key. Null for personal keys',
type: 'object | null',
},
permissions: {
- description: 'Permissions associated with the key',
+ description: 'The scopes the key was given, or null for a full-access key',
type: 'object | null',
},
}}
/>
+The `rateLimit*` fields are unused: limits apply per credential owner, see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only).
+
</div>
<div className="flex flex-col gap-4">
@@ -157,7 +168,7 @@ Returns all API keys owned by the authenticated user, or by a specific organizat
<Tab value="cURL">
```bash title="Request"
curl -X GET "https://app.rybbit.io/api/auth/api-key/list?limit=20" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN"
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN"
```
</Tab>
<Tab value="JavaScript">
@@ -180,7 +191,7 @@ import requests
response = requests.get(
'https://app.rybbit.io/api/auth/api-key/list?limit=20',
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
}
)
@@ -193,7 +204,7 @@ $ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.rybbit.io/api/auth/api-key/list?limit=20");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
]);
$response = curl_exec($ch);
@@ -209,7 +220,7 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/api-key/list?limit=20")
req = Net::HTTP::Get.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
@@ -218,7 +229,7 @@ data = JSON.parse(res.body)
<Tab value="Go">
```go title="Request"
req, _ := http.NewRequest("GET", "https://app.rybbit.io/api/auth/api-key/list?limit=20", nil)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
client := &http.Client{}
resp, _ := client.Do(req)
@@ -233,7 +244,7 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.get("https://app.rybbit.io/api/auth/api-key/list?limit=20")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.send()
.await?;
@@ -245,7 +256,7 @@ let data: serde_json::Value = res.json().await?;
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/api-key/list?limit=20"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
.GET()
.build();
@@ -255,7 +266,7 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
var response = await client.GetAsync("https://app.rybbit.io/api/auth/api-key/list?limit=20");
var data = await response.Content.ReadAsStringAsync();
@@ -271,9 +282,10 @@ var data = await response.Content.ReadAsStringAsync();
{
"id": "key_8f3a1b2c4d5e6f7g",
"name": "CI pipeline",
- "start": "rybbit_sk_live_xxxx",
- "prefix": "rybbit_sk_live_",
- "userId": "user_2a9b8c7d6e5f4g3h",
+ "start": "aBcDeF",
+ "prefix": null,
+ "referenceId": "user_2a9b8c7d6e5f4g3h",
+ "configId": "default",
"enabled": true,
"expiresAt": "2026-07-25T12:00:00.000Z",
"createdAt": "2026-06-25T12:00:00.000Z",
diff --git a/docs/content/docs/api/api-keys/update.mdx b/docs/content/docs/api/api-keys/update.mdx
index e0fb07981..e590f6222 100644
--- a/docs/content/docs/api/api-keys/update.mdx
+++ b/docs/content/docs/api/api-keys/update.mdx
@@ -20,7 +20,7 @@ POST /api/auth/api-key/update
Updates mutable fields on an existing API key. The key is identified by its `keyId`.
-<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie with the request.</Callout>
+<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie and an `Origin` header with the request. To update an organization key, pass `"configId": "org"`; without it the key is not found (`404`). Managing organization keys requires the owner or admin role.</Callout>
### Request Body
@@ -31,8 +31,13 @@ Updates mutable fields on an existing API key. The key is identified by its `key
type: 'string',
required: true,
},
+ configId: {
+ description: 'Set to "org" for an organization key. Omit for a personal key.',
+ type: 'string',
+ required: false,
+ },
name: {
- description: 'A new label for the key',
+ description: 'A new label for the key, 1 to 32 characters',
type: 'string',
required: false,
},
@@ -42,18 +47,15 @@ Updates mutable fields on an existing API key. The key is identified by its `key
required: false,
},
expiresIn: {
- description: 'New expiry in seconds from now. Pass null to make the key never expire.',
+ description: 'New expiry in seconds from now, from 86,400 (1 day) to 31,536,000 (365 days). Pass null to make the key never expire.',
type: 'number | null',
required: false,
},
- rateLimitEnabled: {
- description: 'Legacy per-key rate limit toggle. Has no effect β€” [rate limits](/docs/api/getting-started#rate-limits-cloud-only) are enforced per credential owner and follow that owner\'s plan',
- type: 'boolean',
- required: false,
- },
}}
/>
+Scopes (`permissions`) and the legacy rate-limit fields (`rateLimitEnabled`, `rateLimitMax`, `rateLimitTimeWindow`, `remaining`, `refillAmount`, `refillInterval`) can't be changed over HTTP; sending any of them returns `400`. To change a key's scopes, create a new key and delete the old one.
+
### Response
Returns the updated API key object (without the secret key value).
@@ -76,8 +78,12 @@ Returns the updated API key object (without the secret key value).
description: 'The key prefix',
type: 'string | null',
},
- userId: {
- description: 'ID of the user that owns the key',
+ referenceId: {
+ description: 'Owner of the key: your user ID for personal keys, the organization ID for organization keys',
+ type: 'string',
+ },
+ configId: {
+ description: '"default" for personal keys, "org" for organization keys',
type: 'string',
},
enabled: {
@@ -97,15 +103,15 @@ Returns the updated API key object (without the secret key value).
type: 'string',
},
rateLimitEnabled: {
- description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only))',
+ description: 'Unused legacy field. Per-key rate limiting is off; limits apply per credential owner (see Rate Limits in Getting Started)',
type: 'boolean',
},
rateLimitMax: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number | null',
},
rateLimitTimeWindow: {
- description: 'Unused legacy field. It is ignored β€” see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only) for the limits that actually apply',
+ description: 'Unused legacy field. It is ignored β€” see Rate Limits in Getting Started for the limits that actually apply',
type: 'number | null',
},
}}
@@ -113,6 +119,8 @@ Returns the updated API key object (without the secret key value).
**Note:** Additional fields may be present in the response object.
+The `rateLimit*` fields are unused: limits apply per credential owner, see [Rate Limits](/docs/api/getting-started#rate-limits-cloud-only).
+
</div>
<div className="flex flex-col gap-4">
@@ -120,7 +128,8 @@ Returns the updated API key object (without the secret key value).
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/auth/api-key/update" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Origin: https://app.rybbit.io" \
-H "Content-Type: application/json" \
-d '{"keyId": "key_8f3a1b2c4d5e6f7g", "name": "CI pipeline (rotated)", "enabled": true}'
```
@@ -158,7 +167,8 @@ response = requests.post(
'enabled': True
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin': 'https://app.rybbit.io'
}
)
@@ -177,7 +187,8 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'enabled' => true
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin: https://app.rybbit.io',
'Content-Type: application/json'
]);
@@ -194,7 +205,8 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/api-key/update")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Origin'] = 'https://app.rybbit.io'
req['Content-Type'] = 'application/json'
req.body = {
keyId: 'key_8f3a1b2c4d5e6f7g',
@@ -214,7 +226,8 @@ body := bytes.NewBuffer([]byte(`{
"enabled": true
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/auth/api-key/update", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Origin", "https://app.rybbit.io")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -230,7 +243,8 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/auth/api-key/update")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.json(&serde_json::json!({
"keyId": "key_8f3a1b2c4d5e6f7g",
"name": "CI pipeline (rotated)",
@@ -248,7 +262,8 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"keyId\": \"key_8f3a1b2c4d5e6f7g\", \"name\": \"CI pipeline (rotated)\", \"enabled\": true}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/api-key/update"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -259,7 +274,8 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Origin", "https://app.rybbit.io");
var content = new StringContent(
"{\"keyId\": \"key_8f3a1b2c4d5e6f7g\", \"name\": \"CI pipeline (rotated)\", \"enabled\": true}",
@@ -277,9 +293,10 @@ var data = await response.Content.ReadAsStringAsync();
{
"id": "key_8f3a1b2c4d5e6f7g",
"name": "CI pipeline (rotated)",
- "start": "rybbit_sk_live_xxxx",
- "prefix": "rybbit_sk_live_",
- "userId": "user_2a9b8c7d6e5f4g3h",
+ "start": "aBcDeF",
+ "prefix": null,
+ "referenceId": "user_2a9b8c7d6e5f4g3h",
+ "configId": "default",
"enabled": true,
"expiresAt": "2026-07-25T12:00:00.000Z",
"createdAt": "2026-06-25T12:00:00.000Z",
diff --git a/docs/content/docs/api/bots/ai-summary.mdx b/docs/content/docs/api/bots/ai-summary.mdx
index 4094c865c..58683dc62 100644
--- a/docs/content/docs/api/bots/ai-summary.mdx
+++ b/docs/content/docs/api/bots/ai-summary.mdx
@@ -38,7 +38,7 @@ Operators that only read, and operators that only referred, both appear; the mis
Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (time and filters).
-Filters apply to both halves, using the bot filter subset described in [Get Bots by Dimension](/docs/api/bots/by-dimension).
+Filters apply differently to each half. The crawl half (`crawls`, `training_crawls`, `search_crawls`, `agent_requests`) uses only the bot filter subset described in [Get Bots by Dimension](/docs/api/bots/by-dimension) and ignores other parameters. The referral half (`referrals`) uses the full events filter set. So a channel, UTM, or `event_name` filter narrows referrals but leaves crawl counts unchanged.
### Response
diff --git a/docs/content/docs/api/bots/by-dimension.mdx b/docs/content/docs/api/bots/by-dimension.mdx
index cfb5b07d1..3384c2f70 100644
--- a/docs/content/docs/api/bots/by-dimension.mdx
+++ b/docs/content/docs/api/bots/by-dimension.mdx
@@ -38,7 +38,7 @@ Bot filtering supports a subset of filter parameters: `browser`, `browser_versio
<TypeTable
type={{
dimension: {
- description: 'The dimension to group by',
+ description: 'The dimension to group by. There is no default: a missing or unknown value fails with 500.',
type: 'string',
typeDescription: '"browser" | "browser_version" | "operating_system" | "operating_system_version" | "country" | "region" | "city" | "device_type" | "referrer" | "hostname" | "pathname" | "dimensions" | "asn_org" | "asn_provider" | "bot_category" | "bot_name" | "bot_operator" | "bot_purpose" | "matched_ua_pattern"',
required: true,
diff --git a/docs/content/docs/api/bots/time-series.mdx b/docs/content/docs/api/bots/time-series.mdx
index 1a8bab44f..1ebc0e8eb 100644
--- a/docs/content/docs/api/bots/time-series.mdx
+++ b/docs/content/docs/api/bots/time-series.mdx
@@ -215,8 +215,8 @@ var data = await response.Content.ReadAsStringAsync();
```json title="Response"
{
"data": [
- { "time": "2024-01-15 13:00:00", "bot_requests": 42 },
- { "time": "2024-01-15 14:00:00", "bot_requests": 58 }
+ { "time": "2024-01-15 13:00:00", "bot_requests": 42, "ai_agent_requests": 3, "ai_crawler_requests": 17 },
+ { "time": "2024-01-15 14:00:00", "bot_requests": 58, "ai_agent_requests": 5, "ai_crawler_requests": 22 }
]
}
```
diff --git a/docs/content/docs/api/channel-performance.mdx b/docs/content/docs/api/channel-performance.mdx
index 4661de96e..e3b71f41f 100644
--- a/docs/content/docs/api/channel-performance.mdx
+++ b/docs/content/docs/api/channel-performance.mdx
@@ -34,7 +34,7 @@ The key technique here is the [`filters` parameter](/docs/api/getting-started#fi
## Full script
-This script ranks every channel by the conversion rate of a chosen goal (here, goal `1` β€” your signup goal). Swap in whichever goal matters to your business.
+This script ranks every channel by the conversion rate of a chosen goal (here, goal `1` β€” your signup goal). Swap in whichever goal matters to your business. `/goals` returns 10 goals per page by default, newest first, so the script asks for `page_size=100` (the maximum); with more than 100 goals, page through with `page` until you find yours.
<Tabs items={['JavaScript', 'Python']}>
<Tab value="JavaScript">
@@ -63,7 +63,8 @@ async function getChannels() {
// 2. Conversion rate for one channel, scoped with a filter
async function goalForChannel(channel) {
const filters = JSON.stringify([{ parameter: 'channel', type: 'equals', value: [channel] }]);
- const { data } = await get('/goals', { filters, ...range });
+ // /goals is paginated (10 per page, newest first by default); ask for the maximum of 100
+ const { data } = await get('/goals', { filters, page_size: 100, ...range });
return data.find((g) => g.goalId === PRIMARY_GOAL_ID);
}
@@ -128,7 +129,8 @@ def get_channels():
def goal_for_channel(channel):
# 2. Conversion rate for one channel, scoped with a filter
filters = json.dumps([{"parameter": "channel", "type": "equals", "value": [channel]}])
- goals = get("/goals", filters=filters, **RANGE)["data"]
+ # /goals is paginated (10 per page, newest first by default); ask for the maximum of 100
+ goals = get("/goals", filters=filters, page_size=100, **RANGE)["data"]
return next((g for g in goals if g["goalId"] == PRIMARY_GOAL_ID), None)
diff --git a/docs/content/docs/api/errors/events.mdx b/docs/content/docs/api/errors/events.mdx
index 1f0d801af..1ef280ad9 100644
--- a/docs/content/docs/api/errors/events.mdx
+++ b/docs/content/docs/api/errors/events.mdx
@@ -36,12 +36,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
errorMessage: {
- description: 'The error message to filter by',
+ description: 'The exact error message to return occurrences for (the value field from Get Error Names). Missing returns 400.',
type: 'string',
required: true,
},
page: {
- description: 'Page number (1-indexed)',
+ description: 'Page number (1-indexed). When set, data becomes { data, totalCount } instead of an array.',
type: 'number',
required: false,
},
@@ -58,12 +58,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
data: {
- description: 'Array of error event objects',
- type: 'ErrorEvent[]',
+ description: 'Array of error event objects, newest first. When page is set, an object { data: ErrorEvent[], totalCount: number } instead, where totalCount is the number of matching occurrences.',
+ type: 'ErrorEvent[] | { data: ErrorEvent[], totalCount: number }',
},
}}
/>
+With `page`, the response nests one level deeper: `{ "data": { "data": [...], "totalCount": 42 } }`.
+
#### ErrorEvent Object
<TypeTable
@@ -71,7 +73,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
timestamp: {
description: 'When the error occurred',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
session_id: {
description: 'Session identifier',
@@ -89,6 +91,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Hostname',
type: 'string',
},
+ page_title: {
+ description: 'Page title',
+ type: 'string',
+ },
+ referrer: {
+ description: 'Referrer URL',
+ type: 'string',
+ },
browser: {
description: 'Browser name',
type: 'string',
@@ -101,6 +111,10 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Operating system',
type: 'string',
},
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
device_type: {
description: 'Device type',
type: 'string',
@@ -109,6 +123,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Country code',
type: 'string',
},
+ region: {
+ description: 'Region/state',
+ type: 'string',
+ },
+ city: {
+ description: 'City name',
+ type: 'string',
+ },
message: {
description: 'Error message',
type: 'string',
@@ -254,16 +276,21 @@ var data = await response.Content.ReadAsStringAsync();
{
"data": [
{
- "timestamp": "2024-01-31T14:22:00.000Z",
+ "timestamp": "2024-01-31 14:22:00",
"session_id": "sess_abc123",
"user_id": "user_xyz789",
"pathname": "/dashboard",
"hostname": "app.example.com",
+ "page_title": "Dashboard",
+ "referrer": "https://app.example.com/login",
"browser": "Chrome",
"browser_version": "120.0.0",
"operating_system": "macOS",
+ "operating_system_version": "14.0",
"device_type": "desktop",
"country": "US",
+ "region": "US-CA",
+ "city": "San Francisco",
"message": "Cannot read property 'map' of undefined",
"stack": "TypeError: Cannot read property 'map' of undefined\n at Dashboard (dashboard.js:42:15)\n at renderWithHooks (react-dom.js:1234:22)",
"fileName": "dashboard.js",
diff --git a/docs/content/docs/api/errors/names.mdx b/docs/content/docs/api/errors/names.mdx
index dcb51330d..498558bb7 100644
--- a/docs/content/docs/api/errors/names.mdx
+++ b/docs/content/docs/api/errors/names.mdx
@@ -36,7 +36,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
page: {
- description: 'Page number (1-indexed). Enables paginated response format.',
+ description: 'Page number (1-indexed). When set, data becomes { data, totalCount } instead of an array.',
type: 'number',
required: false,
},
@@ -53,12 +53,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
data: {
- description: 'Array of error objects (or paginated wrapper)',
- type: 'Error[] | PaginatedResponse',
+ description: 'Array of error objects, most occurrences first. When page is set, an object { data: Error[], totalCount: number } instead, where totalCount is the number of distinct error messages.',
+ type: 'Error[] | { data: Error[], totalCount: number }',
},
}}
/>
+With `page`, the response nests one level deeper: `{ "data": { "data": [...], "totalCount": 42 } }`.
+
#### Error Object
<TypeTable
diff --git a/docs/content/docs/api/errors/time-series.mdx b/docs/content/docs/api/errors/time-series.mdx
index 5af9655e7..c1646f79d 100644
--- a/docs/content/docs/api/errors/time-series.mdx
+++ b/docs/content/docs/api/errors/time-series.mdx
@@ -36,12 +36,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
errorMessage: {
- description: 'The error message to filter by',
+ description: 'The exact error message to count (the value field from Get Error Names). Missing returns 400.',
type: 'string',
required: true,
},
bucket: {
- description: 'Time bucket size for grouping data',
+ description: 'Time bucket size for grouping data. There is no default: a missing or unknown value fails with 500.',
type: 'TimeBucket',
typeDescription: '"minute" | "five_minutes" | "ten_minutes" | "fifteen_minutes" | "hour" | "day" | "week" | "month" | "year"',
required: true,
@@ -58,7 +58,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'boolean',
},
data: {
- description: 'Array of time-bucketed counts',
+ description: 'Array of time-bucketed counts, oldest first. When the time range is bounded, empty buckets are returned with error_count 0.',
type: 'ErrorBucket[]',
},
}}
@@ -71,7 +71,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
time: {
description: 'Start of the time bucket',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'Bucket start in the requested time_zone, "YYYY-MM-DD HH:MM:SS"',
},
error_count: {
description: 'Number of errors in this bucket',
@@ -206,19 +206,19 @@ var data = await response.Content.ReadAsStringAsync();
"success": true,
"data": [
{
- "time": "2024-01-30T00:00:00.000Z",
+ "time": "2024-01-30 00:00:00",
"error_count": 5
},
{
- "time": "2024-01-30T01:00:00.000Z",
+ "time": "2024-01-30 01:00:00",
"error_count": 3
},
{
- "time": "2024-01-30T02:00:00.000Z",
+ "time": "2024-01-30 02:00:00",
"error_count": 8
},
{
- "time": "2024-01-30T03:00:00.000Z",
+ "time": "2024-01-30 03:00:00",
"error_count": 2
}
]
diff --git a/docs/content/docs/api/events/count.mdx b/docs/content/docs/api/events/count.mdx
index 3f98a8cf6..240d74f00 100644
--- a/docs/content/docs/api/events/count.mdx
+++ b/docs/content/docs/api/events/count.mdx
@@ -46,11 +46,23 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
### Response
+<TypeTable
+ type={{
+ data: {
+ description: 'One row per bucket, oldest first. When the time range is bounded, empty buckets are returned as zero rows.',
+ type: 'EventCountBucket[]',
+ },
+ }}
+/>
+
+#### EventCountBucket Object
+
<TypeTable
type={{
time: {
description: 'Start of the time bucket',
type: 'string',
+ typeDescription: 'Bucket start in the requested time_zone, "YYYY-MM-DD HH:MM:SS"',
},
pageview_count: {
description: 'Number of pageviews in this bucket',
diff --git a/docs/content/docs/api/events/list.mdx b/docs/content/docs/api/events/list.mdx
index 030dc3953..b299f9872 100644
--- a/docs/content/docs/api/events/list.mdx
+++ b/docs/content/docs/api/events/list.mdx
@@ -17,6 +17,13 @@ GET /api/sites/:site/events
Returns a paginated list of events (pageviews, custom events, and outbound clicks).
+Web vitals rows are left out. Events come back newest first. Page with cursors:
+
+- **Scroll back:** make the first request with no cursor, then pass `cursor.oldestCursor` as `before_cursor` until `cursor.hasMore` is `false`.
+- **Poll for new events:** pass `cursor.newestCursor` (or any row's `event_cursor`) as `since_cursor`, then pass each response's `cursor.nextCursor` on the next poll. Each poll reads the oldest 500 events after the cursor; if `cursor.hasMore` is `true`, poll again straight away. Each poll re-reads the last 5 seconds, because events can be written slightly out of order, so drop rows whose `event_cursor` you already have. The first poll after a page load gets no such overlap from `cursor.newestCursor` itself, so start it 5 seconds earlier: subtract 5000 from the cursor's millisecond part and use sixteen zeros after the underscore (see [Build a Live Visitor Feed](/docs/api/live-feed)).
+
+`since_timestamp` and `before_timestamp` are older whole-second bounds kept for compatibility. Events in the boundary second are skipped, so prefer the cursors.
+
### Path Parameters
<TypeTable
@@ -36,32 +43,42 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
page_size: {
- description: 'Number of results per page',
+ description: 'Number of results per page. Ignored when since_cursor or since_timestamp is set.',
type: 'number',
default: 50,
},
+ before_cursor: {
+ description: 'Return events older than this cursor. Pass cursor.oldestCursor from the previous page, or a row\'s event_cursor.',
+ type: 'string',
+ },
+ since_cursor: {
+ description: 'Poll for events newer than this cursor. Returns up to 500 events per poll, read oldest first, and a cursor with nextCursor and hasMore. Takes precedence over every other cursor parameter.',
+ type: 'string',
+ },
since_timestamp: {
- description: 'Poll for new events after this timestamp (ISO 8601). Used for realtime polling. Returns up to 500 events.',
+ description: 'Legacy. Return events after this second (UTC, "YYYY-MM-DD HH:MM:SS"). Returns only the newest 500 and no cursor; events in the boundary second are skipped.',
type: 'string',
},
before_timestamp: {
- description: 'Fetch events before this timestamp (ISO 8601). Used for cursor-based pagination (scrolling back).',
+ description: 'Legacy. Return events before this second (UTC, "YYYY-MM-DD HH:MM:SS"). Events in the boundary second are skipped.',
type: 'string',
},
}}
/>
+A malformed `before_cursor` or `since_cursor` returns `400`.
+
### Response
<TypeTable
type={{
data: {
- description: 'Array of event objects',
+ description: 'Array of event objects, newest first',
type: 'Event[]',
},
cursor: {
- description: 'Cursor metadata for pagination (only present when not using since_timestamp)',
- type: '{ hasMore: boolean, oldestTimestamp: string | null }',
+ description: 'Pagination cursor. Omitted when since_timestamp is used. With since_cursor it is { nextCursor, hasMore }; otherwise it is the scroll-back shape.',
+ type: '{ hasMore: boolean, oldestTimestamp: string | null, oldestCursor: string | null, newestCursor: string | null } | { nextCursor: string, hasMore: boolean }',
},
}}
/>
@@ -73,12 +90,17 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
timestamp: {
description: 'Event timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ event_cursor: {
+ description: 'The row\'s position in the log, usable as before_cursor or since_cursor',
+ type: 'string',
+ typeDescription: '"<epoch milliseconds>_<16 hex digits>"',
},
type: {
description: 'Event type',
type: 'string',
- typeDescription: '"pageview" | "custom_event" | "outbound" | "button_click" | "copy" | "form_submit" | "input_change"',
+ typeDescription: '"pageview" | "custom_event" | "outbound" | "button_click" | "copy" | "form_submit" | "input_change" | "error"',
},
event_name: {
description: 'Custom event name',
@@ -100,6 +122,10 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Identified user ID (if user has been identified)',
type: 'string',
},
+ traits: {
+ description: 'Traits of the identified user, or null when the event has no identified user or no stored profile',
+ type: 'object | null',
+ },
pathname: {
description: 'Page path',
type: 'string',
@@ -298,7 +324,7 @@ var data = await response.Content.ReadAsStringAsync();
{
"data": [
{
- "timestamp": "2024-01-31T14:22:00.000Z",
+ "timestamp": "2024-01-31 14:22:00",
"type": "custom_event",
"event_name": "signup",
"properties": "{\"plan\":\"pro\",\"source\":\"homepage\"}",
@@ -322,10 +348,12 @@ var data = await response.Content.ReadAsStringAsync();
"lon": -122.4194,
"screen_width": 1920,
"screen_height": 1080,
- "device_type": "desktop"
+ "device_type": "desktop",
+ "event_cursor": "1706710920412_9F3C2A61B07E4D18",
+ "traits": null
},
{
- "timestamp": "2024-01-31T14:21:00.000Z",
+ "timestamp": "2024-01-31 14:21:00",
"type": "pageview",
"event_name": "",
"properties": "{}",
@@ -349,12 +377,16 @@ var data = await response.Content.ReadAsStringAsync();
"lon": -122.4194,
"screen_width": 1920,
"screen_height": 1080,
- "device_type": "desktop"
+ "device_type": "desktop",
+ "event_cursor": "1706710860118_04B7E9D25C3A1F60",
+ "traits": null
}
],
"cursor": {
"hasMore": true,
- "oldestTimestamp": "2024-01-31T14:21:00.000Z"
+ "oldestTimestamp": "2024-01-31 14:21:00",
+ "oldestCursor": "1706710860118_04B7E9D25C3A1F60",
+ "newestCursor": "1706710920412_9F3C2A61B07E4D18"
}
}
```
diff --git a/docs/content/docs/api/events/names.mdx b/docs/content/docs/api/events/names.mdx
index 018ed4cfb..45184713a 100644
--- a/docs/content/docs/api/events/names.mdx
+++ b/docs/content/docs/api/events/names.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:site/events/names
```
-Returns a list of unique custom event names with their occurrence counts.
+Returns a list of unique custom event names with their occurrence counts, most frequent first. Returns at most 1,000 names.
### Path Parameters
@@ -38,7 +38,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
<TypeTable
type={{
data: {
- description: 'Array of event name objects',
+ description: 'Array of event name objects, sorted by count descending (at most 1,000)',
type: 'EventName[]',
},
}}
@@ -184,10 +184,6 @@ var data = await response.Content.ReadAsStringAsync();
"eventName": "signup",
"count": 1250
},
- {
- "eventName": "purchase",
- "count": 320
- },
{
"eventName": "add_to_cart",
"count": 890
@@ -195,6 +191,10 @@ var data = await response.Content.ReadAsStringAsync();
{
"eventName": "newsletter_subscribe",
"count": 456
+ },
+ {
+ "eventName": "purchase",
+ "count": 320
}
]
}
diff --git a/docs/content/docs/api/events/outbound.mdx b/docs/content/docs/api/events/outbound.mdx
index 631e27955..54ef9fa37 100644
--- a/docs/content/docs/api/events/outbound.mdx
+++ b/docs/content/docs/api/events/outbound.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:site/events/outbound
```
-Returns a list of outbound link clicks with their occurrence counts.
+Returns a list of outbound link clicks with their occurrence counts, most-clicked first. Returns at most 1,000 URLs.
### Path Parameters
@@ -38,7 +38,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
<TypeTable
type={{
data: {
- description: 'Array of outbound link objects',
+ description: 'Array of outbound link objects, sorted by count descending (at most 1,000)',
type: 'OutboundLink[]',
},
}}
@@ -59,7 +59,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
lastClicked: {
description: 'Most recent click timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
}}
/>
@@ -188,17 +188,17 @@ var data = await response.Content.ReadAsStringAsync();
{
"url": "https://github.com/example/repo",
"count": 245,
- "lastClicked": "2024-01-31T14:22:00.000Z"
+ "lastClicked": "2024-01-31 14:22:00"
},
{
"url": "https://twitter.com/example",
"count": 189,
- "lastClicked": "2024-01-31T12:15:00.000Z"
+ "lastClicked": "2024-01-31 12:15:00"
},
{
"url": "https://docs.example.com",
"count": 156,
- "lastClicked": "2024-01-31T10:30:00.000Z"
+ "lastClicked": "2024-01-31 10:30:00"
}
]
}
diff --git a/docs/content/docs/api/events/properties.mdx b/docs/content/docs/api/events/properties.mdx
index b44bf2858..d9bfb4d2c 100644
--- a/docs/content/docs/api/events/properties.mdx
+++ b/docs/content/docs/api/events/properties.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:site/events/properties
```
-Returns property key-value pairs for a specific event name with their occurrence counts.
+Returns property key-value pairs for a specific event name with their occurrence counts. Returns at most 500 key-value pairs in total, sorted by key, then by count descending, so later keys can be cut off on events with many distinct values.
### Path Parameters
@@ -36,7 +36,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
event_name: {
- description: 'Event name to get properties for',
+ description: 'Event name to get properties for. Missing returns 400.',
type: 'string',
required: true,
},
@@ -48,7 +48,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
data: {
- description: 'Array of property objects',
+ description: 'Array of property objects (at most 500)',
type: 'EventProperty[]',
},
}}
diff --git a/docs/content/docs/api/events/time-series.mdx b/docs/content/docs/api/events/time-series.mdx
index 80958f5a2..e3fe9cc4f 100644
--- a/docs/content/docs/api/events/time-series.mdx
+++ b/docs/content/docs/api/events/time-series.mdx
@@ -52,11 +52,23 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
### Response
+<TypeTable
+ type={{
+ data: {
+ description: 'One row per bucket and event name, oldest first. Buckets with no events are omitted.',
+ type: 'EventBucket[]',
+ },
+ }}
+/>
+
+#### EventBucket Object
+
<TypeTable
type={{
time: {
description: 'Start of the time bucket',
type: 'string',
+ typeDescription: 'Bucket start in the requested time_zone, "YYYY-MM-DD HH:MM:SS"',
},
event_name: {
description: 'Name of the custom event',
diff --git a/docs/content/docs/api/funnel-dropoff.mdx b/docs/content/docs/api/funnel-dropoff.mdx
index 09cc860d0..4f6a88b8e 100644
--- a/docs/content/docs/api/funnel-dropoff.mdx
+++ b/docs/content/docs/api/funnel-dropoff.mdx
@@ -1,18 +1,18 @@
---
title: Find Where Users Drop Off
-description: Chain the funnel analysis and journeys endpoints to locate the biggest leak in a conversion flow, then discover where the users who abandon actually go instead.
+description: Chain the funnel analysis and funnel step sessions endpoints to locate the biggest leak in a conversion flow, then see the last page the people who abandon viewed.
---
import { Callout } from 'fumadocs-ui/components/callout';
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
import { Step, Steps } from 'fumadocs-ui/components/steps';
-A funnel tells you *how many* people fall out at each step. The journeys endpoint tells you *where they went instead*. Putting them together turns "our signup funnel leaks at the pricing page" into "people leave the pricing page for the FAQ β€” they have unanswered questions."
+A funnel tells you *how many* people fall out at each step. The funnel step sessions endpoint lists *the sessions that fell out*, with the last page each one viewed. Putting them together turns "our signup funnel leaks at the pricing page" into "people who stall on pricing end their visit on the FAQ β€” they have unanswered questions."
**Endpoints used:**
- [`POST /funnels/analyze`](/docs/api/funnels/analyze) β€” step-by-step conversion and drop-off rates
-- [`GET /journeys`](/docs/api/insights/journeys) β€” the most common navigation paths
+- [`POST /funnels/:stepNumber/sessions`](/docs/api/funnels/step-sessions) β€” the sessions that reached a step but not the next one
## The workflow
@@ -24,7 +24,7 @@ A funnel tells you *how many* people fall out at each step. The journeys endpoin
**Find the worst step** β€” the one with the highest `dropoff_rate`.
</Step>
<Step>
-**Pull journeys that start at that step's page** using `stepFilters`, so you can see the most common next page for people who were there.
+**List the sessions that dropped** after the step before the leak (`mode=dropped`) and count their `exit_page`, the last page each one viewed.
</Step>
</Steps>
@@ -60,6 +60,7 @@ async function analyzeFunnel() {
},
body: JSON.stringify({ steps: funnelSteps }),
});
+ if (!res.ok) throw new Error(`Funnel analysis failed: HTTP ${res.status}`);
const { data } = await res.json();
return data; // array of { step_number, step_name, sessions, conversion_rate, dropoff_rate }
}
@@ -154,59 +155,77 @@ print(
In the example above, the steepest drop-off is **60%, between Pricing and Signup** β€” of the 4,500 people who reached the pricing page, only 1,800 went on to signup. That makes the **pricing page** the one to investigate: it's where the audience was sitting right before the biggest leak.
-## Step 3 β€” See where the leavers went
+## Step 3 β€” See where the leavers ended up
-The [journeys endpoint](/docs/api/insights/journeys) ranks the most common page paths. Use `stepFilters` to anchor step `0` to the page people were dropping from β€” now every returned journey shows you a common *next* page for that audience.
+[`POST /funnels/:stepNumber/sessions?mode=dropped`](/docs/api/funnels/step-sessions) returns the sessions that reached step `stepNumber` but never reached the next one, using the same `steps` body as the analyze call. Each session carries `exit_page`, the last page it viewed in the requested range. Count those across a few pages of results to see where people who stalled ended their visit.
<Tabs items={['JavaScript', 'Python']}>
<Tab value="JavaScript">
-```javascript title="What did they do after the leaky page?"
-async function journeysFrom(page) {
- const stepFilters = JSON.stringify({ '0': page });
- const url = new URL(`${API}/api/sites/${SITE}/journeys`);
- url.searchParams.set('steps', '2');
- url.searchParams.set('limit', '10');
- url.searchParams.set('stepFilters', stepFilters);
- Object.entries(range).forEach(([k, v]) => url.searchParams.set(k, v));
-
- const res = await fetch(url, { headers: { Authorization: `Bearer ${API_KEY}` } });
- const { journeys } = await res.json();
- return journeys;
+```javascript title="Where did the leavers end their visit?"
+async function droppedSessions(stepNumber, pages = 5) {
+ const sessions = [];
+ for (let page = 1; page <= pages; page++) {
+ const url = new URL(`${API}/api/sites/${SITE}/funnels/${stepNumber}/sessions`);
+ url.searchParams.set('mode', 'dropped');
+ url.searchParams.set('limit', '100');
+ url.searchParams.set('page', String(page));
+ Object.entries(range).forEach(([k, v]) => url.searchParams.set(k, v));
+
+ const res = await fetch(url, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${API_KEY}`, 'Content-Type': 'application/json' },
+ body: JSON.stringify({ steps: funnelSteps }),
+ });
+ if (!res.ok) throw new Error(`Step sessions failed: HTTP ${res.status}`);
+ const { data } = await res.json();
+ sessions.push(...data);
+ if (data.length < 100) break; // last page
+ }
+ return sessions;
}
-// The leaky step's page β€” '/pricing' in our example
-const leakyPage = funnelSteps[leak.step_number - 2].value;
-const journeys = await journeysFrom(leakyPage);
+// Sessions that reached the step before the leak ('Pricing') but not the next one
+const dropped = await droppedSessions(enteredStep.step_number);
-console.log(`Where users go after ${leakyPage}:`);
-journeys
- .filter((j) => j.path[1] && j.path[1] !== '/signup') // exclude the intended next step
+const exits = {};
+for (const s of dropped) exits[s.exit_page] = (exits[s.exit_page] || 0) + 1;
+
+console.log(`Last page viewed by ${dropped.length} sessions that left after ${enteredStep.step_name}:`);
+Object.entries(exits)
+ .sort((a, b) => b[1] - a[1])
.slice(0, 5)
- .forEach((j) => console.log(` β†’ ${j.path[1]} (${j.count} sessions, ${j.percentage}%)`));
+ .forEach(([page, n]) => console.log(` ${page} (${n} sessions, ${((n / dropped.length) * 100).toFixed(1)}%)`));
```
</Tab>
<Tab value="Python">
-```python title="What did they do after the leaky page?"
-import json
-
-
-def journeys_from(page):
- res = requests.get(
- f"{API}/api/sites/{SITE}/journeys",
- params={"steps": 2, "limit": 10, "stepFilters": json.dumps({"0": page}), **RANGE},
- headers={"Authorization": f"Bearer {API_KEY}"},
- )
- res.raise_for_status()
- return res.json()["journeys"]
-
-
-# The leaky step's page β€” '/pricing' in our example
-leaky_page = FUNNEL_STEPS[leak["step_number"] - 2]["value"]
-journeys = journeys_from(leaky_page)
-
-print(f"Where users go after {leaky_page}:")
-for j in [j for j in journeys if len(j["path"]) > 1 and j["path"][1] != "/signup"][:5]:
- print(f' β†’ {j["path"][1]} ({j["count"]} sessions, {j["percentage"]}%)')
+```python title="Where did the leavers end their visit?"
+from collections import Counter
+
+
+def dropped_sessions(step_number, pages=5):
+ sessions = []
+ for page in range(1, pages + 1):
+ res = requests.post(
+ f"{API}/api/sites/{SITE}/funnels/{step_number}/sessions",
+ params={"mode": "dropped", "limit": 100, "page": page, **RANGE},
+ json={"steps": FUNNEL_STEPS},
+ headers={"Authorization": f"Bearer {API_KEY}"},
+ )
+ res.raise_for_status()
+ data = res.json()["data"]
+ sessions.extend(data)
+ if len(data) < 100: # last page
+ break
+ return sessions
+
+
+# Sessions that reached the step before the leak ('Pricing') but not the next one
+dropped = dropped_sessions(entered_step["step_number"])
+exits = Counter(s["exit_page"] for s in dropped)
+
+print(f'Last page viewed by {len(dropped)} sessions that left after {entered_step["step_name"]}:')
+for page, n in exits.most_common(5):
+ print(f" {page} ({n} sessions, {n / len(dropped) * 100:.1f}%)")
```
</Tab>
</Tabs>
@@ -214,19 +233,26 @@ for j in [j for j in journeys if len(j["path"]) > 1 and j["path"][1] != "/signup
### The insight
```text
-Where users go after /pricing:
- β†’ /faq (1,240 sessions, 27.6%)
- β†’ / (820 sessions, 18.2%)
- β†’ /enterprise (610 sessions, 13.6%)
+Last page viewed by 500 sessions that left after Pricing:
+ /faq (138 sessions, 27.6%)
+ /pricing (121 sessions, 24.2%)
+ /enterprise (68 sessions, 13.6%)
```
-More than a quarter of people who hit Pricing and didn't sign up went to the FAQ β€” a strong signal that pricing raises questions your FAQ has to answer. That's a far more actionable finding than "the pricing page has a 60% drop-off."
+In this example more than a quarter of the people who reached Pricing and didn't sign up ended their visit on the FAQ, a sign that pricing raises questions the FAQ has to answer. That is more actionable than "the pricing page has a 60% drop-off."
+
+This samples the most recent dropped sessions (up to 500 here). Raise `pages` for a fuller count; each page is one request against your [rate limit](/docs/api/getting-started#rate-limits-cloud-only).
+
+<Callout type="info">
+Don't use [`GET /journeys`](/docs/api/insights/journeys) with `stepFilters` `{"0": "/pricing"}` for this. A journey is the first pages of a session, so step `0` is the landing page: that filter only covers sessions that *landed* on pricing, and each journey's `percentage` is a share of all sessions with two or more pages, not of that audience. It is the right tool for "where do people who land on /pricing go next?", not for funnel drop-off.
+</Callout>
<Callout type="info">
-**Quantify before you act.** Combine the funnel and journey numbers into a one-line business case: *"2,700 users/month leave Pricing; 28% head to the FAQ. Surfacing the top FAQ answers on the pricing page could recover a meaningful share of them."*
+**Quantify before you act.** Combine the funnel and exit-page numbers into a one-line business case: *"2,700 sessions a month leave after Pricing; 28% end on the FAQ. Surfacing the top FAQ answers on the pricing page could recover a meaningful share of them."*
</Callout>
## Next steps
- [Compare Marketing Channel Performance](/docs/api/channel-performance) β€” find out which traffic sources fill the top of this funnel with people who actually convert.
-- [Funnels API reference](/docs/api/funnels/analyze) β€” event steps, property matching, and per-step session lookups.
+- [Funnels API reference](/docs/api/funnels/analyze) β€” event steps and property matching.
+- [Funnel step sessions](/docs/api/funnels/step-sessions) β€” `reached` and `dropped` session lists for any step.
diff --git a/docs/content/docs/api/funnels/analyze.mdx b/docs/content/docs/api/funnels/analyze.mdx
index 78345f901..9652e48b9 100644
--- a/docs/content/docs/api/funnels/analyze.mdx
+++ b/docs/content/docs/api/funnels/analyze.mdx
@@ -56,9 +56,10 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
required: true,
},
value: {
- description: 'Page path pattern or event name',
+ description: 'page: path pattern (* matches within one path segment, ** across segments). event: custom event name. Autocapture types (outbound, button_click, form_submit, copy): wildcard pattern for the destination URL, button or copied text, or form name, ID, or action; leave empty to match every event of the type.',
type: 'string',
- required: true,
+ typeDescription: 'Required for page and event steps',
+ required: false,
},
name: {
description: 'Display name for the step',
@@ -70,13 +71,18 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
type: 'string',
required: false,
},
+ propertyFilters: {
+ description: 'Exact-match filters that must all pass. For event and autocapture steps they match event properties; for page steps they match URL query parameters. Property values are compared as strings: a boolean or number stored as a native JSON value (e.g. `{ gift: true }`) does not match.',
+ type: 'Array<{ key: string; value: string | number | boolean }>',
+ required: false,
+ },
eventPropertyKey: {
- description: 'Event property key to match (for event steps)',
+ description: 'Deprecated: use propertyFilters. Single property key; ignored when propertyFilters is set.',
type: 'string',
required: false,
},
eventPropertyValue: {
- description: 'Event property value to match',
+ description: 'Deprecated: use propertyFilters. Single property value; ignored when propertyFilters is set.',
type: 'string | number | boolean',
required: false,
},
diff --git a/docs/content/docs/api/funnels/create.mdx b/docs/content/docs/api/funnels/create.mdx
index 7a1ff4933..cea10e26c 100644
--- a/docs/content/docs/api/funnels/create.mdx
+++ b/docs/content/docs/api/funnels/create.mdx
@@ -1,6 +1,6 @@
---
title: Create Funnel
-description: Creates or updates a saved funnel. If `reportId` is provided, updates the existing funnel.
+description: Creates or updates a saved funnel. If `reportId` is provided, updates the existing funnel. Requires the member role or above on the site (the `funnels:write` permission).
full: true
method: POST
---
@@ -8,6 +8,8 @@ method: POST
import { TypeTable } from 'fumadocs-ui/components/type-table';
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+Each step uses the [FunnelStep object](/docs/api/funnels/analyze#funnelstep-object). Returns `201` on success; `400` for fewer than 2 steps, an unknown step type, a page or event step without a `value`, or a missing name; `404` if `reportId` does not exist; `403` if it belongs to another site.
+
<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
<div>
diff --git a/docs/content/docs/api/funnels/delete.mdx b/docs/content/docs/api/funnels/delete.mdx
index 5045356ec..0cb53b512 100644
--- a/docs/content/docs/api/funnels/delete.mdx
+++ b/docs/content/docs/api/funnels/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/funnels/:funnelId
```
-Deletes a saved funnel. This action cannot be undone.
+Deletes a saved funnel. This action cannot be undone. Requires the member role or above on the site (the `funnels:write` permission). Returns `404` if the funnel does not exist and `403` if it belongs to another site.
### Path Parameters
diff --git a/docs/content/docs/api/funnels/list.mdx b/docs/content/docs/api/funnels/list.mdx
index 1089bcf45..204393754 100644
--- a/docs/content/docs/api/funnels/list.mdx
+++ b/docs/content/docs/api/funnels/list.mdx
@@ -53,18 +53,22 @@ Returns all saved funnels for a site.
type: 'string',
},
steps: {
- description: 'Array of funnel steps',
+ description: 'Array of funnel steps, as saved (see the FunnelStep object on Analyze Funnel)',
type: 'FunnelStep[]',
},
+ configuration: {
+ description: 'Extra settings stored with older funnels; an empty object for funnels saved through Create Funnel',
+ type: 'object',
+ },
createdAt: {
description: 'Creation timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
updatedAt: {
description: 'Last update timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
}}
/>
@@ -228,8 +232,9 @@ var data = await response.Content.ReadAsStringAsync();
{ "type": "page", "value": "/signup", "name": "Signup" },
{ "type": "page", "value": "/signup/complete", "name": "Complete" }
],
- "createdAt": "2024-01-10T12:00:00.000Z",
- "updatedAt": "2024-01-15T09:30:00.000Z"
+ "configuration": {},
+ "createdAt": "2024-01-10 12:00:00.123456",
+ "updatedAt": "2024-01-15 09:30:00.654321"
}
]
}
diff --git a/docs/content/docs/api/funnels/step-sessions.mdx b/docs/content/docs/api/funnels/step-sessions.mdx
index 45eeb2ed8..c1d2f5ce4 100644
--- a/docs/content/docs/api/funnels/step-sessions.mdx
+++ b/docs/content/docs/api/funnels/step-sessions.mdx
@@ -41,7 +41,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
mode: {
- description: 'Whether to get sessions that reached or dropped off at this step',
+ description: 'reached: sessions that completed this step. dropped: sessions that completed this step but not the next one (empty for the last step).',
type: 'string',
typeDescription: '"reached" | "dropped"',
required: true,
@@ -56,6 +56,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'number',
default: 25,
},
+ replays_only: {
+ description: 'Only return sessions that have a session replay',
+ type: 'string',
+ typeDescription: '"true" | "false"',
+ default: 'false',
+ },
}}
/>
@@ -64,7 +70,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
steps: {
- description: 'Array of funnel steps (same as used in analyze)',
+ description: 'Array of funnel steps (minimum 2), using the FunnelStep object from Analyze Funnel',
type: 'FunnelStep[]',
required: true,
},
@@ -82,6 +88,175 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
}}
/>
+#### Session Object
+
+Session fields other than `traits` (the identified user's current profile) are computed from the events inside the requested time range. Sessions are ordered by `session_end`, newest first.
+
+<TypeTable
+ type={{
+ session_id: {
+ description: 'Unique session identifier',
+ type: 'string',
+ },
+ user_id: {
+ description: 'Device fingerprint identifier',
+ type: 'string',
+ },
+ identified_user_id: {
+ description: 'Custom user ID when identified, otherwise empty',
+ type: 'string',
+ },
+ traits: {
+ description: 'Traits of the identified user, or null',
+ type: 'object | null',
+ },
+ country: {
+ description: 'Country code (latest event)',
+ type: 'string',
+ },
+ region: {
+ description: 'Region code (latest event)',
+ type: 'string',
+ },
+ city: {
+ description: 'City (latest event)',
+ type: 'string',
+ },
+ language: {
+ description: 'Browser language (latest event)',
+ type: 'string',
+ },
+ device_type: {
+ description: 'Device type',
+ type: 'string',
+ },
+ browser: {
+ description: 'Browser name',
+ type: 'string',
+ },
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
+ operating_system: {
+ description: 'Operating system',
+ type: 'string',
+ },
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
+ screen_width: {
+ description: 'Screen width in pixels',
+ type: 'number',
+ },
+ screen_height: {
+ description: 'Screen height in pixels',
+ type: 'number',
+ },
+ referrer: {
+ description: 'Session referrer',
+ type: 'string',
+ },
+ channel: {
+ description: 'Traffic channel',
+ type: 'string',
+ },
+ hostname: {
+ description: 'Hostname of the first event',
+ type: 'string',
+ },
+ page_title: {
+ description: 'Page title of the first event',
+ type: 'string',
+ },
+ querystring: {
+ description: 'Query string of the first event',
+ type: 'string',
+ },
+ utm_source: {
+ description: 'UTM source of the first event',
+ type: 'string',
+ },
+ utm_medium: {
+ description: 'UTM medium of the first event',
+ type: 'string',
+ },
+ utm_campaign: {
+ description: 'UTM campaign of the first event',
+ type: 'string',
+ },
+ utm_term: {
+ description: 'UTM term of the first event',
+ type: 'string',
+ },
+ utm_content: {
+ description: 'UTM content of the first event',
+ type: 'string',
+ },
+ session_start: {
+ description: 'First event time in the session',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_end: {
+ description: 'Last event time in the session',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_duration: {
+ description: 'Seconds between first and last event',
+ type: 'number',
+ },
+ entry_page: {
+ description: 'First page viewed',
+ type: 'string',
+ },
+ exit_page: {
+ description: 'Last page viewed',
+ type: 'string',
+ },
+ pageviews: {
+ description: 'Number of pageviews',
+ type: 'number',
+ },
+ events: {
+ description: 'Number of custom events',
+ type: 'number',
+ },
+ errors: {
+ description: 'Number of error events',
+ type: 'number',
+ },
+ outbound: {
+ description: 'Number of outbound link clicks',
+ type: 'number',
+ },
+ ip: {
+ description: 'Visitor IP address. null unless the site stores IPs (trackIp).',
+ type: 'string | null',
+ },
+ lat: {
+ description: 'Latitude (latest event)',
+ type: 'number',
+ },
+ lon: {
+ description: 'Longitude (latest event)',
+ type: 'number',
+ },
+ tag: {
+ description: 'Tag set on the latest event',
+ type: 'string',
+ },
+ has_replay: {
+ description: '1 when the session has a replay with at least two recorded events, otherwise 0',
+ type: 'number',
+ },
+ }}
+/>
+
+Returns `400` for fewer than 2 steps, a `stepNumber` outside the steps, an invalid `mode`, or an invalid `replays_only`.
+
</div>
<div className="flex flex-col gap-4">
@@ -299,18 +474,43 @@ var data = await response.Content.ReadAsStringAsync();
{
"session_id": "sess_abc123",
"user_id": "user_xyz789",
+ "identified_user_id": "",
+ "traits": null,
"country": "US",
+ "region": "US-CA",
+ "city": "San Francisco",
+ "language": "en-US",
+ "device_type": "desktop",
"browser": "Chrome",
+ "browser_version": "128.0",
"operating_system": "macOS",
- "device_type": "desktop",
+ "operating_system_version": "14.5",
+ "screen_width": 1920,
+ "screen_height": 1080,
+ "referrer": "https://google.com",
+ "channel": "Organic Search",
+ "hostname": "example.com",
+ "page_title": "Home",
+ "querystring": "",
+ "utm_source": "",
+ "utm_medium": "",
+ "utm_campaign": "",
+ "utm_term": "",
+ "utm_content": "",
+ "session_start": "2024-01-31 14:00:00",
+ "session_end": "2024-01-31 14:02:05",
+ "session_duration": 125,
"entry_page": "/",
"exit_page": "/pricing",
"pageviews": 3,
- "session_duration": 125,
- "session_start": "2024-01-31T14:00:00.000Z",
- "session_end": "2024-01-31T14:02:05.000Z",
- "referrer": "https://google.com",
- "channel": "organic"
+ "events": 0,
+ "errors": 0,
+ "outbound": 0,
+ "ip": null,
+ "lat": 37.77,
+ "lon": -122.42,
+ "tag": "",
+ "has_replay": 0
}
]
}
diff --git a/docs/content/docs/api/getting-started.mdx b/docs/content/docs/api/getting-started.mdx
index 103adead9..c116a92c0 100644
--- a/docs/content/docs/api/getting-started.mdx
+++ b/docs/content/docs/api/getting-started.mdx
@@ -32,11 +32,19 @@ Looking for what to *build* with the API? These end-to-end recipes chain endpoin
- [**Find Where Users Drop Off**](/docs/api/funnel-dropoff) β€” locate the biggest leak in a funnel, then see where the people who abandon go instead.
- [**Compare Channel Performance**](/docs/api/channel-performance) β€” rank acquisition channels by how well they convert, not just how much traffic they send.
- [**Build a Live Visitor Feed**](/docs/api/live-feed) β€” poll the events endpoint for a real-time activity stream you can render or alert on.
-- [**Export Events to a Warehouse**](/docs/api/export-events) β€” backfill your full event history and keep it in sync with an incremental job.
## Authentication
-All API requests must include authentication using one of the following methods:
+Most requests need a credential, sent one of the ways below. Two exceptions:
+
+- **Public sites.** Read endpoints for a site with [Public Analytics](/docs/site-settings#public-analytics) turned on answer without any credential.
+- **Private links.** Send a site's private link key in an `x-private-key` header to read that site's analytics without a credential, the same access a [private dashboard link](/docs/embeds/dashboard) gives. A rotated key stops working immediately.
+
+```bash
+x-private-key: your_private_link_key
+```
+
+Both only cover reads that the public dashboard can make (analytics, sessions, events, users, funnels, goals, segments, annotations and similar). Settings, organization endpoints, and writes other than event ingestion need a credential. [`POST /api/track`](/docs/api/sending-events) accepts events without one, as the browser script does; an API key with `ingest:write` additionally lets you set the visitor's IP and user agent.
### Bearer Token (Recommended)
@@ -54,6 +62,10 @@ Authorization: Bearer your_api_key_here
Query parameters expose API keys in server logs and browser history. Use only for quick testing.
</Callout>
+### Session cookie
+
+Requests from a signed-in dashboard session (the Better Auth session cookie) are also accepted. A few account endpoints, such as creating a personal API key or managing keys and invitations under `/api/auth/*`, accept only a session. In production the cookie is named `__Secure-better-auth.session_token`. A `POST` to `/api/auth/*` that sends a cookie must also send an `Origin` header for your Rybbit instance (for example `Origin: https://app.rybbit.io`), or it is refused with `403` and code `MISSING_OR_NULL_ORIGIN`.
+
## Generating API Keys
Rybbit has two kinds of API keys:
@@ -75,7 +87,51 @@ Rybbit has two kinds of API keys:
3. Enter a name for the key and click **Create**
4. Copy the key immediately (it won't be shown again)
-Both kinds support restricting a key to specific permissions when you create it β€” leave restrictions off for a full-access key.
+Both kinds support restricting a key to specific scopes when you create it. Leave restrictions off for a full-access key.
+
+## Roles and Scopes
+
+A request is allowed only if the caller's **role** permits it and, for API keys and OAuth tokens, the credential's **scopes** do too.
+
+### Roles
+
+Each organization member has one role. Every role can do everything the roles below it can:
+
+| Role | Can |
+|------|-----|
+| `owner` | Everything, including billing and deleting the organization |
+| `admin` | Manage members, teams and API keys; create, delete and transfer sites. Sees every site |
+| `editor` | Configure sites: tracking settings, feature flags, experiments, imports, Search Console. Manage everyone's segments and annotations |
+| `member` | Build reports: goals, funnels, dashboards, their own segments and annotations |
+| `viewer` | Read everything they can reach; change nothing |
+
+Below admin, a member can be limited to specific sites, and a per-site grant (direct or through a [team](/docs/teams)) can raise their role on a site to `editor`, `member` or `viewer`. A grant never lowers a role. Organization keys act with `admin` authority over every site in their organization. Personal keys act with your role.
+
+### Scopes
+
+A scoped key carries `resource:action` pairs. `write` implies `read` on the same resource. Requests outside a key's scopes get `403` with `"error": "Insufficient scope"` and the missing scope in `required`.
+
+| Resource | Actions | Covers |
+|----------|---------|--------|
+| `analytics` | `read` | Overview, metrics, time series, performance, bots, journeys, retention, PDF export |
+| `sessions` | `read` | Sessions |
+| `events` | `read` | Events |
+| `users` | `read`, `write` | Users and user traits |
+| `goals` | `read`, `write` | Goals |
+| `funnels` | `read`, `write` | Funnels |
+| `dashboards` | `read`, `write` | Dashboards |
+| `annotations` | `read`, `write` | Annotations |
+| `segments` | `read`, `write` | Saved segments, and the `segment_id` parameter |
+| `flags` | `read`, `write` | Feature flags |
+| `experiments` | `read`, `write` | Experiments |
+| `sites` | `read`, `write` | Site settings, creating, deleting and transferring sites, imports |
+| `gsc` | `read`, `write` | Google Search Console |
+| `org` | `read`, `write` | Organizations, members, teams |
+| `replay` | `read`, `write` | Session replay |
+| `sql` | `read` | Custom SQL queries |
+| `ingest` | `write` | Sending events |
+
+Scopes never raise a role: an `org:write` key still needs an admin behind it to add members. Some account surfaces (creating API keys, billing, account settings) reject scoped keys and organization keys outright, whatever their scopes. Cookie sessions are never scope-limited.
### Rate Limits (Cloud Only)
@@ -121,6 +177,8 @@ Analytics and management endpoints report your current budget on every response,
Treat these as advisory: a few endpoints resolve credentials outside the standard path and omit them. `Retry-After` on a `429` is always present.
+To check an organization's daily quota without spending a request against a site, call `GET /api/organizations/:organizationId/api-usage` (role `viewer` or above; keys need `org:read`). It returns `dailyUsed`, `dailyLimit`, `dailyRemaining`, `resetsInSeconds`, `burstLimit` and `burstWindowSeconds`, plus `metered` (`false` on self-hosted) and `available` (`false` when the counter could not be read). It covers the organization's own keys only; personal keys are budgeted per user and are not counted here.
+
#### When you hit a limit
A `429` names the limit you hit and tells you how long to wait, in seconds:
@@ -144,7 +202,7 @@ The following parameters are shared across all analytics endpoints.
### Time Parameters
-All endpoints require date-based, exact datetime, or relative time parameters:
+Time parameters are optional on most endpoints. With none, a query covers all time. A few endpoints differ: retention defaults to the last 90 days, and PDF export requires `start_date`, `end_date` and `time_zone`. To narrow a query, pass one of the ranges below:
<TypeTable
type={{
@@ -163,7 +221,7 @@ All endpoints require date-based, exact datetime, or relative time parameters:
time_zone: {
description: 'IANA timezone identifier',
type: 'string',
- typeDescription: 'e.g., "America/New_York", "Europe/London", "Asia/Tokyo". Required with date and exact datetime ranges.',
+ typeDescription: 'e.g., "America/New_York", "Europe/London", "Asia/Tokyo". Defaults to UTC. Sets which midnight a date range uses and the timezone of time buckets.',
required: false,
},
start_datetime: {
@@ -193,10 +251,16 @@ All endpoints require date-based, exact datetime, or relative time parameters:
}}
/>
-**Note:** You must provide either:
-- All three date parameters (`start_date`, `end_date`, `time_zone`), OR
-- All three exact datetime parameters (`start_datetime`, `end_datetime`, `time_zone`), OR
-- Both relative parameters (`past_minutes_start`, `past_minutes_end`)
+**Note:** Each range's parameters come in pairs. Send both or neither:
+- `start_date` and `end_date` (both days inclusive; when `end_date` is today, the range ends now)
+- `start_datetime` and `end_datetime`
+- `past_minutes_start` and `past_minutes_end`
+
+Half a pair, a malformed value, or an invalid `time_zone` returns `400`, as does a datetime or past-minutes range whose start isn't before its end. A date range may start and end on the same day; a reversed date range isn't rejected, it just matches nothing. If you send more than one range, the date range wins, then the datetime range, then past minutes.
+
+### Timestamps in responses
+
+Analytics timestamps (events, sessions, users, time-series buckets) and most stored records come back as `YYYY-MM-DD HH:MM:SS`, sometimes with fractional seconds (`2024-01-15 13:00:00.123`), without a `T` or a `Z`. Event and session timestamps are UTC; time-series bucket values are wall-clock times in the requested `time_zone`. Some endpoints, such as retention and annotations, return ISO 8601 strings with `T` and a zone instead. Parse defensively rather than with a parser that assumes local time. In JavaScript, for a UTC value: `new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(ts) ? ts : ts.replace(' ', 'T') + 'Z')`.
#### Examples
@@ -219,7 +283,7 @@ All endpoints require date-based, exact datetime, or relative time parameters:
The `filters` parameter accepts a JSON-encoded array of filter objects to narrow down your data.
-You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), instead of or alongside `filters`. The segment's filters are expanded on the server and ANDed with any `filters` you pass. Use the [Segments endpoints](/docs/api/segments/list) to find IDs. Public and private-link callers can only use segments marked as shown on the public dashboard.
+You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), instead of or alongside `filters`. The segment's filters are expanded on the server and ANDed with any `filters` you pass. Use the [Segments endpoints](/docs/api/segments/list) to find IDs. Public and private-link callers can only use segments marked as shown on the public dashboard. A scoped API key also needs `segments:read` to pass `segment_id`, whatever scope the endpoint itself requires.
```
?start_date=2024-01-01&end_date=2024-01-31&time_zone=UTC&segment_id=12
@@ -238,13 +302,13 @@ You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), ins
type: {
description: 'The type of comparison to perform',
type: 'FilterType',
- typeDescription: '"equals" | "not_equals" | "contains" | "not_contains" | "regex" | "not_regex" | "greater_than" | "less_than"',
+ typeDescription: 'One of the 14 types under Filter Types below',
required: true,
},
value: {
description: 'Array of values to match against',
type: 'Array<string | number>',
- typeDescription: 'Multiple values are treated as OR conditions',
+ typeDescription: 'Multiple values are ORed; for not_equals and not_contains they are ANDed (matches none of them). Ignored by is_null and is_not_null. Comparison types, regex and not_regex use only the first value',
required: true,
},
}}
@@ -274,29 +338,61 @@ You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), ins
type: 'string',
typeDescription: 'Value must not contain the substring',
},
+ starts_with: {
+ description: 'Prefix match',
+ type: 'string',
+ typeDescription: 'Value must start with the string',
+ },
+ ends_with: {
+ description: 'Suffix match',
+ type: 'string',
+ typeDescription: 'Value must end with the string',
+ },
regex: {
description: 'Regular expression match',
type: 'string',
- typeDescription: 'Value must match the regex pattern (max 500 characters)',
+ typeDescription: 'Value must match the regex pattern (RE2 syntax: no lookaround or backreferences; max 500 characters)',
},
not_regex: {
description: 'Exclude regex matches',
type: 'string',
typeDescription: 'Value must not match the regex pattern',
},
+ is_null: {
+ description: 'Value is missing',
+ type: 'none',
+ typeDescription: 'Matches empty values; send "value": []',
+ },
+ is_not_null: {
+ description: 'Value is present',
+ type: 'none',
+ typeDescription: 'Matches non-empty values; send "value": []',
+ },
greater_than: {
description: 'Numeric greater than',
type: 'number',
- typeDescription: 'For numeric fields like lat, lon',
+ typeDescription: 'lat and lon only',
},
less_than: {
description: 'Numeric less than',
type: 'number',
- typeDescription: 'For numeric fields like lat, lon',
+ typeDescription: 'lat and lon only',
+ },
+ greater_than_or_equal: {
+ description: 'Numeric greater than or equal',
+ type: 'number',
+ typeDescription: 'lat and lon only',
+ },
+ less_than_or_equal: {
+ description: 'Numeric less than or equal',
+ type: 'number',
+ typeDescription: 'lat and lon only',
},
}}
/>
+The four comparison types only work on `lat` and `lon`, and `lat`/`lon` take no string types (`contains`, `not_contains`, `starts_with`, `ends_with`, `regex`, `not_regex`). Either mismatch returns `400`.
+
#### Available Filter Parameters
**Browser & Device**
@@ -465,9 +561,21 @@ You can also pass `segment_id`, the ID of a [saved segment](/docs/segments), ins
type: 'string',
typeDescription: 'Filters to sessions containing the event',
},
+ tag: {
+ description: 'Tag set by the tracking script',
+ type: 'string',
+ typeDescription: 'The data-tag value from the tracking script',
+ },
+ 'feature_flag:<key>': {
+ description: 'Value of a feature flag recorded on the event',
+ type: 'string',
+ typeDescription: 'Replace <key> with the flag key, e.g. "feature_flag:new_checkout"',
+ },
}}
/>
+`tag` filters on the `data-tag` value set by the tracking script ([Tagging](/docs/tagging)). `feature_flag:<key>` filters on the value a [feature flag](/docs/feature-flags) had when the event was recorded.
+
#### Filter Examples
<Tabs items={['Single Filter', 'Multiple Filters', 'Contains', 'Regex', 'Numeric', 'URL-encoded']}>
@@ -551,20 +659,36 @@ Geolocation comparison:
## Error Responses
-All endpoints return standard HTTP status codes:
+Endpoints use standard HTTP status codes:
-- **200** - Success
-- **400** - Bad Request (invalid parameters)
-- **401** - Unauthorized (missing or invalid API key)
-- **403** - Forbidden (no access to site)
-- **404** - Not Found (site doesn't exist)
-- **429** - Too Many Requests (rate limit exceeded)
-- **500** - Internal Server Error
+- **200** - Success (some create endpoints return **201**)
+- **400** - Bad request: invalid parameters, body, filters, or time range
+- **401** - No usable credential where one is required (organization and account endpoints), or a credential the endpoint can't act for
+- **403** - Forbidden. On site endpoints this is also what a missing or invalid API key gets, and what a site ID that doesn't exist gets, so a site's existence isn't revealed. Also returned when your role or the key's scopes fall short
+- **404** - Not found: a malformed site ID, an unknown text site identifier, or a resource that doesn't exist inside a site you can access (a segment, goal, funnel and so on). A numeric site ID you can't access returns `403`, not `404`
+- **409** - Conflict with the current state
+- **429** - Rate limit exceeded (see [Rate Limits](#rate-limits-cloud-only))
+- **500** - Internal server error
### Error Response Format
+Every error from `/api` has the same shape, except the MCP endpoint and Better Auth routes under `/api/auth/*`, which return their own error bodies:
+
```json
{
- "error": "Error message describing what went wrong"
+ "error": "Insufficient role",
+ "code": "FORBIDDEN",
+ "message": "Insufficient role",
+ "resolution": "Use a credential with the required scope and Site or Organization access.",
+ "required": "admin"
}
```
+
+| Field | Meaning |
+|-------|---------|
+| `error` | Human-readable error, kept for backward compatibility |
+| `code` | Machine-readable code. Endpoints that don't set one get a default per status: `INVALID_REQUEST`, `AUTHENTICATION_REQUIRED`, `FORBIDDEN`, `NOT_FOUND`, `CONFLICT`, `RATE_LIMITED`, `INTERNAL_ERROR` |
+| `message` | Human-readable explanation |
+| `resolution` | What to do about it |
+
+Some errors add fields. Role and scope failures (`"Insufficient role"`, `"Insufficient scope"`) usually include `required`, the role or `resource:action` scope you need; it is omitted when the endpoint rejects scoped keys outright. `429` responses usually include `scope` and `retryAfter`, and most include `limit`; the `Retry-After` header is always set. Branch on `code` and `required` when present, not on the text of `error`.
diff --git a/docs/content/docs/api/goals/create.mdx b/docs/content/docs/api/goals/create.mdx
index 4e888c96c..1beeaf5e3 100644
--- a/docs/content/docs/api/goals/create.mdx
+++ b/docs/content/docs/api/goals/create.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:site/goals
```
-Creates a new goal for tracking conversions.
+Creates a new goal for tracking conversions. Requires the member role or above on the site (the `goals:write` permission). Returns `201` on success and `400` with `details` when the body fails validation.
### Path Parameters
@@ -52,35 +52,40 @@ Creates a new goal for tracking conversions.
}}
/>
-#### GoalConfig for Path Goals
+#### GoalConfig Object
+
+Which fields apply depends on `goalType`. Path goals need `pathPattern` and event goals need `eventName`; autocapture goals need nothing, and match every event of their type when `valuePattern` is omitted.
<TypeTable
type={{
pathPattern: {
- description: 'URL path pattern to match. Supports wildcards (*)',
+ description: 'path goals: URL path pattern. * matches within one path segment, ** across segments. Required for path goals.',
type: 'string',
- required: true,
- typeDescription: 'e.g., "/checkout/*", "/signup/complete"',
+ required: false,
},
- }}
-/>
-
-#### GoalConfig for Event Goals
-
-<TypeTable
- type={{
eventName: {
- description: 'Event name to match',
+ description: 'event goals: custom event name to match exactly. Required for event goals.',
type: 'string',
- required: true,
+ required: false,
+ },
+ valuePattern: {
+ description: 'Autocapture goals (outbound, button_click, form_submit, copy): wildcard pattern matched against the destination URL (outbound), the button or copied text (button_click, copy), or the form name, ID, or action (form_submit). * matches one or more characters, ** zero or more. Omit to match every event of the type.',
+ type: 'string',
+ typeDescription: 'Max 512 characters',
+ required: false,
+ },
+ propertyFilters: {
+ description: 'Exact-match filters that must all pass. For event and autocapture goals they match event properties; for path goals they match URL query parameters. Property values are compared as strings: a boolean or number stored as a native JSON value (e.g. `{ gift: true }`) does not match.',
+ type: 'Array<{ key: string; value: string | number | boolean }>',
+ required: false,
},
eventPropertyKey: {
- description: 'Property key to match (optional)',
+ description: 'Deprecated: use propertyFilters. Single property key; ignored when propertyFilters is set. Must be sent together with eventPropertyValue.',
type: 'string',
required: false,
},
eventPropertyValue: {
- description: 'Property value to match (required if key is provided)',
+ description: 'Deprecated: use propertyFilters. Single property value; ignored when propertyFilters is set.',
type: 'string | number | boolean',
required: false,
},
diff --git a/docs/content/docs/api/goals/delete.mdx b/docs/content/docs/api/goals/delete.mdx
index f97a4dc31..646c5249c 100644
--- a/docs/content/docs/api/goals/delete.mdx
+++ b/docs/content/docs/api/goals/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/goals/:goalId
```
-Deletes a goal. This action cannot be undone.
+Deletes a goal. This action cannot be undone. Requires the member role or above on the site (the `goals:write` permission). Returns `404` if the goal does not exist and `403` if it belongs to another site.
### Path Parameters
diff --git a/docs/content/docs/api/goals/list.mdx b/docs/content/docs/api/goals/list.mdx
index 53bb0de93..df80e4414 100644
--- a/docs/content/docs/api/goals/list.mdx
+++ b/docs/content/docs/api/goals/list.mdx
@@ -41,14 +41,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
default: 1,
},
page_size: {
- description: 'Number of results per page (max 100)',
+ description: 'Number of results per page, 1-100. Out-of-range values return 400.',
type: 'number',
default: 10,
},
sort: {
description: 'Field to sort by',
type: 'string',
- typeDescription: '"goalId" | "name" | "goalType" | "createdAt"',
+ typeDescription: '"goalId" | "name" | "goalType" | "createdAt" (other values fall back to createdAt)',
default: 'createdAt',
},
order: {
@@ -90,7 +90,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
goalType: {
description: 'Type of goal',
type: 'string',
- typeDescription: '"path" | "event"',
+ typeDescription: '"path" | "event" | "outbound" | "button_click" | "form_submit" | "copy"',
},
config: {
description: 'Goal configuration',
@@ -98,8 +98,8 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
},
createdAt: {
description: 'Creation timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
total_conversions: {
description: 'Number of sessions that completed the goal',
@@ -121,22 +121,33 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
pathPattern: {
- description: 'URL path pattern (for path goals). Supports wildcards (*)',
+ description: 'path goals: URL path pattern. * matches within one path segment, ** across segments. Required for path goals.',
type: 'string',
required: false,
},
eventName: {
- description: 'Event name to match (for event goals)',
+ description: 'event goals: custom event name to match exactly. Required for event goals.',
type: 'string',
required: false,
},
+ valuePattern: {
+ description: 'Autocapture goals (outbound, button_click, form_submit, copy): wildcard pattern matched against the destination URL (outbound), the button or copied text (button_click, copy), or the form name, ID, or action (form_submit). * matches one or more characters, ** zero or more. Omit to match every event of the type.',
+ type: 'string',
+ typeDescription: 'Max 512 characters',
+ required: false,
+ },
+ propertyFilters: {
+ description: 'Exact-match filters that must all pass. For event and autocapture goals they match event properties; for path goals they match URL query parameters. Property values are compared as strings: a boolean or number stored as a native JSON value (e.g. `{ gift: true }`) does not match.',
+ type: 'Array<{ key: string; value: string | number | boolean }>',
+ required: false,
+ },
eventPropertyKey: {
- description: 'Event property key to match',
+ description: 'Deprecated: use propertyFilters. Single property key; ignored when propertyFilters is set. Must be sent together with eventPropertyValue.',
type: 'string',
required: false,
},
eventPropertyValue: {
- description: 'Event property value to match',
+ description: 'Deprecated: use propertyFilters. Single property value; ignored when propertyFilters is set.',
type: 'string | number | boolean',
required: false,
},
@@ -327,7 +338,7 @@ class Program
"config": {
"pathPattern": "/signup/complete"
},
- "createdAt": "2024-01-10T12:00:00.000Z",
+ "createdAt": "2024-01-10 12:00:00.123456",
"total_conversions": 1250,
"total_sessions": 15420,
"conversion_rate": 0.081
@@ -341,7 +352,7 @@ class Program
"eventPropertyKey": "value",
"eventPropertyValue": 100
},
- "createdAt": "2024-01-15T09:30:00.000Z",
+ "createdAt": "2024-01-15 09:30:00.654321",
"total_conversions": 320,
"total_sessions": 15420,
"conversion_rate": 0.021
diff --git a/docs/content/docs/api/goals/sessions.mdx b/docs/content/docs/api/goals/sessions.mdx
index 3ddc92bfd..5bd8fb3a2 100644
--- a/docs/content/docs/api/goals/sessions.mdx
+++ b/docs/content/docs/api/goals/sessions.mdx
@@ -66,6 +66,8 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
#### Session Object
+Session fields are computed from the events inside the requested time range. Sessions are ordered by `session_end`, newest first.
+
<TypeTable
type={{
session_id: {
@@ -73,54 +75,152 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'string',
},
user_id: {
- description: 'User identifier',
+ description: 'Device fingerprint identifier',
type: 'string',
},
country: {
- description: 'Country code',
+ description: 'Country code (latest event)',
+ type: 'string',
+ },
+ region: {
+ description: 'Region code (latest event)',
+ type: 'string',
+ },
+ city: {
+ description: 'City (latest event)',
+ type: 'string',
+ },
+ language: {
+ description: 'Browser language (latest event)',
+ type: 'string',
+ },
+ device_type: {
+ description: 'Device type',
type: 'string',
},
browser: {
description: 'Browser name',
type: 'string',
},
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
operating_system: {
description: 'Operating system',
type: 'string',
},
- device_type: {
- description: 'Device type',
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
+ screen_width: {
+ description: 'Screen width in pixels',
+ type: 'number',
+ },
+ screen_height: {
+ description: 'Screen height in pixels',
+ type: 'number',
+ },
+ referrer: {
+ description: 'Referrer of the first event',
type: 'string',
},
+ channel: {
+ description: 'Traffic channel of the first event',
+ type: 'string',
+ },
+ hostname: {
+ description: 'Hostname of the first event',
+ type: 'string',
+ },
+ page_title: {
+ description: 'Page title of the first event',
+ type: 'string',
+ },
+ querystring: {
+ description: 'Query string of the first event',
+ type: 'string',
+ },
+ utm_source: {
+ description: 'UTM source',
+ type: 'string',
+ },
+ utm_medium: {
+ description: 'UTM medium',
+ type: 'string',
+ },
+ utm_campaign: {
+ description: 'UTM campaign',
+ type: 'string',
+ },
+ utm_term: {
+ description: 'UTM term',
+ type: 'string',
+ },
+ utm_content: {
+ description: 'UTM content',
+ type: 'string',
+ },
+ session_start: {
+ description: 'First event time in the session',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_end: {
+ description: 'Last event time in the session',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_duration: {
+ description: 'Seconds between first and last event',
+ type: 'number',
+ },
entry_page: {
- description: 'First page visited',
+ description: 'First page viewed',
type: 'string',
},
exit_page: {
- description: 'Last page visited',
+ description: 'Last page viewed',
type: 'string',
},
pageviews: {
description: 'Number of pageviews',
type: 'number',
},
- session_duration: {
- description: 'Session duration in seconds',
+ events: {
+ description: 'Number of custom events',
type: 'number',
},
- session_start: {
- description: 'Session start time',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ errors: {
+ description: 'Number of error events',
+ type: 'number',
},
- session_end: {
- description: 'Session end time',
+ outbound: {
+ description: 'Number of outbound link clicks',
+ type: 'number',
+ },
+ ip: {
+ description: 'Visitor IP address. null unless the site stores IPs (trackIp).',
+ type: 'string | null',
+ },
+ lat: {
+ description: 'Latitude (latest event)',
+ type: 'number',
+ },
+ lon: {
+ description: 'Longitude (latest event)',
+ type: 'number',
+ },
+ tag: {
+ description: 'Tag set on the latest event',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
},
}}
/>
+Returns `404` if the goal does not exist and `403` if it belongs to another site.
+
</div>
<div className="flex flex-col gap-4">
@@ -302,17 +402,39 @@ class Program
"session_id": "sess_abc123",
"user_id": "user_xyz789",
"country": "US",
+ "region": "US-CA",
+ "city": "San Francisco",
+ "language": "en-US",
+ "device_type": "desktop",
"browser": "Chrome",
+ "browser_version": "128.0",
"operating_system": "macOS",
- "device_type": "desktop",
+ "operating_system_version": "14.5",
+ "screen_width": 1920,
+ "screen_height": 1080,
+ "referrer": "https://google.com",
+ "channel": "Organic Search",
+ "hostname": "example.com",
+ "page_title": "Home",
+ "querystring": "",
+ "utm_source": "",
+ "utm_medium": "",
+ "utm_campaign": "",
+ "utm_term": "",
+ "utm_content": "",
+ "session_start": "2024-01-31 14:00:00",
+ "session_end": "2024-01-31 14:04:05",
+ "session_duration": 245,
"entry_page": "/",
"exit_page": "/signup/complete",
"pageviews": 5,
- "session_duration": 245,
- "session_start": "2024-01-31T14:00:00.000Z",
- "session_end": "2024-01-31T14:04:05.000Z",
- "referrer": "https://google.com",
- "channel": "organic"
+ "events": 1,
+ "errors": 0,
+ "outbound": 0,
+ "ip": null,
+ "lat": 37.77,
+ "lon": -122.42,
+ "tag": ""
}
]
}
diff --git a/docs/content/docs/api/goals/time-series.mdx b/docs/content/docs/api/goals/time-series.mdx
index 2f45de1fd..e3662d116 100644
--- a/docs/content/docs/api/goals/time-series.mdx
+++ b/docs/content/docs/api/goals/time-series.mdx
@@ -63,12 +63,25 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
### Response
+<TypeTable
+ type={{
+ data: {
+ description: 'One point per goal per bucket. Empty when goal_ids is missing or matches no goal on this site.',
+ type: 'GoalTimeSeriesPoint[]',
+ },
+ }}
+/>
+
+Returns `400` for an unknown `bucket`.
+
+#### GoalTimeSeriesPoint Object
+
<TypeTable
type={{
time: {
description: 'Start of the time bucket',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'Bucket start in the requested time_zone, "YYYY-MM-DD HH:MM:SS"',
},
goal_id: {
description: 'ID of the goal',
@@ -215,14 +228,14 @@ var data = await response.Content.ReadAsStringAsync();
{
"data": [
{
- "time": "2024-01-01T00:00:00.000Z",
+ "time": "2024-01-01 00:00:00",
"goal_id": 1,
"conversions": 84,
"total_sessions": 1250,
"conversion_rate": 0.0672
},
{
- "time": "2024-01-02T00:00:00.000Z",
+ "time": "2024-01-02 00:00:00",
"goal_id": 1,
"conversions": 97,
"total_sessions": 1420,
diff --git a/docs/content/docs/api/goals/update.mdx b/docs/content/docs/api/goals/update.mdx
index ee764b173..b1038330d 100644
--- a/docs/content/docs/api/goals/update.mdx
+++ b/docs/content/docs/api/goals/update.mdx
@@ -15,7 +15,11 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:site/goals/:goalId
```
-Updates an existing goal.
+Updates an existing goal. Requires the member role or above on the site (the `goals:write` permission).
+
+This is a full replacement, not a partial update: send `goalType` and the whole `config` every time. Omitting `name` clears it to `null`. The body is validated the same way as [Create Goal](/docs/api/goals/create), which documents the `GoalConfig` fields.
+
+Returns `404` if the goal does not exist and `403` if it belongs to another site.
### Path Parameters
@@ -39,14 +43,14 @@ Updates an existing goal.
<TypeTable
type={{
name: {
- description: 'Updated goal name',
+ description: 'Goal name. Omitting it sets the name to null.',
type: 'string',
required: false,
},
goalType: {
description: 'Type of goal',
type: 'string',
- typeDescription: '"path" | "event"',
+ typeDescription: '"path" | "event" | "outbound" | "button_click" | "form_submit" | "copy"',
required: true,
},
config: {
diff --git a/docs/content/docs/api/imports/delete.mdx b/docs/content/docs/api/imports/delete.mdx
index 912ddc039..2f055aa9a 100644
--- a/docs/content/docs/api/imports/delete.mdx
+++ b/docs/content/docs/api/imports/delete.mdx
@@ -1,6 +1,6 @@
---
title: Delete Import
-description: Deletes an import and all events it added. The import must be finished.
+description: Deletes an import and all events it added. The import must be finished, or started more than 2 hours ago.
full: true
method: DELETE
---
@@ -15,9 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/imports/:importId
```
-Deletes an import and all events it added. The import must be finished. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
+Deletes an import and all events it added. The import must be finished, or started more than 2 hours ago. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
-A still-running import cannot be deleted and returns HTTP `400`.
+An unfinished import started within the last 2 hours is treated as still running and returns HTTP `400`. After 2 hours an unfinished import (for example, one whose uploader stopped before sending `isLastBatch`) can be deleted. Returns `404` if the import does not exist and `403` if it belongs to another site.
### Path Parameters
diff --git a/docs/content/docs/api/imports/events.mdx b/docs/content/docs/api/imports/events.mdx
index 9b02cbc6f..b038c896d 100644
--- a/docs/content/docs/api/imports/events.mdx
+++ b/docs/content/docs/api/imports/events.mdx
@@ -41,7 +41,7 @@ Upload events in batches. The request body limit is 50 MB, so split large export
<TypeTable
type={{
events: {
- description: 'Raw, platform-specific event objects whose shape matches the platform chosen when the import was created (Umami, Simple Analytics, or Plausible export rows)',
+ description: 'Platform-specific event objects matching the platform chosen when the import was created: Umami or Simple Analytics export rows, or, for Plausible, per-event objects (timestamp, session_id, user_id, hostname, pathname, ...) such as the synthetic events the dashboard builds from Plausible aggregate CSV exports. Every key of the platform shape must be present as a string.',
type: 'object[]',
required: true,
},
@@ -55,7 +55,14 @@ Upload events in batches. The request body limit is 50 MB, so split large export
### Response
-Returns `200 OK` with an empty body. Events outside your plan's retention window are skipped and reflected in the import's `skippedEvents` / `invalidEvents` counts (see [List Imports](/docs/api/imports/list)).
+Returns `200 OK` with an empty body. Progress shows up in the import's counts (see [List Imports](/docs/api/imports/list)):
+
+- `400` for the whole batch if the events don't all fit one platform's shape (a missing key, a non-string value, or rows from different platforms in the same batch). Nothing from that batch is stored.
+- The shape check accepts any of the three platforms before the import's own platform is used. A batch in another platform's shape (for example, Umami rows sent to a Plausible import) returns `200`, but every event is dropped and counted in `invalidEvents`.
+- An event whose values don't validate (bad timestamp, malformed ID, over-long field) is dropped and counted in `invalidEvents`.
+- An event is skipped and counted in `skippedEvents` when its timestamp is in the future, is older than your plan's historical window, or falls in a month whose import quota is already used up.
+
+Other errors: `403` on the Rybbit Cloud free plan, `404` if the import does not exist (a site that doesn't exist gets `403`), `400` if the import belongs to another site.
</div>
<div className="flex flex-col gap-4">
diff --git a/docs/content/docs/api/imports/list.mdx b/docs/content/docs/api/imports/list.mdx
index 66f83a3b8..cb22ca87e 100644
--- a/docs/content/docs/api/imports/list.mdx
+++ b/docs/content/docs/api/imports/list.mdx
@@ -1,6 +1,6 @@
---
title: List Imports
-description: Returns all data imports for a site with their progress counts.
+description: Returns the 10 most recent data imports for a site with their progress counts.
full: true
method: GET
---
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:site/imports
```
-Returns all data imports for a site with their progress counts. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
+Returns the 10 most recent data imports for a site, newest first, with their progress counts. Requires the editor role or above on the site. On Rybbit Cloud, this requires a paid plan.
### Path Parameters
@@ -63,22 +63,22 @@ This endpoint takes no query parameters.
type: 'number',
},
skippedEvents: {
- description: 'Number of events skipped (e.g. outside the retention window)',
+ description: 'Number of events skipped: timestamp in the future, older than the plan\'s historical window, or over the monthly import quota for its month',
type: 'number',
},
invalidEvents: {
- description: 'Number of events rejected as invalid',
+ description: 'Number of events dropped because their values failed validation',
type: 'number',
},
startedAt: {
description: 'When the import started',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
completedAt: {
description: 'When the import finished, or null while it is still running',
type: 'string | null',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
}}
/>
@@ -256,23 +256,23 @@ class Program
```json title="Response"
{
"data": [
- {
- "importId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
- "platform": "plausible",
- "importedEvents": 15420,
- "skippedEvents": 120,
- "invalidEvents": 3,
- "startedAt": "2024-01-10T12:00:00.000Z",
- "completedAt": "2024-01-10T12:04:30.000Z"
- },
{
"importId": "9a1c8f2e-3b7d-4e1a-9c0f-2d5b6a7e8f10",
"platform": "umami",
"importedEvents": 8200,
"skippedEvents": 0,
"invalidEvents": 0,
- "startedAt": "2024-01-15T09:30:00.000Z",
+ "startedAt": "2024-01-15 09:30:00.789",
"completedAt": null
+ },
+ {
+ "importId": "f47ac10b-58cc-4372-a567-0e02b2c3d479",
+ "platform": "plausible",
+ "importedEvents": 15420,
+ "skippedEvents": 120,
+ "invalidEvents": 3,
+ "startedAt": "2024-01-10 12:00:00.123",
+ "completedAt": "2024-01-10 12:04:30.456"
}
]
}
diff --git a/docs/content/docs/api/insights/journeys.mdx b/docs/content/docs/api/insights/journeys.mdx
index a4c940db1..e3af0ef63 100644
--- a/docs/content/docs/api/insights/journeys.mdx
+++ b/docs/content/docs/api/insights/journeys.mdx
@@ -46,9 +46,9 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
default: 100,
},
stepFilters: {
- description: 'JSON object to filter specific steps (e.g., {"0": "/"})',
+ description: 'JSON object pinning steps to a page (e.g., {"0": "/"}). A journey is the first `steps` pages of a session, so step 0 is always the landing page: {"0": "/pricing"} keeps sessions that landed on /pricing, not every session that visited it',
type: 'string',
- typeDescription: 'JSON string mapping step index to required path',
+ typeDescription: 'JSON string mapping step index (0-based) to a path or pattern',
required: false,
},
endsAt: {
@@ -78,7 +78,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'Journey[]',
},
totalSessions: {
- description: 'Sessions that visited two or more pages in the period, before stepFilters and endsAt are applied',
+ description: 'Sessions that visited two or more pages in the period, before stepFilters and endsAt are applied. It is 0 when no journeys match, because the total is read from the journey rows',
type: 'number',
},
}}
diff --git a/docs/content/docs/api/live-feed.mdx b/docs/content/docs/api/live-feed.mdx
index 82f66a636..20f880946 100644
--- a/docs/content/docs/api/live-feed.mdx
+++ b/docs/content/docs/api/live-feed.mdx
@@ -7,7 +7,7 @@ import { Callout } from 'fumadocs-ui/components/callout';
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
import { Step, Steps } from 'fumadocs-ui/components/steps';
-Rybbit doesn't push a websocket stream, but the events endpoint is built for polling: pass a `since_timestamp` and you get only the events that happened after it. This guide builds a self-advancing feed loop you can wire into a dashboard, a terminal ticker, or an alerting rule.
+Rybbit doesn't push a websocket stream, but the events endpoint is built for polling: pass a `since_cursor` and you get the events that arrived after it, plus the cursor to send next time. This guide builds a self-advancing feed loop you can wire into a dashboard, a terminal ticker, or an alerting rule.
**Endpoints used:**
@@ -16,22 +16,26 @@ Rybbit doesn't push a websocket stream, but the events endpoint is built for pol
## How incremental polling works
-The events endpoint returns the newest events first. To stream without duplicates, remember the timestamp of the most recent event you've seen and send it as `since_timestamp` on the next request β€” the API returns only events newer than that, up to 500 per call.
+Every event in the response has an `event_cursor`, its exact place in the event log. Cursors are what you page and poll with:
<Steps>
<Step>
-**Fetch the initial batch** to establish a starting watermark (the newest timestamp).
+**Fetch the initial batch** with `page_size`. Polling starts 5 seconds before the response's `cursor.newestCursor`, so the first poll gets the same overlap as the ones after it (`cursor.oldestCursor` is for scrolling back with `before_cursor`). A cursor is `<epoch milliseconds>_<16 hex digits>`, so subtract 5000 from the first part and use sixteen zeros for the second.
</Step>
<Step>
-**On an interval, request events `since_timestamp`** = your watermark.
+**On an interval, request events with `since_cursor`** set to the cursor you are holding. The response carries `cursor.nextCursor` and `cursor.hasMore`.
</Step>
<Step>
-**Process the new events** (print, render, alert) and advance the watermark to the newest one returned.
+**Process the new events**, skipping any whose `event_cursor` you have already seen, and keep `nextCursor` for the next poll. If `hasMore` is `true`, poll again straight away.
</Step>
</Steps>
-<Callout type="info">
-`since_timestamp` returns up to **500** events per call. If you expect more than 500 events between polls (a very high-traffic site with a long interval), poll more frequently so each batch stays under the cap.
+A `since_cursor` poll reads up to **500** events, starting with the oldest after the cursor, so a backlog bigger than that is read over several polls instead of being skipped (`hasMore` tells you more are waiting). The events in `data` are still sorted newest first.
+
+Events are written in small batches, so one can land slightly after a later one. To avoid missing those, a poll never starts later than 5 seconds before the request, and `nextCursor` points at that overlap. The next poll can therefore return events you already have: drop them by `event_cursor`.
+
+<Callout type="warn">
+`since_timestamp` and `before_timestamp` still work but are legacy whole-second bounds. They skip events that share the boundary second, and `since_timestamp` returns the newest 500 events after it, so a larger backlog loses its oldest events. Use cursors for anything that must not miss events.
</Callout>
## Full script
@@ -67,20 +71,42 @@ function describe(e) {
return `β€’ ${e.type} β€” ${where}`;
}
-let watermark = null; // ISO timestamp of the newest event we've shown
+let cursor = null; // where the next poll starts
+const seen = new Set(); // event_cursor values already shown (polls overlap by a few seconds)
+const SEEN_MAX = 5000;
+
+// Timestamps are UTC, formatted "YYYY-MM-DD HH:MM:SS" with no zone marker
+const toDate = (ts) => new Date(ts.replace(' ', 'T') + 'Z');
async function poll() {
try {
- const params = watermark ? { since_timestamp: watermark } : { page_size: 20 };
- const [{ data: events }, count] = await Promise.all([get('/events', params), liveCount()]);
+ const polling = cursor !== null; // false for the initial load
+ const params = polling ? { since_cursor: cursor } : { page_size: 20 };
+ const [res, count] = await Promise.all([get('/events', params), liveCount()]);
// Events come back newest-first; show oldest-first so the feed reads top-to-bottom
- for (const e of [...events].reverse()) {
- console.log(`[${new Date(e.timestamp).toLocaleTimeString()}] ${describe(e)}`);
+ for (const e of [...res.data].reverse()) {
+ if (seen.has(e.event_cursor)) continue;
+ seen.add(e.event_cursor);
+ console.log(`[${toDate(e.timestamp).toLocaleTimeString()}] ${describe(e)}`);
+ }
+ // Keep memory bounded by forgetting the oldest cursors; the recent ones cover the overlap
+ for (const old of seen) {
+ if (seen.size <= SEEN_MAX) break;
+ seen.delete(old);
+ }
+
+ if (polling) {
+ cursor = res.cursor.nextCursor;
+ } else if (res.cursor.newestCursor) {
+ // Initial load: start 5 seconds before the newest event, the same overlap
+ // later polls get (newestCursor is null on a site with no events yet)
+ const [ms] = res.cursor.newestCursor.split('_');
+ cursor = `${Number(ms) - 5000}_0000000000000000`;
}
- if (events.length) watermark = events[0].timestamp; // newest event becomes the new watermark
process.stdout.write(`\n🟒 ${count} visitors online\n`);
+ if (polling && res.cursor.hasMore) return poll(); // backlog: read the next 500 now
} catch (err) {
console.error('poll error:', err.message);
}
@@ -94,7 +120,7 @@ setInterval(poll, POLL_MS);
<Tab value="Python">
```python title="live_feed.py"
import os, time
-from datetime import datetime
+from datetime import datetime, timezone
import requests
API = "https://app.rybbit.io"
@@ -127,25 +153,42 @@ def describe(e):
return f'β€’ {e["type"]} β€” {where}'
-watermark = None # ISO timestamp of the newest event we've shown
+cursor = None # where the next poll starts
+seen = {} # event_cursor values already shown, oldest first (polls overlap by a few seconds)
+SEEN_MAX = 5000
print("Starting live feed… (Ctrl+C to stop)")
while True:
+ has_more = False
try:
- params = {"since_timestamp": watermark} if watermark else {"page_size": 20}
- events = get("/events", **params)["data"]
+ res = get("/events", **({"since_cursor": cursor} if cursor else {"page_size": 20}))
# Events come back newest-first; show oldest-first so the feed reads top-to-bottom
- for e in reversed(events):
- ts = datetime.fromisoformat(e["timestamp"].replace("Z", "+00:00")).strftime("%H:%M:%S")
- print(f"[{ts}] {describe(e)}")
- if events:
- watermark = events[0]["timestamp"] # newest event becomes the new watermark
+ for e in reversed(res["data"]):
+ if e["event_cursor"] in seen:
+ continue
+ seen[e["event_cursor"]] = True
+ # Timestamps are UTC, formatted "YYYY-MM-DD HH:MM:SS" with no zone marker
+ ts = datetime.strptime(e["timestamp"][:19], "%Y-%m-%d %H:%M:%S").replace(tzinfo=timezone.utc)
+ print(f"[{ts.astimezone().strftime('%H:%M:%S')}] {describe(e)}")
+ # Keep memory bounded by forgetting the oldest cursors; the recent ones cover the overlap
+ while len(seen) > SEEN_MAX:
+ del seen[next(iter(seen))]
+
+ if cursor:
+ cursor = res["cursor"]["nextCursor"]
+ has_more = res["cursor"]["hasMore"]
+ elif res["cursor"]["newestCursor"]:
+ # Initial load: start 5 seconds before the newest event, the same overlap
+ # later polls get (newestCursor is None on a site with no events yet)
+ ms = int(res["cursor"]["newestCursor"].split("_")[0])
+ cursor = f"{ms - 5000}_0000000000000000"
print(f"\n🟒 {live_count()} visitors online\n")
except Exception as err:
print(f"poll error: {err}")
- time.sleep(POLL_SECONDS)
+ if not has_more: # with a backlog, read the next 500 straight away
+ time.sleep(POLL_SECONDS)
```
</Tab>
</Tabs>
@@ -168,7 +211,9 @@ Because each poll hands you the raw events, you can act on them instead of just
<Tabs items={['JavaScript']}>
<Tab value="JavaScript">
```javascript title="React to specific events"
-for (const e of events) {
+// Inside poll(), before the loop that prints new events and adds them to `seen`:
+for (const e of res.data) {
+ if (seen.has(e.event_cursor)) continue; // already handled in an earlier poll
if (e.type === 'pageview' && e.pathname === '/enterprise') {
await fetch(process.env.SLACK_WEBHOOK, {
method: 'POST',
@@ -189,5 +234,4 @@ for (const e of events) {
## Next steps
-- [Events API reference](/docs/api/events/list) β€” full event object fields, plus `before_timestamp` for scrolling backwards through history.
-- [Export Raw Events to Your Warehouse](/docs/api/export-events) β€” the same `since_timestamp` mechanism, used for durable incremental syncs instead of a live view.
+- [Events API reference](/docs/api/events/list) β€” full event object fields, plus `before_cursor` for scrolling backwards through history.
diff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.json
index fa5b9534d..88136408f 100644
--- a/docs/content/docs/api/meta.json
+++ b/docs/content/docs/api/meta.json
@@ -13,6 +13,7 @@
"---Endpoints---",
"sending-events",
"overview",
+ "pages",
"sessions",
"session-replay",
"users",
@@ -26,6 +27,8 @@
"errors",
"bots",
"insights",
+ "query",
+ "search-console",
"---Management---",
"organizations",
"teams",
diff --git a/docs/content/docs/api/organizations/add-member.mdx b/docs/content/docs/api/organizations/add-member.mdx
index d34be5b12..95b2c2d52 100644
--- a/docs/content/docs/api/organizations/add-member.mdx
+++ b/docs/content/docs/api/organizations/add-member.mdx
@@ -5,6 +5,7 @@ full: true
method: POST
---
+import { Callout } from 'fumadocs-ui/components/callout';
import { TypeTable } from 'fumadocs-ui/components/type-table';
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
@@ -17,6 +18,8 @@ POST /api/organizations/:organizationId/members
Adds a user to an organization with a specified role. The user must already exist in the system. Requires admin or owner role in the organization. You cannot assign a role above your own.
+<Callout type="warn">Call this with your dashboard session or a **personal** API key; keys need the `org:write` scope. An **organization** API key passes the role check but has no user behind it, so the request returns `401`.</Callout>
+
### Path Parameters
<TypeTable
@@ -50,7 +53,7 @@ Adds a user to an organization with a specified role. The user must already exis
### Response
-Returns a success message when the user is added successfully.
+Returns `201` with a success message when the user is added.
<TypeTable
type={{
@@ -70,7 +73,11 @@ Returns a success message when the user is added successfully.
type: 'object',
},
'401': {
- description: 'Unauthorized (not an admin/owner of the organization)',
+ description: 'No credential, or an organization API key (no user to act as)',
+ type: 'object',
+ },
+ '403': {
+ description: 'Caller is below admin ("Insufficient role", with `required`), not a member of the organization, missing the `org:write` scope, assigning a role above their own ("You cannot assign a role above your own"), or the plan\'s member limit is reached',
type: 'object',
},
'404': {
@@ -264,11 +271,17 @@ var data = await response.Content.ReadAsStringAsync();
}
```
-```json title="Error Response (401 - Unauthorized)"
+```json title="Error Response (403 - Not an admin)"
{
- "error": "Unauthorized"
+ "error": "Insufficient role",
+ "code": "FORBIDDEN",
+ "message": "Insufficient role",
+ "resolution": "Use a credential with the required scope and Site or Organization access.",
+ "required": "admin"
}
```
+Every error body also carries `code`, `message` and `resolution`; see [Error Responses](/docs/api/getting-started#error-responses).
+
</div>
</div>
diff --git a/docs/content/docs/api/organizations/api-usage.mdx b/docs/content/docs/api/organizations/api-usage.mdx
new file mode 100644
index 000000000..b021e2630
--- /dev/null
+++ b/docs/content/docs/api/organizations/api-usage.mdx
@@ -0,0 +1,201 @@
+---
+title: Get Organization API Usage
+description: Returns today's API request usage and limits for the organization's API keys.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/organizations/:organizationId/api-usage
+```
+
+Returns how much of today's [daily API quota](/docs/api/getting-started#rate-limits-cloud-only) the organization's own API keys (`rb_org_`) have used. Personal keys are budgeted per user and aren't included.
+
+**Permissions:** the `viewer` role or above in the organization. API keys need the `org:read` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "Organization ID",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ metered: {
+ description: "False on self-hosted instances, where API requests aren't metered (the daily figures are then 0)",
+ type: "boolean",
+ },
+ available: {
+ description: "False when the usage counter couldn't be read. The quota is still enforced; dailyUsed is then reported as 0 and dailyRemaining as the full dailyLimit, so the real remainder may be lower",
+ type: "boolean",
+ },
+ dailyUsed: {
+ description: "Requests made today",
+ type: "number",
+ },
+ dailyLimit: {
+ description: "The organization's daily quota",
+ type: "number",
+ },
+ dailyRemaining: {
+ description: "Requests left today",
+ type: "number",
+ },
+ resetsInSeconds: {
+ description: "Seconds until the quota resets at 00:00 UTC",
+ type: "number",
+ },
+ burstLimit: {
+ description: "Burst bucket size",
+ type: "number",
+ },
+ burstWindowSeconds: {
+ description: "Seconds for the burst bucket to refill completely",
+ type: "number",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/organizations/org_123/api-usage" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/organizations/org_123/api-usage',
+ {
+ 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://app.rybbit.io/api/organizations/org_123/api-usage',
+ 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://app.rybbit.io/api/organizations/org_123/api-usage');
+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://app.rybbit.io/api/organizations/org_123/api-usage')
+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://app.rybbit.io/api/organizations/org_123/api-usage", 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://app.rybbit.io/api/organizations/org_123/api-usage")
+ .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://app.rybbit.io/api/organizations/org_123/api-usage"))
+ .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://app.rybbit.io/api/organizations/org_123/api-usage");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "metered": true,
+ "available": true,
+ "dailyUsed": 1284,
+ "dailyLimit": 25000,
+ "dailyRemaining": 23716,
+ "resetsInSeconds": 34200,
+ "burstLimit": 50,
+ "burstWindowSeconds": 10
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/organizations/create-site.mdx b/docs/content/docs/api/organizations/create-site.mdx
index 13e453ed2..b15b5babc 100644
--- a/docs/content/docs/api/organizations/create-site.mdx
+++ b/docs/content/docs/api/organizations/create-site.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/organizations/:organizationId/sites
```
-Creates a new site within an organization. Requires admin or owner role in the organization.
+Creates a new site within an organization. Requires admin or owner role in the organization; API keys need the `sites:write` scope.
### Path Parameters
@@ -34,11 +34,16 @@ Creates a new site within an organization. Requires admin or owner role in the o
<TypeTable
type={{
domain: {
- description: 'Site domain',
+ description: 'Site domain, or for a mobile app its bundle/package identifier. A leading http(s):// and trailing slashes are stripped',
type: 'string',
- typeDescription: 'Valid domain format (e.g., example.com)',
+ typeDescription: 'Web: a domain like example.com. Mobile: an identifier like com.example.app',
required: true,
},
+ type: {
+ description: 'Kind of site. Mobile sites cannot enable sessionReplay or webVitals',
+ type: '"web" | "mobile"',
+ default: '"web"',
+ },
name: {
description: 'Site display name',
type: 'string',
@@ -94,6 +99,11 @@ Creates a new site within an organization. Requires admin or owner role in the o
type: 'boolean',
default: true,
},
+ trackUrlFragments: {
+ description: 'Keep the URL fragment (#...) in tracked page paths',
+ type: 'boolean',
+ default: false,
+ },
trackInitialPageView: {
description: 'Automatically track the initial page view',
type: 'boolean',
@@ -134,7 +144,7 @@ Creates a new site within an organization. Requires admin or owner role in the o
### Response
-Returns the created site object with the assigned `siteId`.
+Returns `201` with the created site object, including the assigned `siteId`. `type` is `null` for web sites.
<TypeTable
type={{
@@ -233,6 +243,25 @@ Returns the created site object with the assigned `siteId`.
}}
/>
+### Error Responses
+
+<TypeTable
+ type={{
+ '400': {
+ description: 'Invalid domain or app identifier, or sessionReplay/webVitals on a mobile site',
+ type: 'object',
+ },
+ '403': {
+ description: 'Caller is below admin or the key lacks sites:write; or, on Rybbit Cloud: session replay without a plan that includes it, webVitals/trackErrors/trackButtonClicks/trackCopy/trackFormInteractions without an active subscription, or the plan\'s site limit is reached',
+ type: 'object',
+ },
+ '404': {
+ description: 'Organization not found (Rybbit Cloud)',
+ type: 'object',
+ },
+ }}
+/>
+
</div>
<div className="flex flex-col gap-4">
@@ -401,10 +430,11 @@ var data = await response.Content.ReadAsStringAsync();
</Tab>
</Tabs>
-```json title="Response"
+```json title="Response (201)"
{
"siteId": 456,
"id": "a1b2c3d4e5f6",
+ "type": null,
"domain": "example.com",
"name": "My Website",
"organizationId": "org_123",
@@ -419,6 +449,7 @@ var data = await response.Content.ReadAsStringAsync();
"trackErrors": false,
"trackOutbound": true,
"trackUrlParams": true,
+ "trackUrlFragments": false,
"trackInitialPageView": true,
"trackSpaNavigation": true,
"trackIp": false,
diff --git a/docs/content/docs/api/organizations/create-user.mdx b/docs/content/docs/api/organizations/create-user.mdx
new file mode 100644
index 000000000..af72eef47
--- /dev/null
+++ b/docs/content/docs/api/organizations/create-user.mdx
@@ -0,0 +1,299 @@
+---
+title: Create User in Organization
+description: Creates a new user account with a password and adds it to the organization.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/organizations/:organizationId/users
+```
+
+Creates a new Rybbit account with an email and password and adds it to the organization with the given role, without sending an invitation. To add someone who already has an account, use [Add Member](/docs/api/organizations/add-member); to email an invitation, use [Invite Member](/docs/api/organizations/invite-member).
+
+**Permissions:** the `admin` role or above in the organization. API keys need the `org:write` scope. You can't assign a role above your own. The new member is checked against your own membership, so organization API keys are rejected with `401`.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "Organization ID",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ email: {
+ description: "Email address for the new account (stored lowercased). Must not belong to an existing user",
+ type: "string",
+ required: true,
+ },
+ password: {
+ description: "Password for the new account",
+ type: "string",
+ typeDescription: "At least 8 characters",
+ required: true,
+ },
+ role: {
+ description: "Role in the organization",
+ type: "string",
+ typeDescription: "\"owner\" | \"admin\" | \"editor\" | \"member\" | \"viewer\"",
+ required: true,
+ },
+ name: {
+ description: "Display name. Defaults to the email address",
+ type: "string",
+ required: false,
+ },
+ }}
+/>
+
+### Response
+
+Returns `201`.
+
+<TypeTable
+ type={{
+ message: {
+ description: "Success message",
+ type: "string",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Missing email, password or role; invalid role; password under 8 characters; or a user with this email already exists",
+ type: "object",
+ },
+ "401": {
+ description: "No user behind the credential (organization API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Not an admin or owner, a role above your own, or the organization is at its plan's member limit",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/organizations/org_123/users" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "email": "[email protected]",
+ "name": "Jane Doe",
+ "password": "a-long-password",
+ "role": "viewer"
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/organizations/org_123/users',
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ email: '[email protected]',
+ name: 'Jane Doe',
+ password: 'a-long-password',
+ role: 'viewer'
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/organizations/org_123/users',
+ json={
+ 'email': '[email protected]',
+ 'name': 'Jane Doe',
+ 'password': 'a-long-password',
+ 'role': 'viewer'
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'email' => '[email protected]',
+ 'name' => 'Jane Doe',
+ 'password' => 'a-long-password',
+ 'role' => 'viewer'
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/organizations/org_123/users');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/organizations/org_123/users')
+request = Net::HTTP::Post.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ email: '[email protected]',
+ name: 'Jane Doe',
+ password: 'a-long-password',
+ role: 'viewer'
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "email": "[email protected]",
+ "name": "Jane Doe",
+ "password": "a-long-password",
+ "role": "viewer",
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/organizations/org_123/users", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "email": "[email protected]",
+ "name": "Jane Doe",
+ "password": "a-long-password",
+ "role": "viewer"
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/organizations/org_123/users")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "email": "[email protected]",
+ "name": "Jane Doe",
+ "password": "a-long-password",
+ "role": "viewer"
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/organizations/org_123/users"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ email = "[email protected]",
+ name = "Jane Doe",
+ password = "a-long-password",
+ role = "viewer"
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/organizations/org_123/users", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "message": "User created and added to organization successfully"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/organizations/invite-member.mdx b/docs/content/docs/api/organizations/invite-member.mdx
index d5b4cd13f..e9ca55e2a 100644
--- a/docs/content/docs/api/organizations/invite-member.mdx
+++ b/docs/content/docs/api/organizations/invite-member.mdx
@@ -18,7 +18,7 @@ POST /api/auth/organization/invite-member
Sends an invitation email inviting a user to join an organization with a given role. (To add an existing user directly without an email invite, see Add Member.)
-<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie with the request.</Callout>
+<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie and an `Origin` header for your Rybbit instance with the request; without `Origin` it returns `403` (`MISSING_OR_NULL_ORIGIN`). You must be an **owner or admin** of the organization to invite members.</Callout>
### Request Body
@@ -30,8 +30,8 @@ Sends an invitation email inviting a user to join an organization with a given r
required: true,
},
role: {
- description: 'Role to assign: `owner`, `admin`, `editor`, `member` or `viewer`. You cannot assign a role above your own.',
- type: 'string | string[]',
+ description: 'Exactly one role: `owner`, `admin`, `editor`, `member` or `viewer`. Anything else, including an array, returns `400`. Only owners can invite owners.',
+ type: 'string',
required: true,
},
organizationId: {
@@ -122,7 +122,8 @@ Returns the created invitation object.
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/auth/organization/invite-member" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Origin: https://app.rybbit.io" \
-H "Content-Type: application/json" \
-d '{"email": "[email protected]", "role": "member"}'
```
@@ -158,7 +159,8 @@ response = requests.post(
'role': 'member'
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin': 'https://app.rybbit.io'
}
)
@@ -176,7 +178,8 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'role' => 'member'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin: https://app.rybbit.io',
'Content-Type: application/json'
]);
@@ -193,7 +196,8 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/organization/invite-member")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Origin'] = 'https://app.rybbit.io'
req['Content-Type'] = 'application/json'
req.body = {
@@ -211,7 +215,8 @@ body := bytes.NewBuffer([]byte(`{
"role": "member"
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/auth/organization/invite-member", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Origin", "https://app.rybbit.io")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -227,7 +232,8 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/auth/organization/invite-member")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.json(&serde_json::json!({
"email": "[email protected]",
"role": "member"
@@ -244,7 +250,8 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"email\": \"[email protected]\", \"role\": \"member\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/organization/invite-member"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -255,7 +262,8 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Origin", "https://app.rybbit.io");
var content = new StringContent(
"{\"email\": \"[email protected]\", \"role\": \"member\"}",
diff --git a/docs/content/docs/api/organizations/list.mdx b/docs/content/docs/api/organizations/list.mdx
index f06e1faec..3c51b2903 100644
--- a/docs/content/docs/api/organizations/list.mdx
+++ b/docs/content/docs/api/organizations/list.mdx
@@ -1,6 +1,6 @@
---
title: Get My Organizations
-description: Returns all organizations the authenticated user is a member of, including all members for each organization. Excludes subscription and billing information. Supports both session cookies and API key (Bearer token) authentication.
+description: Returns the organizations the caller belongs to, with the sites the caller can access in each. Excludes subscription and billing information. Supports both session cookies and API key (Bearer token) authentication.
full: true
method: GET
---
@@ -16,9 +16,11 @@ import { Callout } from 'fumadocs-ui/components/callout';
GET /api/organizations
```
-Returns all organizations the authenticated user is a member of, including all members for each organization. Excludes subscription and billing information. Supports both session cookies and API key (Bearer token) authentication.
+Returns the organizations the caller belongs to, with the sites the caller can access in each. Excludes subscription and billing information. Supports both session cookies and API key (Bearer token) authentication, and needs no particular scope.
-<Callout type="warn">The `members` roster is only populated for session-cookie (dashboard) requests. API key / Bearer callers receive `members: []` for every organization β€” use [GET /organizations/:id/members](/docs/api/organizations/members) to retrieve member data with a key.</Callout>
+<Callout type="warn">The `members` roster is only populated for session-cookie (dashboard) requests. API key / Bearer callers receive `members: []` for every organization; use [GET /organizations/:id/members](/docs/api/organizations/members) to retrieve member data with a key.</Callout>
+
+<Callout>A personal API key returns every organization you belong to, with your role in each. An **organization** API key returns only its own organization, with `role` set to `"admin"`.</Callout>
### Response
@@ -273,7 +275,7 @@ var data = await response.Content.ReadAsStringAsync();
</Tab>
</Tabs>
-```json title="Response"
+```json title="Response (API key)"
[
{
"id": "org_123",
@@ -282,30 +284,7 @@ var data = await response.Content.ReadAsStringAsync();
"logo": "https://example.com/logo.png",
"createdAt": "2024-01-15T10:30:00.000Z",
"role": "owner",
- "members": [
- {
- "id": "member_abc123",
- "role": "owner",
- "userId": "user_xyz789",
- "createdAt": "2024-01-15T10:30:00.000Z",
- "user": {
- "id": "user_xyz789",
- "name": "John Doe",
- "email": "[email protected]"
- }
- },
- {
- "id": "member_def456",
- "role": "member",
- "userId": "user_abc456",
- "createdAt": "2024-02-20T14:15:00.000Z",
- "user": {
- "id": "user_abc456",
- "name": "Jane Smith",
- "email": "[email protected]"
- }
- }
- ],
+ "members": [],
"sites": [
{
"id": "456",
@@ -327,30 +306,7 @@ var data = await response.Content.ReadAsStringAsync();
"logo": null,
"createdAt": "2024-03-10T08:00:00.000Z",
"role": "admin",
- "members": [
- {
- "id": "member_ghi789",
- "role": "owner",
- "userId": "user_owner123",
- "createdAt": "2024-03-10T08:00:00.000Z",
- "user": {
- "id": "user_owner123",
- "name": "Alice Johnson",
- "email": "[email protected]"
- }
- },
- {
- "id": "member_jkl012",
- "role": "admin",
- "userId": "user_xyz789",
- "createdAt": "2024-03-12T09:30:00.000Z",
- "user": {
- "id": "user_xyz789",
- "name": "John Doe",
- "email": "[email protected]"
- }
- }
- ],
+ "members": [],
"sites": [
{
"id": "789",
diff --git a/docs/content/docs/api/organizations/members.mdx b/docs/content/docs/api/organizations/members.mdx
index 579f20b25..d5dc20b6a 100644
--- a/docs/content/docs/api/organizations/members.mdx
+++ b/docs/content/docs/api/organizations/members.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/organizations/:organizationId/members
```
-Returns all members of an organization with their user details and roles. Requires membership in the organization.
+Returns all members of an organization with their user details and roles. Requires membership in the organization (`viewer` or above); API keys need the `org:read` scope.
### Path Parameters
@@ -115,8 +115,18 @@ Each member in the `data` array contains:
type: 'boolean',
},
siteIds: {
- description: 'IDs of the sites the member can access (empty when access is not restricted)',
+ description: 'IDs of the sites the member has a per-site grant on',
+ type: 'number[]',
+ },
+ siteRole: {
+ description: "The role every one of the member's grants raises them to; null when the grants carry no role (the organization role applies) or carry different roles",
+ type: 'string | null',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ },
+ siteGrants: {
+ description: 'Each grant with its own role, for resolving the member\'s role per site',
type: 'array',
+ typeDescription: 'Array of { siteId: number, role: "editor" | "member" | "viewer" | null }',
},
}}
/>
@@ -277,7 +287,9 @@ var data = await response.Content.ReadAsStringAsync();
},
"siteAccess": {
"hasRestrictedSiteAccess": false,
- "siteIds": []
+ "siteIds": [],
+ "siteRole": null,
+ "siteGrants": []
},
"teams": []
},
@@ -294,7 +306,9 @@ var data = await response.Content.ReadAsStringAsync();
},
"siteAccess": {
"hasRestrictedSiteAccess": true,
- "siteIds": ["456"]
+ "siteIds": [456],
+ "siteRole": "editor",
+ "siteGrants": [{ "siteId": 456, "role": "editor" }]
},
"teams": [
{
diff --git a/docs/content/docs/api/organizations/meta.json b/docs/content/docs/api/organizations/meta.json
index 05c056437..dfb26e9bb 100644
--- a/docs/content/docs/api/organizations/meta.json
+++ b/docs/content/docs/api/organizations/meta.json
@@ -1,4 +1,17 @@
{
"title": "Organizations",
- "pages": ["list", "sites", "create-site", "members", "add-member", "invite-member", "remove-member", "update-member-role", "event-count"]
+ "pages": [
+ "list",
+ "sites",
+ "create-site",
+ "members",
+ "add-member",
+ "create-user",
+ "invite-member",
+ "remove-member",
+ "update-member-role",
+ "update-member-sites",
+ "event-count",
+ "api-usage"
+ ]
}
diff --git a/docs/content/docs/api/organizations/remove-member.mdx b/docs/content/docs/api/organizations/remove-member.mdx
index 6ea4a0fc5..c545bc727 100644
--- a/docs/content/docs/api/organizations/remove-member.mdx
+++ b/docs/content/docs/api/organizations/remove-member.mdx
@@ -20,7 +20,7 @@ Removes a member from an organization. The member can be identified by member ID
<Callout type="warn">This endpoint uses **POST**, not HTTP DELETE. You cannot remove the only remaining owner of an organization.</Callout>
-<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie with the request.</Callout>
+<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie and an `Origin` header for your Rybbit instance with the request; without `Origin` it returns `403` (`MISSING_OR_NULL_ORIGIN`). You must be an **owner or admin** of the organization to remove members.</Callout>
### Request Body
@@ -86,7 +86,8 @@ Returns the removed member object.
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/auth/organization/remove-member" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Origin: https://app.rybbit.io" \
-H "Content-Type: application/json" \
-d '{"memberIdOrEmail": "[email protected]"}'
```
@@ -120,7 +121,8 @@ response = requests.post(
'memberIdOrEmail': '[email protected]'
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin': 'https://app.rybbit.io'
}
)
@@ -137,7 +139,8 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'memberIdOrEmail' => '[email protected]'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin: https://app.rybbit.io',
'Content-Type: application/json'
]);
@@ -154,7 +157,8 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/organization/remove-member")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Origin'] = 'https://app.rybbit.io'
req['Content-Type'] = 'application/json'
req.body = {
memberIdOrEmail: '[email protected]'
@@ -170,7 +174,8 @@ body := bytes.NewBuffer([]byte(`{
"memberIdOrEmail": "[email protected]"
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/auth/organization/remove-member", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Origin", "https://app.rybbit.io")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -186,7 +191,8 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/auth/organization/remove-member")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.json(&serde_json::json!({
"memberIdOrEmail": "[email protected]"
}))
@@ -202,7 +208,8 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"memberIdOrEmail\": \"[email protected]\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/organization/remove-member"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -213,7 +220,8 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Origin", "https://app.rybbit.io");
var content = new StringContent(
"{\"memberIdOrEmail\": \"[email protected]\"}",
diff --git a/docs/content/docs/api/organizations/sites.mdx b/docs/content/docs/api/organizations/sites.mdx
index 19ccf2212..20ebf0af9 100644
--- a/docs/content/docs/api/organizations/sites.mdx
+++ b/docs/content/docs/api/organizations/sites.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/organizations/:organizationId/sites
```
-Returns all sites in an organization the caller can access, with usage and subscription info.
+Returns all sites in an organization the caller can access, with usage and subscription info. Any member can call it (`viewer` or above); API keys need the `org:read` scope. Sites are sorted by `sessionsLast24Hours`, highest first.
### Path Parameters
@@ -41,6 +41,15 @@ This endpoint takes no query parameters.
description: 'The organization record, or null',
type: 'object | null',
},
+ role: {
+ description: "The caller's role in the organization (organization keys act as admin)",
+ type: 'string | null',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
+ },
+ permissions: {
+ description: 'Permission names that role holds in the organization, e.g. "analytics:read", "sites:create". A scoped key may be narrowed further by its scopes',
+ type: 'string[]',
+ },
sites: {
description: 'Array of site objects',
type: 'array',
@@ -88,7 +97,20 @@ Each site in the `sites` array contains the following fields. Other site-config
type: 'number',
},
isOwner: {
- description: 'Whether the caller owns the site',
+ description: 'Whether the caller is an admin or owner for this site. Despite the name, it does not mean the caller created or owns the site',
+ type: 'boolean',
+ },
+ role: {
+ description: "The caller's role on this site, after site grants and teams",
+ type: 'string',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer"',
+ },
+ permissions: {
+ description: 'Permission names that role holds on this site',
+ type: 'string[]',
+ },
+ requiresPlan: {
+ description: 'True on Rybbit Cloud when the site needs a paid plan to collect data (the organization has no plan and the site was created after free plans ended)',
type: 'boolean',
},
teams: {
@@ -256,6 +278,8 @@ var data = await response.Content.ReadAsStringAsync();
"slug": "acme",
"createdAt": "2024-01-15T10:30:00.000Z"
},
+ "role": "admin",
+ "permissions": ["analytics:read", "sessions:read", "...", "sites:create", "members:manage"],
"sites": [
{
"siteId": 123,
@@ -266,6 +290,9 @@ var data = await response.Content.ReadAsStringAsync();
"organizationId": "org_abc123",
"sessionsLast24Hours": 842,
"isOwner": true,
+ "role": "admin",
+ "permissions": ["analytics:read", "sessions:read", "..."],
+ "requiresPlan": false,
"teams": [
{
"id": "team_xyz789",
diff --git a/docs/content/docs/api/organizations/update-member-role.mdx b/docs/content/docs/api/organizations/update-member-role.mdx
index f2fa8ed3d..5697437c8 100644
--- a/docs/content/docs/api/organizations/update-member-role.mdx
+++ b/docs/content/docs/api/organizations/update-member-role.mdx
@@ -16,19 +16,19 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/auth/organization/update-member-role
```
-Updates the role(s) assigned to an existing organization member.
+Updates the role of an existing organization member.
<Callout>This endpoint uses **POST**, not PUT or PATCH.</Callout>
-<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie with the request.</Callout>
+<Callout type="warn">This endpoint authenticates with your logged-in dashboard **session**, not an API key. Send your session cookie and an `Origin` header for your Rybbit instance with the request; without `Origin` it returns `403` (`MISSING_OR_NULL_ORIGIN`). You must be an **owner or admin** of the organization to change roles.</Callout>
### Request Body
<TypeTable
type={{
role: {
- description: "The new role: `owner`, `admin`, `editor`, `member` or `viewer`. Requires the admin or owner role; only owners can make owners or change an owner's role.",
- type: 'string | string[]',
+ description: "Exactly one role: `owner`, `admin`, `editor`, `member` or `viewer`. Anything else, including an array, returns `400`. Only owners can make owners or change an owner's role.",
+ type: 'string',
required: true,
},
memberId: {
@@ -80,7 +80,8 @@ Returns the updated member object directly β€” the fields are at the top level,
<Tab value="cURL">
```bash title="Request"
curl -X POST "https://app.rybbit.io/api/auth/organization/update-member-role" \
- -H "Cookie: better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Origin: https://app.rybbit.io" \
-H "Content-Type: application/json" \
-d '{"memberId": "mem_7c6d5e4f3g2h", "role": "admin"}'
```
@@ -116,7 +117,8 @@ response = requests.post(
'role': 'admin'
},
headers={
- 'Cookie': 'better-auth.session_token=YOUR_SESSION_TOKEN'
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin': 'https://app.rybbit.io'
}
)
@@ -134,7 +136,8 @@ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'role' => 'admin'
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
- 'Cookie: better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Origin: https://app.rybbit.io',
'Content-Type: application/json'
]);
@@ -151,7 +154,8 @@ require 'json'
uri = URI("https://app.rybbit.io/api/auth/organization/update-member-role")
req = Net::HTTP::Post.new(uri)
-req['Cookie'] = 'better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+req['Origin'] = 'https://app.rybbit.io'
req['Content-Type'] = 'application/json'
req.body = {
memberId: 'mem_7c6d5e4f3g2h',
@@ -169,7 +173,8 @@ body := bytes.NewBuffer([]byte(`{
"role": "admin"
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/auth/organization/update-member-role", body)
-req.Header.Set("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+req.Header.Set("Origin", "https://app.rybbit.io")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
@@ -185,7 +190,8 @@ json.NewDecoder(resp.Body).Decode(&data)
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/auth/organization/update-member-role")
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.json(&serde_json::json!({
"memberId": "mem_7c6d5e4f3g2h",
"role": "admin"
@@ -202,7 +208,8 @@ HttpClient client = HttpClient.newHttpClient();
String json = "{\"memberId\": \"mem_7c6d5e4f3g2h\", \"role\": \"admin\"}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/auth/organization/update-member-role"))
- .header("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Origin", "https://app.rybbit.io")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
@@ -213,7 +220,8 @@ HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.o
<Tab value=".NET">
```csharp title="Request"
using var client = new HttpClient();
-client.DefaultRequestHeaders.Add("Cookie", "better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+client.DefaultRequestHeaders.Add("Origin", "https://app.rybbit.io");
var content = new StringContent(
"{\"memberId\": \"mem_7c6d5e4f3g2h\", \"role\": \"admin\"}",
diff --git a/docs/content/docs/api/organizations/update-member-sites.mdx b/docs/content/docs/api/organizations/update-member-sites.mdx
new file mode 100644
index 000000000..c6a285c6a
--- /dev/null
+++ b/docs/content/docs/api/organizations/update-member-sites.mdx
@@ -0,0 +1,326 @@
+---
+title: Update Member Site Access
+description: Restricts a member to specific sites, optionally raising their role on those sites, or lifts the restriction.
+full: true
+method: PUT
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+PUT /api/organizations/:organizationId/members/:memberId/sites
+```
+
+Sets which sites a member can reach and the role they hold on them. This replaces the member's site grants: the `siteIds` you send become the full list.
+
+- With `hasRestrictedSiteAccess: true`, the member reaches `siteIds` plus any sites granted to teams they belong to.
+- With `hasRestrictedSiteAccess: false`, their per-site grants are removed and they reach every site that isn't limited to a team, plus the sites of their own teams. Sites limited to teams they aren't on stay hidden.
+
+Team grants are managed separately, with [Teams](/docs/api/teams/update).
+
+`siteRole` raises the member's role on the granted sites above their organization role (for example, an organization `viewer` who is an `editor` on one site). It never lowers it, and it stops at `editor`. Admins and owners always reach every site and can't be restricted.
+
+**Permissions:** the `admin` role or above in the organization. API keys need the `org:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "Organization ID",
+ type: "string",
+ required: true,
+ },
+ memberId: {
+ description: "Member record ID (the `id` returned by List Members, not the user ID)",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ hasRestrictedSiteAccess: {
+ description: "Whether the member is limited to siteIds",
+ type: "boolean",
+ required: true,
+ },
+ siteIds: {
+ description: "Sites the member can reach. Every ID must belong to this organization",
+ type: "number[]",
+ required: true,
+ },
+ siteRole: {
+ description: "Role on the granted sites. null grants no raise. Omit to keep the role existing grants carry (new sites get the role all existing grants share)",
+ type: "string | null",
+ typeDescription: "\"editor\" | \"member\" | \"viewer\" | null",
+ required: false,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ memberId: {
+ description: "Member record ID",
+ type: "string",
+ },
+ hasRestrictedSiteAccess: {
+ description: "The restriction now in effect",
+ type: "boolean",
+ },
+ siteAccess: {
+ description: "The member's site grants after the update",
+ type: "{ siteId: number, role: string | null, name: string, domain: string }[]",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid siteRole, a site ID outside the organization, or an attempt to restrict an admin or owner",
+ type: "object",
+ },
+ "403": {
+ description: "Not an admin or owner of the organization, or missing the org:write scope",
+ type: "object",
+ },
+ "404": {
+ description: "Member not found in this organization",
+ type: "object",
+ },
+ }}
+/>
+
+</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 PUT "https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "hasRestrictedSiteAccess": true,
+ "siteIds": [
+ 123,
+ 456
+ ],
+ "siteRole": "editor"
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites',
+ {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ hasRestrictedSiteAccess: true,
+ siteIds: [123, 456],
+ siteRole: 'editor'
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.put(
+ 'https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites',
+ json={
+ 'hasRestrictedSiteAccess': True,
+ 'siteIds': [123, 456],
+ 'siteRole': 'editor'
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'hasRestrictedSiteAccess' => true,
+ 'siteIds' => [123, 456],
+ 'siteRole' => 'editor'
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites')
+request = Net::HTTP::Put.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ hasRestrictedSiteAccess: true,
+ siteIds: [123, 456],
+ siteRole: 'editor'
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "hasRestrictedSiteAccess": true,
+ "siteIds": []interface{}{123, 456},
+ "siteRole": "editor",
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("PUT", "https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "hasRestrictedSiteAccess": true,
+ "siteIds": [
+ 123,
+ 456
+ ],
+ "siteRole": "editor"
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .put("https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "hasRestrictedSiteAccess": true,
+ "siteIds": [
+ 123,
+ 456
+ ],
+ "siteRole": "editor"
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ hasRestrictedSiteAccess = true,
+ siteIds = new[] { 123, 456 },
+ siteRole = "editor"
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PutAsync("https://app.rybbit.io/api/organizations/org_123/members/mem_7c6d5e4f3g2h/sites", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "memberId": "mem_7c6d5e4f3g2h",
+ "hasRestrictedSiteAccess": true,
+ "siteAccess": [
+ {
+ "siteId": 123,
+ "role": "editor",
+ "name": "Acme",
+ "domain": "acme.com"
+ },
+ {
+ "siteId": 456,
+ "role": "editor",
+ "name": "Acme Docs",
+ "domain": "docs.acme.com"
+ }
+ ]
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/overview/metric.mdx b/docs/content/docs/api/overview/metric.mdx
index adea9f2b8..cbe69a538 100644
--- a/docs/content/docs/api/overview/metric.mdx
+++ b/docs/content/docs/api/overview/metric.mdx
@@ -36,9 +36,9 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
parameter: {
- description: 'The dimension to break down by',
+ description: 'The dimension to break down by. There is no default: a missing or unknown value fails with 500.',
type: 'FilterParameter',
- typeDescription: 'e.g., "pathname", "country", "browser", "event_name"',
+ typeDescription: 'e.g., "pathname", "entry_page", "exit_page", "page_title", "country", "browser", "event_name"',
required: true,
},
limit: {
@@ -59,7 +59,18 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
data: {
- description: 'Array of metric results',
+ description: 'The page of results and the total count',
+ type: 'MetricPage',
+ },
+ }}
+/>
+
+#### MetricPage Object
+
+<TypeTable
+ type={{
+ data: {
+ description: 'Array of metric results, sorted by count descending',
type: 'MetricItem[]',
typeDescription: 'See MetricItem structure below',
},
@@ -89,22 +100,37 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
typeDescription: 'Range: 0-100',
},
pageviews: {
- description: 'Total pageviews (for page-related parameters)',
+ description: 'For pathname: pageviews of this page. For entry_page and exit_page: number of sessions that entered or exited on this page, not total pageviews. For other session dimensions: total pageviews of the sessions with this value. Not returned for page_title or event_name.',
type: 'number',
required: false,
},
pageviews_percentage: {
- description: 'Share of total pageviews (for page-related parameters)',
+ description: 'Share of total pageviews. Returned with pageviews.',
type: 'number',
typeDescription: 'Range: 0-100',
required: false,
},
bounce_rate: {
- description: 'Bounce rate percentage',
- type: 'number',
+ description: 'Percentage of sessions with a single pageview. Not returned for event_name.',
+ type: 'number | null',
typeDescription: 'Range: 0-100',
required: false,
},
+ hostname: {
+ description: 'Most common hostname for this path. Only for pathname, entry_page and exit_page.',
+ type: 'string',
+ required: false,
+ },
+ time_on_page_seconds: {
+ description: 'Average seconds on this page before the next pageview (0 for the last page of a session, each view capped at 1800). Only for pathname, entry_page and exit_page.',
+ type: 'number',
+ required: false,
+ },
+ pathname: {
+ description: 'A representative path for this title. Only for page_title.',
+ type: 'string',
+ required: false,
+ },
}}
/>
diff --git a/docs/content/docs/api/pages/list.mdx b/docs/content/docs/api/pages/list.mdx
new file mode 100644
index 000000000..aaff357c9
--- /dev/null
+++ b/docs/content/docs/api/pages/list.mdx
@@ -0,0 +1,327 @@
+---
+title: Get Pages
+description: Returns one row per page path or per section, with pageviews, sessions, entries, exits, time on page and bounce rate.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/pages
+```
+
+Returns the Pages report: one row per path (or per section, the first path segment), with entry, exit, time-on-page and bounce figures computed from the same pass over the site's pageviews. Within the requested time range, a pageview with no earlier pageview in its session is an entry, one with no later pageview is an exit, and one with neither is a bounce.
+
+**Permissions:** any role on the site (`viewer` and above). API keys need the `analytics:read` scope. Public sites and [private links](/docs/api/sites/get-private-link) can read it without a key.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Query Parameters
+
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (time and filters). Time parameters are optional; omit them for all-time data.
+
+<TypeTable
+ type={{
+ group: {
+ description: "Return one row per path, or one row per section",
+ type: "string",
+ typeDescription: "\"page\" | \"section\"",
+ default: "page",
+ required: false,
+ },
+ section: {
+ description: "Only paths in this section (e.g. \"/docs\"). Page rows only. Max 2048 characters",
+ type: "string",
+ required: false,
+ },
+ mode: {
+ description: "`entry` keeps only rows with entries, `exit` only rows with exits",
+ type: "string",
+ typeDescription: "\"all\" | \"entry\" | \"exit\"",
+ default: "all",
+ required: false,
+ },
+ sort: {
+ description: "Sort column",
+ type: "string",
+ typeDescription: "\"pageviews\" | \"sessions\" | \"entries\" | \"exits\" | \"time_on_page\" | \"bounce_rate\"",
+ default: "pageviews",
+ required: false,
+ },
+ order: {
+ description: "Sort direction. Nulls sort last either way",
+ type: "string",
+ typeDescription: "\"asc\" | \"desc\"",
+ default: "desc",
+ required: false,
+ },
+ search: {
+ description: "Case-insensitive substring matched against the path or title. Page rows only. Max 200 characters",
+ type: "string",
+ required: false,
+ },
+ limit: {
+ description: "Rows per page",
+ type: "number",
+ typeDescription: "1-100",
+ default: 25,
+ required: false,
+ },
+ page: {
+ description: "Page number (1-indexed)",
+ type: "number",
+ typeDescription: "1-10000",
+ default: 1,
+ required: false,
+ },
+ }}
+/>
+
+`section` and `search` can't be combined with `group=section`; the request is rejected with a `400`.
+
+### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: "Paginated result",
+ type: "{ data: PageRow[], totalCount: number }",
+ },
+ }}
+/>
+
+#### PageRow Object
+
+<TypeTable
+ type={{
+ kind: {
+ description: "Row type. With `group=section`, a section that contains only one page is returned as that page",
+ type: "string",
+ typeDescription: "\"page\" | \"section\"",
+ },
+ key: {
+ description: "The path for a page row, the section for a section row",
+ type: "string",
+ },
+ title: {
+ description: "The page's most recent non-empty title; empty for sections and untitled pages",
+ type: "string",
+ },
+ section: {
+ description: "The first path segment the row belongs to (e.g. \"/docs\" for \"/docs/api\"); \"/\" is its own section",
+ type: "string",
+ },
+ pages: {
+ description: "Number of distinct paths in the row (1 for a page row)",
+ type: "number",
+ },
+ pageviews: {
+ description: "Total pageviews",
+ type: "number",
+ },
+ sessions: {
+ description: "Unique sessions that viewed the page",
+ type: "number",
+ },
+ entries: {
+ description: "Pageviews that were the first of their session",
+ type: "number",
+ },
+ exits: {
+ description: "Pageviews that were the last of their session",
+ type: "number",
+ },
+ bounced_entries: {
+ description: "Entries that were the only pageview of their session",
+ type: "number",
+ },
+ time_on_page_seconds: {
+ description: "Average seconds to the next pageview, capped at 1800 per view. Exit views have no next view and are left out of the average",
+ type: "number | null",
+ },
+ bounce_rate: {
+ description: "bounced_entries as a percentage of entries; null when the row has no entries",
+ type: "number | null",
+ typeDescription: "Range: 0-100",
+ },
+ }}
+/>
+
+`totalCount` is the number of rows across all pages of results.
+
+</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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25',
+ {
+ 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://app.rybbit.io/api/sites/123/pages',
+ params={
+ 'start_date': '2024-01-01',
+ 'end_date': '2024-01-31',
+ 'time_zone': 'America/New_York',
+ 'sort': 'entries',
+ 'limit': 25
+ },
+ 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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25');
+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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25')
+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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25", 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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25")
+ .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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25"))
+ .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://app.rybbit.io/api/sites/123/pages?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&sort=entries&limit=25");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "data": {
+ "data": [
+ {
+ "kind": "page",
+ "key": "/",
+ "title": "Acme - Home",
+ "section": "/",
+ "pages": 1,
+ "pageviews": 18420,
+ "sessions": 12950,
+ "entries": 11230,
+ "exits": 7410,
+ "bounced_entries": 5120,
+ "time_on_page_seconds": 41.6,
+ "bounce_rate": 45.59
+ },
+ {
+ "kind": "page",
+ "key": "/pricing",
+ "title": "Pricing - Acme",
+ "section": "/pricing",
+ "pages": 1,
+ "pageviews": 6210,
+ "sessions": 4870,
+ "entries": 1980,
+ "exits": 2240,
+ "bounced_entries": 760,
+ "time_on_page_seconds": 63.2,
+ "bounce_rate": 38.38
+ }
+ ],
+ "totalCount": 214
+ }
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/pages/meta.json b/docs/content/docs/api/pages/meta.json
new file mode 100644
index 000000000..cf5e07ff3
--- /dev/null
+++ b/docs/content/docs/api/pages/meta.json
@@ -0,0 +1,8 @@
+{
+ "title": "Pages",
+ "pages": [
+ "list",
+ "summary",
+ "trends"
+ ]
+}
diff --git a/docs/content/docs/api/pages/summary.mdx b/docs/content/docs/api/pages/summary.mdx
new file mode 100644
index 000000000..82417f5de
--- /dev/null
+++ b/docs/content/docs/api/pages/summary.mdx
@@ -0,0 +1,245 @@
+---
+title: Get Pages Summary
+description: Returns site-wide page totals for the period and the pageviews of every section.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/pages/summary
+```
+
+Returns the totals that head the Pages report, plus each section's pageviews and page count, largest first.
+
+**Permissions:** any role on the site (`viewer` and above). API keys need the `analytics:read` scope. Public sites and [private links](/docs/api/sites/get-private-link) can read it without a key.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Query Parameters
+
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (time and filters). Time parameters are optional; omit them for all-time data.
+
+### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: "Summary object",
+ type: "PagesSummary",
+ },
+ }}
+/>
+
+#### PagesSummary Object
+
+<TypeTable
+ type={{
+ pageviews: {
+ description: "Total pageviews",
+ type: "number",
+ },
+ sessions: {
+ description: "Sessions with at least one pageview",
+ type: "number",
+ },
+ pages: {
+ description: "Distinct paths viewed",
+ type: "number",
+ },
+ bounced_sessions: {
+ description: "Sessions with exactly one pageview",
+ type: "number",
+ },
+ bounce_rate: {
+ description: "bounced_sessions as a percentage of sessions",
+ type: "number | null",
+ typeDescription: "Range: 0-100",
+ },
+ time_on_page_seconds: {
+ description: "Average seconds to the next pageview (capped at 1800 per view), over views that were not the session's last",
+ type: "number | null",
+ },
+ views_per_session: {
+ description: "pageviews divided by sessions",
+ type: "number | null",
+ },
+ sections: {
+ description: "Sections ordered by pageviews (descending), at most 500",
+ type: "{ section: string, pageviews: number, pages: number }[]",
+ },
+ sectionCount: {
+ description: "Total number of sections, including any beyond the first 500",
+ type: "number",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York',
+ {
+ 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://app.rybbit.io/api/sites/123/pages/summary',
+ params={
+ 'start_date': '2024-01-01',
+ 'end_date': '2024-01-31',
+ 'time_zone': 'America/New_York'
+ },
+ 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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York');
+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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York')
+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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York", 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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York")
+ .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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York"))
+ .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://app.rybbit.io/api/sites/123/pages/summary?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "data": {
+ "pageviews": 48210,
+ "sessions": 21480,
+ "pages": 214,
+ "bounced_sessions": 9320,
+ "bounce_rate": 43.39,
+ "time_on_page_seconds": 52.4,
+ "views_per_session": 2.24,
+ "sections": [
+ {
+ "section": "/docs",
+ "pageviews": 19840,
+ "pages": 132
+ },
+ {
+ "section": "/",
+ "pageviews": 18420,
+ "pages": 1
+ },
+ {
+ "section": "/pricing",
+ "pageviews": 6210,
+ "pages": 1
+ }
+ ],
+ "sectionCount": 12
+ }
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/pages/trends.mdx b/docs/content/docs/api/pages/trends.mdx
new file mode 100644
index 000000000..df7c4aefc
--- /dev/null
+++ b/docs/content/docs/api/pages/trends.mdx
@@ -0,0 +1,265 @@
+---
+title: Get Page Trends
+description: Returns pageviews over time for up to 50 paths and sections in one request.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/pages/trends
+```
+
+Returns a pageview time series for each requested path and section. A pageview counts toward its path and toward its section when both are requested.
+
+**Permissions:** any role on the site (`viewer` and above). API keys need the `analytics:read` scope. Public sites and [private links](/docs/api/sites/get-private-link) can read it without a key.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Query Parameters
+
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (time and filters). Time parameters are optional; omit them for all-time data.
+
+<TypeTable
+ type={{
+ paths: {
+ description: "JSON-encoded array of paths, e.g. [\"/pricing\",\"/docs/api\"]",
+ type: "string",
+ required: false,
+ },
+ sections: {
+ description: "JSON-encoded array of sections (first path segment), e.g. [\"/blog\"]",
+ type: "string",
+ required: false,
+ },
+ bucket: {
+ description: "Time bucket size",
+ type: "TimeBucket",
+ typeDescription: "\"minute\" | \"five_minutes\" | \"ten_minutes\" | \"fifteen_minutes\" | \"hour\" | \"day\" | \"week\" | \"month\" | \"year\"",
+ default: "day",
+ required: false,
+ },
+ }}
+/>
+
+Pass at least one path or section, and at most 50 in total (each up to 2048 characters).
+
+### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: "One entry per requested path or section that had pageviews in the period. Keys with no views are omitted",
+ type: "PageTrend[]",
+ },
+ }}
+/>
+
+#### PageTrend Object
+
+<TypeTable
+ type={{
+ kind: {
+ description: "Whether `key` is a path or a section",
+ type: "string",
+ typeDescription: "\"page\" | \"section\"",
+ },
+ key: {
+ description: "The path or section",
+ type: "string",
+ },
+ pageviews: {
+ description: "Total pageviews in the period (the sum of `series`)",
+ type: "number",
+ },
+ series: {
+ description: "Pageviews per bucket. `time` is the bucket start as `YYYY-MM-DD HH:MM:SS`, wall-clock in `time_zone`. Empty buckets are filled with 0 when the request has a time range; all-time requests are not filled",
+ type: "{ time: string, pageviews: number }[]",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D',
+ {
+ 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://app.rybbit.io/api/sites/123/pages/trends',
+ params={
+ 'start_date': '2024-01-01',
+ 'end_date': '2024-01-03',
+ 'time_zone': 'America/New_York',
+ 'bucket': 'day',
+ 'paths': '["/pricing"]',
+ 'sections': '["/docs"]'
+ },
+ 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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D');
+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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D')
+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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D", 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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D")
+ .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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D"))
+ .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://app.rybbit.io/api/sites/123/pages/trends?start_date=2024-01-01&end_date=2024-01-03&time_zone=America/New_York&bucket=day&paths=%5B%22/pricing%22%5D&sections=%5B%22/docs%22%5D");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "data": [
+ {
+ "kind": "page",
+ "key": "/pricing",
+ "pageviews": 612,
+ "series": [
+ {
+ "time": "2024-01-01 00:00:00",
+ "pageviews": 158
+ },
+ {
+ "time": "2024-01-02 00:00:00",
+ "pageviews": 231
+ },
+ {
+ "time": "2024-01-03 00:00:00",
+ "pageviews": 223
+ }
+ ]
+ },
+ {
+ "kind": "section",
+ "key": "/docs",
+ "pageviews": 1934,
+ "series": [
+ {
+ "time": "2024-01-01 00:00:00",
+ "pageviews": 402
+ },
+ {
+ "time": "2024-01-02 00:00:00",
+ "pageviews": 781
+ },
+ {
+ "time": "2024-01-03 00:00:00",
+ "pageviews": 751
+ }
+ ]
+ }
+ ]
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/performance/by-dimension.mdx b/docs/content/docs/api/performance/by-dimension.mdx
index 701984445..2faee7977 100644
--- a/docs/content/docs/api/performance/by-dimension.mdx
+++ b/docs/content/docs/api/performance/by-dimension.mdx
@@ -36,7 +36,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
dimension: {
- description: 'Dimension to break down by',
+ description: 'Dimension to break down by. There is no default: a missing or unknown value fails with 500.',
type: 'string',
typeDescription: '"pathname" | "country" | "device_type" | "browser" | "operating_system" | "region"',
required: true,
@@ -52,7 +52,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
default: 100,
},
sort_by: {
- description: 'Field to sort by',
+ description: 'Field to sort by: the dimension, event_count, or any <metric>_avg / <metric>_p50 / _p75 / _p90 / _p99 field. Any other value silently falls back to event_count. Nulls sort last.',
type: 'string',
default: 'event_count',
},
@@ -71,14 +71,16 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type={{
data: {
description: 'Paginated response object',
- type: 'PaginatedResponse',
+ type: '{ data: DimensionPerformance[], totalCount: number }',
},
}}
/>
+`totalCount` is the number of distinct dimension values. Rows with an empty dimension value are left out.
+
#### DimensionPerformance Object
-Each object includes the dimension value plus all percentiles:
+Each object has the dimension value, `event_count`, and the fields below for each metric (`lcp`, `cls`, `inp`, `fcp`, `ttfb`); LCP is shown. LCP, INP, FCP and TTFB are in milliseconds; CLS is unitless. Averages and percentiles are `null` when no load for that value reported the metric.
<TypeTable
type={{
@@ -92,22 +94,34 @@ Each object includes the dimension value plus all percentiles:
},
lcp_avg: {
description: 'Average LCP',
- type: 'number',
+ type: 'number | null',
},
lcp_p50: {
description: 'LCP 50th percentile',
- type: 'number',
+ type: 'number | null',
},
lcp_p75: {
description: 'LCP 75th percentile',
- type: 'number',
+ type: 'number | null',
},
lcp_p90: {
description: 'LCP 90th percentile',
- type: 'number',
+ type: 'number | null',
},
lcp_p99: {
description: 'LCP 99th percentile',
+ type: 'number | null',
+ },
+ lcp_count: {
+ description: 'Page loads that reported LCP',
+ type: 'number',
+ },
+ lcp_good: {
+ description: 'Page loads with a good LCP (at most 2500 ms; CLS 0.1, INP 200 ms, FCP 1800 ms, TTFB 800 ms)',
+ type: 'number',
+ },
+ lcp_poor: {
+ description: 'Page loads with a poor LCP (over 4000 ms; CLS 0.25, INP 500 ms, FCP 3000 ms, TTFB 1800 ms)',
type: 'number',
},
}}
@@ -245,6 +259,9 @@ var data = await response.Content.ReadAsStringAsync();
"lcp_p75": 3200,
"lcp_p90": 4100,
"lcp_p99": 6500,
+ "lcp_count": 12380,
+ "lcp_good": 6900,
+ "lcp_poor": 2150,
"cls_avg": 0.08,
"cls_p50": 0.05,
"cls_p75": 0.12,
diff --git a/docs/content/docs/api/performance/overview.mdx b/docs/content/docs/api/performance/overview.mdx
index e9df6c21c..ef9637a33 100644
--- a/docs/content/docs/api/performance/overview.mdx
+++ b/docs/content/docs/api/performance/overview.mdx
@@ -46,30 +46,42 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) (ti
#### PerformanceMetrics Object
-Each metric (lcp, cls, inp, fcp, ttfb) includes the following percentiles:
+Each metric (`lcp`, `cls`, `inp`, `fcp`, `ttfb`) has the fields below; LCP is shown. LCP, INP, FCP and TTFB are in milliseconds; CLS is unitless. A percentile is `null` when no page load in the range reported that metric.
<TypeTable
type={{
lcp_p50: {
description: 'LCP 50th percentile (median)',
- type: 'number',
+ type: 'number | null',
typeDescription: 'milliseconds',
},
lcp_p75: {
description: 'LCP 75th percentile',
- type: 'number',
+ type: 'number | null',
typeDescription: 'milliseconds',
},
lcp_p90: {
description: 'LCP 90th percentile',
- type: 'number',
+ type: 'number | null',
typeDescription: 'milliseconds',
},
lcp_p99: {
description: 'LCP 99th percentile',
- type: 'number',
+ type: 'number | null',
typeDescription: 'milliseconds',
},
+ lcp_count: {
+ description: 'Page loads that reported LCP',
+ type: 'number',
+ },
+ lcp_good: {
+ description: 'Page loads with a good LCP (at most 2500 ms; CLS 0.1, INP 200 ms, FCP 1800 ms, TTFB 800 ms)',
+ type: 'number',
+ },
+ lcp_poor: {
+ description: 'Page loads with a poor LCP (over 4000 ms; CLS 0.25, INP 500 ms, FCP 3000 ms, TTFB 1800 ms). The rest of lcp_count needs improvement.',
+ type: 'number',
+ },
total_performance_events: {
description: 'Total number of performance measurements',
type: 'number',
@@ -202,6 +214,9 @@ var data = await response.Content.ReadAsStringAsync();
"lcp_p75": 2400,
"lcp_p90": 3200,
"lcp_p99": 5100,
+ "lcp_count": 48210,
+ "lcp_good": 36150,
+ "lcp_poor": 4320,
"cls_p50": 0.05,
"cls_p75": 0.1,
"cls_p90": 0.18,
@@ -218,6 +233,18 @@ var data = await response.Content.ReadAsStringAsync();
"ttfb_p75": 650,
"ttfb_p90": 950,
"ttfb_p99": 1800,
+ "cls_count": 47980,
+ "cls_good": 39870,
+ "cls_poor": 2110,
+ "inp_count": 21450,
+ "inp_good": 18900,
+ "inp_poor": 640,
+ "fcp_count": 48300,
+ "fcp_good": 41200,
+ "fcp_poor": 1980,
+ "ttfb_count": 48500,
+ "ttfb_good": 42100,
+ "ttfb_poor": 1730,
"total_performance_events": 48521
}
}
diff --git a/docs/content/docs/api/performance/time-series.mdx b/docs/content/docs/api/performance/time-series.mdx
index 0beac8d6f..ededbe006 100644
--- a/docs/content/docs/api/performance/time-series.mdx
+++ b/docs/content/docs/api/performance/time-series.mdx
@@ -58,14 +58,14 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
#### PerformancePoint Object
-Each point includes all percentiles for each metric plus:
+Each point has `<metric>_p50`, `_p75`, `_p90` and `_p99` for `lcp`, `cls`, `inp`, `fcp` and `ttfb` (`null` when no load in the bucket reported the metric), plus:
<TypeTable
type={{
time: {
description: 'Start of the time bucket',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'Bucket start in the requested time_zone, "YYYY-MM-DD HH:MM:SS"',
},
event_count: {
description: 'Number of performance events in this bucket',
@@ -198,7 +198,7 @@ var data = await response.Content.ReadAsStringAsync();
{
"data": [
{
- "time": "2024-01-01T00:00:00.000Z",
+ "time": "2024-01-01 00:00:00",
"lcp_p50": 1820,
"lcp_p75": 2350,
"lcp_p90": 3100,
@@ -214,7 +214,7 @@ var data = await response.Content.ReadAsStringAsync();
"event_count": 6892
},
{
- "time": "2024-01-02T00:00:00.000Z",
+ "time": "2024-01-02 00:00:00",
"lcp_p50": 1900,
"lcp_p75": 2450,
"lcp_p90": 3250,
diff --git a/docs/content/docs/api/query/generate.mdx b/docs/content/docs/api/query/generate.mdx
new file mode 100644
index 000000000..05dbcb76d
--- /dev/null
+++ b/docs/content/docs/api/query/generate.mdx
@@ -0,0 +1,295 @@
+---
+title: Generate SQL Query
+description: Turns a plain-language question into a ClickHouse query for the Run SQL Query endpoint. The query is returned, not run.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/organizations/:organizationId/analytics/query/generate
+```
+
+Uses an AI model to write a `scoped_events` query from a plain-language prompt. The generated SQL is checked against the same rules as [Run SQL Query](/docs/api/query/run) and returned; nothing is executed. Pass `currentQuery` and `history` to refine an earlier query.
+
+**Permissions:** the `viewer` role or above in the organization. API keys need the `sql:read` scope.
+
+**Rate limit:** 20 requests per minute per user (per organization for organization API keys). Self-hosted instances need an OpenRouter API key configured.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "Organization ID",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ prompt: {
+ description: "What you want to know",
+ type: "string",
+ typeDescription: "1-4,000 characters",
+ required: true,
+ },
+ currentSiteId: {
+ description: "A site to focus on; \"this site\" in the prompt refers to it. Must be a site you can access",
+ type: "number",
+ required: false,
+ },
+ currentQuery: {
+ description: "The query to revise for a follow-up request",
+ type: "string",
+ typeDescription: "Up to 20,000 characters",
+ required: false,
+ },
+ history: {
+ description: "Earlier turns of the conversation, oldest first. Only the last 10 are used",
+ type: "{ role: \"user\" | \"assistant\", content: string }[]",
+ typeDescription: "Max 12 items",
+ default: "[]",
+ required: false,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ query: {
+ description: "The generated SQL, ready to send to Run SQL Query",
+ type: "string",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid body",
+ type: "object",
+ },
+ "403": {
+ description: "No role in the organization, missing sql:read scope, no accessible sites, or no access to currentSiteId",
+ type: "object",
+ },
+ "422": {
+ description: "The generated query failed validation; details holds the reason",
+ type: "object",
+ },
+ "429": {
+ description: "More than 20 requests in a minute",
+ type: "object",
+ },
+ "500": {
+ description: "AI query generation isn't configured, or generation failed",
+ type: "object",
+ },
+ "502": {
+ description: "The AI provider returned an error or an empty response",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/organizations/org_123/analytics/query/generate" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "prompt": "Top 10 referrers last month",
+ "currentSiteId": 123
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/organizations/org_123/analytics/query/generate',
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ prompt: 'Top 10 referrers last month',
+ currentSiteId: 123
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/organizations/org_123/analytics/query/generate',
+ json={
+ 'prompt': 'Top 10 referrers last month',
+ 'currentSiteId': 123
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'prompt' => 'Top 10 referrers last month',
+ 'currentSiteId' => 123
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/organizations/org_123/analytics/query/generate');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/organizations/org_123/analytics/query/generate')
+request = Net::HTTP::Post.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ prompt: 'Top 10 referrers last month',
+ currentSiteId: 123
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "prompt": "Top 10 referrers last month",
+ "currentSiteId": 123,
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/organizations/org_123/analytics/query/generate", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "prompt": "Top 10 referrers last month",
+ "currentSiteId": 123
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/organizations/org_123/analytics/query/generate")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "prompt": "Top 10 referrers last month",
+ "currentSiteId": 123
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/organizations/org_123/analytics/query/generate"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ prompt = "Top 10 referrers last month",
+ currentSiteId = 123
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/organizations/org_123/analytics/query/generate", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "query": "SELECT referrer, count() AS events FROM scoped_events WHERE site_id = 123 AND referrer != '' AND timestamp >= toStartOfMonth(now() - INTERVAL 1 MONTH) AND timestamp < toStartOfMonth(now()) GROUP BY referrer ORDER BY events DESC LIMIT 10"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/query/meta.json b/docs/content/docs/api/query/meta.json
new file mode 100644
index 000000000..b5792eea3
--- /dev/null
+++ b/docs/content/docs/api/query/meta.json
@@ -0,0 +1,7 @@
+{
+ "title": "Custom SQL",
+ "pages": [
+ "run",
+ "generate"
+ ]
+}
diff --git a/docs/content/docs/api/query/run.mdx b/docs/content/docs/api/query/run.mdx
new file mode 100644
index 000000000..154f66900
--- /dev/null
+++ b/docs/content/docs/api/query/run.mdx
@@ -0,0 +1,341 @@
+---
+title: Run SQL Query
+description: Runs a read-only ClickHouse SQL query over the raw events of the sites you can access in an organization.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/organizations/:organizationId/analytics/query
+```
+
+Runs one read-only ClickHouse `SELECT` against `scoped_events`: the raw events of every site in the organization that the caller can access, or of a single site when `siteId` is given. Results are capped at 1,000 rows and 60 seconds of execution.
+
+**Permissions:** the `viewer` role or above in the organization. API keys need the `sql:read` scope. Members with restricted site access only see their sites; organization API keys see every site in the organization.
+
+**Rate limit:** 60 requests per minute per user (per organization for organization API keys), on top of the [standard API limits](/docs/api/getting-started#rate-limits-cloud-only).
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "Organization ID",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ query: {
+ description: "A single SELECT (or WITH ... SELECT) statement reading from scoped_events. A trailing semicolon is removed",
+ type: "string",
+ typeDescription: "1-20,000 characters",
+ required: true,
+ },
+ siteId: {
+ description: "Limit scoped_events to this site. Omit to query every accessible site in the organization",
+ type: "number",
+ required: false,
+ },
+ }}
+/>
+
+### Query Rules
+
+- Read from `scoped_events` only, or from CTEs you define over it. `events`, `system.*`, `information_schema.*` and other tables are rejected, and `scoped_events` can't be redefined.
+- One statement, starting with `SELECT` or `WITH`.
+- These keywords are rejected anywhere outside string literals: `ALTER`, `ATTACH`, `BACKUP`, `CREATE`, `DELETE`, `DESCRIBE`, `DETACH`, `DROP`, `EXCHANGE`, `EXPLAIN`, `FORMAT`, `GRANT`, `INFILE`, `INSERT`, `INTO`, `KILL`, `OPTIMIZE`, `OUTFILE`, `RENAME`, `RESTORE`, `REVOKE`, `SET`, `SETTINGS`, `SHOW`, `SYSTEM`, `TRUNCATE`, `USE`, `WATCH`.
+- Table functions and functions that reach outside the events (for example `url()`, `s3()`, `file()`, `remote()`, `numbers()`, `dictGet()`, `sleep()`) are rejected.
+- Double-quoted or backtick identifiers, `#` and `//` comments, nested `/* */` comments, `$$` strings, and non-ASCII characters outside string literals are rejected. Use single quotes for strings.
+- Your query is wrapped as `SELECT * FROM (your query) LIMIT 1000`.
+
+#### scoped_events Columns
+
+| Column | Type | Description |
+|--------|------|-------------|
+| `site_id` | `UInt16` | Rybbit site ID |
+| `timestamp` | `DateTime` | Event time (UTC) |
+| `timestamp_ms` | `DateTime64(3)` | Event time with milliseconds, for ordering |
+| `session_id` | `String` | Session ID |
+| `user_id` | `String` | Anonymous device ID |
+| `identified_user_id` | `String` | ID set via identify(); empty when not identified |
+| `hostname` | `String` | Page hostname, e.g. www.example.com |
+| `pathname` | `String` | URL path, e.g. /pricing |
+| `querystring` | `String` | Raw query string, usually with the leading ? |
+| `url_parameters` | `Map(String, String)` | Parsed query parameters, e.g. url_parameters['utm_source'] |
+| `page_title` | `String` | document.title; may be empty |
+| `referrer` | `String` | External referrer URL; empty for direct traffic |
+| `channel` | `String` | Acquisition channel, e.g. Direct, Organic Search, Referral |
+| `browser, browser_version` | `LowCardinality(String)` | Browser and major version |
+| `operating_system, operating_system_version` | `LowCardinality(String)` | OS and version |
+| `language` | `LowCardinality(String)` | Browser language, e.g. en-US |
+| `country` | `LowCardinality(FixedString(2))` | ISO 3166-1 alpha-2 code |
+| `region` | `LowCardinality(String)` | Region code, e.g. US-CA |
+| `city` | `String` | City name |
+| `lat, lon` | `Float64` | Coordinates; 0 when unknown |
+| `screen_width, screen_height` | `UInt16` | Screen size in pixels; 0 when unavailable |
+| `device_type` | `LowCardinality(String)` | Desktop, Mobile, Tablet, TV, Console or Embedded |
+| `type` | `LowCardinality(String)` | pageview, custom_event, performance, outbound, error, button_click, copy, form_submit or input_change |
+| `event_name` | `String` | Custom event name, error name, or web-vitals |
+| `props` | `JSON` | Event properties; read with JSONExtractString(toString(props), 'key') |
+| `lcp, cls, inp, fcp, ttfb` | `Nullable(Float64)` | Web vitals; set only on performance events |
+| `ip` | `Nullable(String)` | Visitor IP when IP tracking is on for the site; otherwise null |
+| `timezone` | `LowCardinality(String)` | Visitor timezone from geolocation |
+| `tag` | `LowCardinality(String)` | Optional script tag; empty when unset |
+| `import_id` | `Nullable(UUID)` | Import job ID for imported rows; null for tracked events |
+| `feature_flags` | `Map(String, String)` | Feature flag values recorded with the event |
+| `asn` | `Nullable(UInt32)` | Autonomous system number of the visitor's IP |
+| `asn_org` | `LowCardinality(String)` | Organization that owns the ASN; empty when unknown |
+| `is_datacenter_asn` | `UInt8` | 1 when the ASN belongs to a datacenter or hosting provider |
+
+### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: "Result rows as ClickHouse serializes them to JSON. 64-bit integers (such as count()) are returned as strings; DateTime values as YYYY-MM-DD HH:MM:SS in UTC",
+ type: "object[]",
+ },
+ meta: {
+ description: "Query metadata",
+ type: "{ queryId: string, rowCount: number, maxExecutionTimeSeconds: number, maxRows: number }",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid body, a query that breaks the rules above (the message names the problem), or a ClickHouse error such as a syntax error, unknown column, or the time or memory limit being hit",
+ type: "object",
+ },
+ "403": {
+ description: "No role in the organization, missing sql:read scope, no accessible sites, or no access to the requested siteId",
+ type: "object",
+ },
+ "429": {
+ description: "More than 60 queries in a minute",
+ type: "object",
+ },
+ "503": {
+ description: "Custom SQL is unavailable because the ClickHouse query user isn't provisioned (self-hosted)",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/organizations/org_123/analytics/query" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "query": "SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = '\''pageview'\'' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10",
+ "siteId": 123
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/organizations/org_123/analytics/query',
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ query: 'SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = \'pageview\' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10',
+ siteId: 123
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/organizations/org_123/analytics/query',
+ json={
+ 'query': 'SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = \'pageview\' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10',
+ 'siteId': 123
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'query' => 'SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = \'pageview\' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10',
+ 'siteId' => 123
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/organizations/org_123/analytics/query');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/organizations/org_123/analytics/query')
+request = Net::HTTP::Post.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ query: 'SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = \'pageview\' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10',
+ siteId: 123
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "query": "SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = 'pageview' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10",
+ "siteId": 123,
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/organizations/org_123/analytics/query", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "query": "SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = 'pageview' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10",
+ "siteId": 123
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/organizations/org_123/analytics/query")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "query": "SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = 'pageview' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10",
+ "siteId": 123
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/organizations/org_123/analytics/query"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ query = "SELECT pathname, count() AS pageviews FROM scoped_events WHERE type = 'pageview' AND timestamp >= now() - INTERVAL 7 DAY GROUP BY pathname ORDER BY pageviews DESC LIMIT 10",
+ siteId = 123
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/organizations/org_123/analytics/query", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "data": [
+ {
+ "pathname": "/",
+ "pageviews": "4210"
+ },
+ {
+ "pathname": "/pricing",
+ "pageviews": "1388"
+ }
+ ],
+ "meta": {
+ "queryId": "9f2c7a1e-3b4d-4e5f-8a6b-1c2d3e4f5a6b",
+ "rowCount": 2,
+ "maxExecutionTimeSeconds": 60,
+ "maxRows": 1000
+ }
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/search-console/data.mdx b/docs/content/docs/api/search-console/data.mdx
new file mode 100644
index 000000000..29ad35e0e
--- /dev/null
+++ b/docs/content/docs/api/search-console/data.mdx
@@ -0,0 +1,302 @@
+---
+title: Get Search Console Data
+description: Returns Google Search Console clicks, impressions, CTR and position, grouped by query, page, country, device or date.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/gsc/data
+```
+
+Queries Google Search Console's Search Analytics for the site's connected property and returns its rows. The site must be [connected](/docs/api/search-console/status).
+
+**Permissions:** any role on the site (`viewer` and above). API keys need the `gsc:read` scope. Public sites and [private links](/docs/api/sites/get-private-link) can read it without a key.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Query Parameters
+
+<TypeTable
+ type={{
+ start_date: {
+ description: "Start date",
+ type: "string",
+ typeDescription: "YYYY-MM-DD",
+ required: true,
+ },
+ end_date: {
+ description: "End date, on or after start_date",
+ type: "string",
+ typeDescription: "YYYY-MM-DD",
+ required: true,
+ },
+ dimensions: {
+ description: "Comma-separated dimensions to group by (1 to 3): query, page, country, device, date",
+ type: "string",
+ required: false,
+ },
+ dimension: {
+ description: "Legacy single dimension (query, page, country or device). Rows then use a `name` key. Ignored when dimensions is set",
+ type: "string",
+ required: false,
+ },
+ filters: {
+ description: "JSON-encoded array of up to 10 filters, ANDed: [{\"dimension\":\"country\",\"operator\":\"equals\",\"expression\":\"US\"}]. dimension is query, page, country or device; operator is equals (default), notEquals, contains, notContains, includingRegex or excludingRegex. With equals and notEquals, countries take ISO alpha-2 codes",
+ type: "string",
+ required: false,
+ },
+ search_type: {
+ description: "Search Console search type",
+ type: "string",
+ typeDescription: "\"web\" | \"image\" | \"video\" | \"news\" | \"discover\" | \"googleNews\"",
+ required: false,
+ },
+ data_state: {
+ description: "`all` includes fresh, not yet final data",
+ type: "string",
+ typeDescription: "\"final\" | \"all\"",
+ required: false,
+ },
+ row_limit: {
+ description: "Maximum rows",
+ type: "number",
+ typeDescription: "1-25000",
+ default: 1000,
+ required: false,
+ },
+ start_row: {
+ description: "Zero-based row offset, for paging",
+ type: "number",
+ required: false,
+ },
+ }}
+/>
+
+One of `dimensions` or `dimension` is required. This endpoint takes its own `filters` format, not the analytics filters.
+
+### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: "Rows as returned by Search Console",
+ type: "GSCRow[]",
+ },
+ }}
+/>
+
+#### GSCRow Object
+
+<TypeTable
+ type={{
+ "[dimension]": {
+ description: "One key per requested dimension, e.g. query and page. Countries are ISO alpha-2 codes; dates are YYYY-MM-DD. With the legacy dimension parameter, the single key is \"name\"",
+ type: "string",
+ },
+ clicks: {
+ description: "Clicks",
+ type: "number",
+ },
+ impressions: {
+ description: "Impressions",
+ type: "number",
+ },
+ ctr: {
+ description: "Click-through rate as a fraction",
+ type: "number",
+ typeDescription: "Range: 0-1",
+ },
+ position: {
+ description: "Average position",
+ type: "number",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Missing or invalid parameters, or Search Console rejected the query",
+ type: "object",
+ },
+ "404": {
+ description: "Search Console isn't connected for this site",
+ type: "object",
+ },
+ "429": {
+ description: "Search Console quota exceeded",
+ type: "object",
+ },
+ "502": {
+ description: "Search Console denied access to the property (reconnect it) or failed",
+ type: "object",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100',
+ {
+ 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://app.rybbit.io/api/sites/123/gsc/data',
+ params={
+ 'start_date': '2026-10-01',
+ 'end_date': '2026-10-28',
+ 'dimensions': 'query,country',
+ 'row_limit': 100
+ },
+ 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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100');
+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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100')
+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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100", 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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100")
+ .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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100"))
+ .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://app.rybbit.io/api/sites/123/gsc/data?start_date=2026-10-01&end_date=2026-10-28&dimensions=query,country&row_limit=100");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "data": [
+ {
+ "query": "acme analytics",
+ "country": "US",
+ "clicks": 412,
+ "impressions": 3820,
+ "ctr": 0.1078,
+ "position": 2.4
+ },
+ {
+ "query": "acme pricing",
+ "country": "GB",
+ "clicks": 96,
+ "impressions": 1210,
+ "ctr": 0.0793,
+ "position": 3.1
+ }
+ ]
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/search-console/meta.json b/docs/content/docs/api/search-console/meta.json
new file mode 100644
index 000000000..4fb73d295
--- /dev/null
+++ b/docs/content/docs/api/search-console/meta.json
@@ -0,0 +1,7 @@
+{
+ "title": "Search Console",
+ "pages": [
+ "status",
+ "data"
+ ]
+}
diff --git a/docs/content/docs/api/search-console/status.mdx b/docs/content/docs/api/search-console/status.mdx
new file mode 100644
index 000000000..899d8c432
--- /dev/null
+++ b/docs/content/docs/api/search-console/status.mdx
@@ -0,0 +1,171 @@
+---
+title: Get Search Console Status
+description: Returns whether a site is connected to Google Search Console, and to which property.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/gsc/status
+```
+
+Returns whether the site has a Google Search Console connection. Connect it in the dashboard under Site settings.
+
+**Permissions:** any role on the site (`viewer` and above). API keys need the `gsc:read` scope. Public sites and [private links](/docs/api/sites/get-private-link) can read it without a key.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ connected: {
+ description: "Whether Search Console is connected",
+ type: "boolean",
+ },
+ gscPropertyUrl: {
+ description: "The connected Search Console property, or null when not connected",
+ type: "string | null",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/sites/123/gsc/status" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/gsc/status',
+ {
+ 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://app.rybbit.io/api/sites/123/gsc/status',
+ 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://app.rybbit.io/api/sites/123/gsc/status');
+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://app.rybbit.io/api/sites/123/gsc/status')
+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://app.rybbit.io/api/sites/123/gsc/status", 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://app.rybbit.io/api/sites/123/gsc/status")
+ .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://app.rybbit.io/api/sites/123/gsc/status"))
+ .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://app.rybbit.io/api/sites/123/gsc/status");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "connected": true,
+ "gscPropertyUrl": "sc-domain:acme.com"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/segments/create.mdx b/docs/content/docs/api/segments/create.mdx
index c05b9f4c1..7b3481c58 100644
--- a/docs/content/docs/api/segments/create.mdx
+++ b/docs/content/docs/api/segments/create.mdx
@@ -17,6 +17,8 @@ POST /api/sites/:site/segments
Creates a saved segment. Members create site segments they own; editors, admins and owners can also create organization-wide segments.
+The body is strict: unknown fields return `400`. Creating an organization-wide segment without the editor role in the organization returns `403`.
+
### Path Parameters
<TypeTable
@@ -39,7 +41,7 @@ Creates a saved segment. Members create site segments they own; editors, admins
required: true,
},
filters: {
- description: 'Filters that define the segment (1–20). Validated with the same schema as the `filters` parameter',
+ description: 'Filters that define the segment (1–20). Uses the `filters` parameter format with stricter limits: at most 50 values per filter, each up to 500 characters; regex filters take exactly one valid pattern; comparison and lat/lon filters need numeric values; every filter except is_null/is_not_null needs at least one value (those two still send `value: []`)',
type: 'Filter[]',
typeDescription: 'See Filter Parameters in Getting Started',
required: true,
@@ -80,8 +82,8 @@ Returns the created segment with status 201.
isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },
type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },
canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },
- createdAt: { description: 'ISO 8601 timestamp', type: 'string' },
- updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },
+ createdAt: { description: 'Creation timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
+ updatedAt: { description: 'Last update timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
}}
/>
@@ -145,8 +147,8 @@ data = response.json()
"isPublic": false,
"type": "segment",
"canEdit": true,
- "createdAt": "2026-09-02T10:15:00.000Z",
- "updatedAt": "2026-09-02T10:15:00.000Z"
+ "createdAt": "2026-09-02 10:15:00.482913",
+ "updatedAt": "2026-09-02 10:15:00.482913"
}
```
diff --git a/docs/content/docs/api/segments/delete.mdx b/docs/content/docs/api/segments/delete.mdx
index be55cece9..d782b7203 100644
--- a/docs/content/docs/api/segments/delete.mdx
+++ b/docs/content/docs/api/segments/delete.mdx
@@ -1,6 +1,6 @@
---
title: Delete Segment
-description: Deletes a saved segment. Admins and owners can delete any segment; members can delete segments they created. Links that already expanded the segment's filters keep working.
+description: Deletes a saved segment. Editors and above can delete any segment on the site; members can delete segments they created. Links that already expanded the segment's filters keep working.
full: true
method: DELETE
---
@@ -15,7 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/segments/:segmentId
```
-Deletes a saved segment. Admins and owners can delete any segment; members can delete segments they created. Links that already expanded the segment's filters keep working.
+Deletes a saved segment. Links that already expanded the segment's filters keep working.
+
+Editors and above can delete any segment on the site, including through a per-site editor grant; members can delete segments they created. Organization-wide segments need the editor role or above in the organization, even for the segment's creator. Returns `403` when you may not delete it and `404` when it does not exist on this site.
### Path Parameters
diff --git a/docs/content/docs/api/segments/get.mdx b/docs/content/docs/api/segments/get.mdx
index c89ee2fc5..f47496756 100644
--- a/docs/content/docs/api/segments/get.mdx
+++ b/docs/content/docs/api/segments/get.mdx
@@ -50,8 +50,8 @@ Returns the segment.
isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },
type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },
canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },
- createdAt: { description: 'ISO 8601 timestamp', type: 'string' },
- updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },
+ createdAt: { description: 'Creation timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
+ updatedAt: { description: 'Last update timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
}}
/>
@@ -110,8 +110,8 @@ data = response.json()
"isPublic": false,
"type": "segment",
"canEdit": true,
- "createdAt": "2026-09-02T10:15:00.000Z",
- "updatedAt": "2026-09-02T10:15:00.000Z"
+ "createdAt": "2026-09-02 10:15:00.482913",
+ "updatedAt": "2026-09-02 10:15:00.482913"
}
```
diff --git a/docs/content/docs/api/segments/list.mdx b/docs/content/docs/api/segments/list.mdx
index 41bee2c3e..bbc58a620 100644
--- a/docs/content/docs/api/segments/list.mdx
+++ b/docs/content/docs/api/segments/list.mdx
@@ -45,8 +45,8 @@ Returns an array of segments, sorted by name.
isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },
type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },
canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },
- createdAt: { description: 'ISO 8601 timestamp', type: 'string' },
- updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },
+ createdAt: { description: 'Creation timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
+ updatedAt: { description: 'Last update timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
}}
/>
@@ -106,8 +106,8 @@ data = response.json()
"isPublic": false,
"type": "segment",
"canEdit": true,
- "createdAt": "2026-09-02T10:15:00.000Z",
- "updatedAt": "2026-09-02T10:15:00.000Z"
+ "createdAt": "2026-09-02 10:15:00.482913",
+ "updatedAt": "2026-09-02 10:15:00.482913"
}
]
```
diff --git a/docs/content/docs/api/segments/update.mdx b/docs/content/docs/api/segments/update.mdx
index 3ebf4f786..5a0f03bb5 100644
--- a/docs/content/docs/api/segments/update.mdx
+++ b/docs/content/docs/api/segments/update.mdx
@@ -1,6 +1,6 @@
---
title: Update Segment
-description: Updates a saved segment. Editors, admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
+description: Updates a saved segment. Editors and above can edit any segment on the site; members can edit segments they created. Only the fields you send change.
full: true
method: PUT
---
@@ -15,7 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:site/segments/:segmentId
```
-Updates a saved segment. Editors, admins and owners can edit any segment; members can edit segments they created. Only the fields you send change.
+Updates a saved segment. Only the fields you send change; omitted fields keep their current values.
+
+Editors and above can edit any segment on the site, including through a per-site editor grant; members can edit segments they created. Organization-wide segments, and moving a segment to `"organization"` scope, need the editor role or above in the organization, even for the segment's creator. The body is strict: unknown fields return `400`.
### Path Parameters
@@ -44,7 +46,7 @@ Updates a saved segment. Editors, admins and owners can edit any segment; member
required: false,
},
filters: {
- description: 'Filters that define the segment (1–20). Validated with the same schema as the `filters` parameter',
+ description: 'Filters that define the segment (1–20). Uses the `filters` parameter format with stricter limits: at most 50 values per filter, each up to 500 characters; regex filters take exactly one valid pattern; comparison and lat/lon filters need numeric values; every filter except is_null/is_not_null needs at least one value (those two still send `value: []`)',
type: 'Filter[]',
typeDescription: 'See Filter Parameters in Getting Started',
required: false,
@@ -58,13 +60,11 @@ Updates a saved segment. Editors, admins and owners can edit any segment; member
description: 'Where the segment is available. Organization-wide segments need the editor role or above in the organization',
type: 'string',
typeDescription: '"site" | "organization"',
- default: 'site',
required: false,
},
isPublic: {
description: 'Show on the public dashboard and private links',
type: 'boolean',
- default: 'false',
required: false,
},
}}
@@ -85,8 +85,8 @@ Returns the updated segment.
isPublic: { description: 'Shown on the public dashboard and private links', type: 'boolean' },
type: { description: 'Always "segment" today; reserved for cohorts', type: 'string' },
canEdit: { description: 'Whether the caller may edit or delete this segment', type: 'boolean' },
- createdAt: { description: 'ISO 8601 timestamp', type: 'string' },
- updatedAt: { description: 'ISO 8601 timestamp', type: 'string' },
+ createdAt: { description: 'Creation timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
+ updatedAt: { description: 'Last update timestamp', type: 'string', typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix' },
}}
/>
@@ -150,8 +150,8 @@ data = response.json()
"isPublic": true,
"type": "segment",
"canEdit": true,
- "createdAt": "2026-09-02T10:15:00.000Z",
- "updatedAt": "2026-09-02T10:15:00.000Z"
+ "createdAt": "2026-09-02 10:15:00.482913",
+ "updatedAt": "2026-09-02 10:15:00.482913"
}
```
diff --git a/docs/content/docs/api/session-replay/delete.mdx b/docs/content/docs/api/session-replay/delete.mdx
index b5c6c43b8..51ce4c9d7 100644
--- a/docs/content/docs/api/session-replay/delete.mdx
+++ b/docs/content/docs/api/session-replay/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:site/session-replay/:sessionId
```
-Permanently deletes a session replay recording. Requires the editor role or above on the site.
+Permanently deletes a session replay recording. Requires the editor role or above on the site (the `replay:delete` permission; API keys need write access to replays).
### Path Parameters
diff --git a/docs/content/docs/api/session-replay/list.mdx b/docs/content/docs/api/session-replay/list.mdx
index f9a10cef1..9a9b4d080 100644
--- a/docs/content/docs/api/session-replay/list.mdx
+++ b/docs/content/docs/api/session-replay/list.mdx
@@ -90,12 +90,12 @@ Identified users are enriched with their `traits`.
start_time: {
description: 'Replay start time',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS.mmm"',
},
end_time: {
description: 'Replay end time',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS.mmm"',
},
duration_ms: {
description: 'Duration in milliseconds',
@@ -279,8 +279,8 @@ var data = await response.Content.ReadAsStringAsync();
"session_id": "a1b2c3d4-5e6f-7a8b-9c0d-1e2f3a4b5c6d",
"user_id": "dev_xyz789",
"identified_user_id": "[email protected]",
- "start_time": "2024-01-31T14:00:00.000Z",
- "end_time": "2024-01-31T14:00:48.200Z",
+ "start_time": "2024-01-31 14:00:00.000",
+ "end_time": "2024-01-31 14:00:48.200",
"duration_ms": 48200,
"page_url": "/",
"event_count": 312,
diff --git a/docs/content/docs/api/sessions/get.mdx b/docs/content/docs/api/sessions/get.mdx
index 05d3af8c3..484239e84 100644
--- a/docs/content/docs/api/sessions/get.mdx
+++ b/docs/content/docs/api/sessions/get.mdx
@@ -49,13 +49,15 @@ Returns detailed information about a specific session including all events and p
default: 0,
},
minutes: {
- description: 'Only return events from the last N minutes',
+ description: 'Only use events from the last N minutes. Applies to the session summary, the events, and the total. 0 or a non-numeric value is ignored, and the whole session is returned.',
type: 'number',
required: false,
},
}}
/>
+Returns `404` when the session has no events (or none in the last `minutes`).
+
### Response
<TypeTable
@@ -72,11 +74,11 @@ Returns detailed information about a specific session including all events and p
<TypeTable
type={{
session: {
- description: 'Session metadata',
+ description: 'Session summary',
type: 'SessionMeta',
},
events: {
- description: 'Array of events in the session',
+ description: 'Events in the session, oldest first. Performance (web vitals) events are left out.',
type: 'Event[]',
},
pagination: {
@@ -86,6 +88,107 @@ Returns detailed information about a specific session including all events and p
}}
/>
+#### SessionMeta Object
+
+<TypeTable
+ type={{
+ session_id: {
+ description: 'Session identifier',
+ type: 'string',
+ },
+ user_id: {
+ description: 'Device fingerprint identifier',
+ type: 'string',
+ },
+ country: {
+ description: 'Country code',
+ type: 'string',
+ },
+ region: {
+ description: 'Region/state',
+ type: 'string',
+ },
+ city: {
+ description: 'City name',
+ type: 'string',
+ },
+ language: {
+ description: 'Browser language',
+ type: 'string',
+ },
+ device_type: {
+ description: 'Device type',
+ type: 'string',
+ },
+ browser: {
+ description: 'Browser name',
+ type: 'string',
+ },
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
+ operating_system: {
+ description: 'Operating system',
+ type: 'string',
+ },
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
+ screen_width: {
+ description: 'Screen width in pixels',
+ type: 'number',
+ },
+ screen_height: {
+ description: 'Screen height in pixels',
+ type: 'number',
+ },
+ referrer: {
+ description: 'First non-empty referrer in the session',
+ type: 'string',
+ },
+ channel: {
+ description: 'Traffic channel',
+ type: 'string',
+ },
+ session_start: {
+ description: 'Time of the first event',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_end: {
+ description: 'Time of the last event',
+ type: 'string',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
+ },
+ session_duration: {
+ description: 'Duration in seconds',
+ type: 'number',
+ },
+ pageviews: {
+ description: 'Number of pageviews',
+ type: 'number',
+ },
+ events: {
+ description: 'Number of events of every type, including pageviews and performance events',
+ type: 'number',
+ },
+ entry_page: {
+ description: 'First page visited',
+ type: 'string',
+ },
+ exit_page: {
+ description: 'Last page visited',
+ type: 'string',
+ },
+ ip: {
+ description: 'IP address. null unless the site has IP tracking turned on.',
+ type: 'string | null',
+ },
+ }}
+/>
+
#### Event Object
<TypeTable
@@ -93,7 +196,7 @@ Returns detailed information about a specific session including all events and p
timestamp: {
description: 'Event timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS.mmm"',
},
pathname: {
description: 'Page path',
@@ -103,23 +206,58 @@ Returns detailed information about a specific session including all events and p
description: 'Hostname',
type: 'string',
},
+ querystring: {
+ description: 'Raw query string',
+ type: 'string',
+ },
page_title: {
description: 'Page title',
type: 'string',
},
+ referrer: {
+ description: 'Referrer URL',
+ type: 'string',
+ },
type: {
description: 'Event type',
type: 'string',
typeDescription: '"pageview" | "custom_event" | "error" | "outbound" | "button_click" | "copy" | "form_submit" | "input_change"',
},
event_name: {
- description: 'Custom event name (for custom_event type)',
+ description: 'Custom event name, or the error type for errors. Often empty for other types.',
type: 'string',
},
props: {
description: 'Event properties',
type: 'object',
},
+ goals: {
+ description: "Goals this event completed, usually empty. Only the site's 50 oldest goals are matched, and API keys without the goals:read scope always get an empty list.",
+ type: '{ id: number; name: string | null }[]',
+ },
+ }}
+/>
+
+#### Pagination Object
+
+<TypeTable
+ type={{
+ total: {
+ description: 'Number of events in the session, excluding performance events',
+ type: 'number',
+ },
+ limit: {
+ description: 'The limit used',
+ type: 'number',
+ },
+ offset: {
+ description: 'The offset used',
+ type: 'number',
+ },
+ hasMore: {
+ description: 'Whether more events follow this page',
+ type: 'boolean',
+ },
}}
/>
@@ -245,33 +383,51 @@ var data = await response.Content.ReadAsStringAsync();
"session_id": "sess_abc123",
"user_id": "dev_xyz789",
"country": "US",
+ "region": "US-CA",
+ "city": "San Francisco",
+ "language": "en-US",
+ "device_type": "Desktop",
"browser": "Chrome",
+ "browser_version": "120.0",
"operating_system": "macOS",
- "device_type": "desktop",
- "session_start": "2024-01-31T14:00:00.000Z",
- "session_end": "2024-01-31T14:04:05.000Z",
+ "operating_system_version": "14.2",
+ "screen_width": 1920,
+ "screen_height": 1080,
+ "referrer": "https://google.com",
+ "channel": "Organic Search",
+ "session_start": "2024-01-31 14:00:00",
+ "session_end": "2024-01-31 14:04:05",
"session_duration": 245,
"pageviews": 5,
"events": 7,
"entry_page": "/",
- "exit_page": "/pricing"
+ "exit_page": "/pricing",
+ "ip": null
},
"events": [
{
- "timestamp": "2024-01-31T14:00:00.000Z",
+ "timestamp": "2024-01-31 14:00:00.000",
"pathname": "/",
"hostname": "example.com",
+ "querystring": "",
"page_title": "Home",
+ "referrer": "https://google.com",
"type": "pageview",
- "referrer": "https://google.com"
+ "event_name": "",
+ "props": {},
+ "goals": []
},
{
- "timestamp": "2024-01-31T14:01:30.000Z",
+ "timestamp": "2024-01-31 14:01:30.412",
"pathname": "/",
"hostname": "example.com",
+ "querystring": "",
+ "page_title": "Home",
+ "referrer": "",
"type": "custom_event",
"event_name": "cta_click",
- "props": { "button": "hero" }
+ "props": { "button": "hero" },
+ "goals": [{ "id": 12, "name": "CTA click" }]
}
],
"pagination": {
diff --git a/docs/content/docs/api/sessions/list.mdx b/docs/content/docs/api/sessions/list.mdx
index 28b2d5420..e29dd8688 100644
--- a/docs/content/docs/api/sessions/list.mdx
+++ b/docs/content/docs/api/sessions/list.mdx
@@ -31,22 +31,27 @@ Returns a paginated list of sessions with their analytics data.
### Query Parameters
-Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plus the following. An invalid `view`, `sort_by`, `sort_order`, `include_goals`, or min/max value returns `400`.
<TypeTable
type={{
page: {
- description: 'Page number (1-indexed)',
+ description: 'Page number (1-indexed). Invalid values fall back to 1.',
type: 'number',
default: 1,
},
limit: {
- description: 'Number of results per page',
+ description: 'Number of results per page, capped at 10,000. Invalid values fall back to 100.',
type: 'number',
default: 100,
},
user_id: {
- description: 'Filter sessions by user ID',
+ description: 'Only sessions of this user. Matches the identified user ID, or the device ID of anonymous sessions.',
+ type: 'string',
+ required: false,
+ },
+ session_id: {
+ description: 'Only this session',
type: 'string',
required: false,
},
@@ -56,6 +61,60 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
typeDescription: '"true" | "false"',
default: 'false',
},
+ view: {
+ description: 'Preset view. identified: identified users. replay: sessions with a replay. converted: completed at least one goal (turns on include_goals); API keys without the goals:read scope get no sessions for this view. bounced: exactly one pageview. errors: at least one error.',
+ type: 'string',
+ typeDescription: '"all" | "identified" | "replay" | "converted" | "bounced" | "errors"',
+ default: 'all',
+ },
+ sort_by: {
+ description: 'Sort column. events sorts by custom events plus autocaptured interactions. Ties fall back to session start, then session ID.',
+ type: 'string',
+ typeDescription: '"started" | "ended" | "duration" | "pageviews" | "events" | "errors"',
+ default: 'ended',
+ },
+ sort_order: {
+ description: 'Sort direction',
+ type: 'string',
+ typeDescription: '"asc" | "desc"',
+ default: 'desc',
+ },
+ include_goals: {
+ description: "Add converted_goals to each session. Only the site's 50 oldest goals are matched. API keys without the goals:read scope get an empty list.",
+ type: 'string',
+ typeDescription: '"true" | "false"',
+ default: 'false',
+ },
+ min_pageviews: {
+ description: 'Minimum pageviews (inclusive)',
+ type: 'number',
+ required: false,
+ },
+ max_pageviews: {
+ description: 'Maximum pageviews (inclusive)',
+ type: 'number',
+ required: false,
+ },
+ min_events: {
+ description: 'Minimum events (inclusive). Counts custom events plus button clicks, copies, form submits, and input changes.',
+ type: 'number',
+ required: false,
+ },
+ max_events: {
+ description: 'Maximum events (inclusive), counted like min_events',
+ type: 'number',
+ required: false,
+ },
+ min_duration: {
+ description: 'Minimum session duration in seconds (inclusive)',
+ type: 'number',
+ required: false,
+ },
+ max_duration: {
+ description: 'Maximum session duration in seconds (inclusive)',
+ type: 'number',
+ required: false,
+ },
}}
/>
@@ -72,6 +131,8 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
#### Session Object
+Attribute fields (`country`, `browser`, and so on) come from the session's latest event. `referrer`, `channel`, and the UTM fields come from its first event that has one.
+
<TypeTable
type={{
session_id: {
@@ -83,11 +144,11 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'string',
},
identified_user_id: {
- description: 'Custom user ID when identified',
+ description: 'Custom user ID when identified, empty string otherwise',
type: 'string',
},
traits: {
- description: 'Custom user traits',
+ description: 'Custom user traits, null for anonymous users or users without a profile',
type: 'object | null',
},
country: {
@@ -102,18 +163,50 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'City name',
type: 'string',
},
+ lat: {
+ description: 'Latitude of the visitor location',
+ type: 'number',
+ },
+ lon: {
+ description: 'Longitude of the visitor location',
+ type: 'number',
+ },
+ timezone: {
+ description: 'Timezone of the visitor location',
+ type: 'string',
+ },
+ language: {
+ description: 'Browser language',
+ type: 'string',
+ },
browser: {
description: 'Browser name',
type: 'string',
},
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
operating_system: {
description: 'Operating system',
type: 'string',
},
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
device_type: {
description: 'Device type',
type: 'string',
},
+ screen_width: {
+ description: 'Screen width in pixels',
+ type: 'number',
+ },
+ screen_height: {
+ description: 'Screen height in pixels',
+ type: 'number',
+ },
referrer: {
description: 'Referrer URL',
type: 'string',
@@ -122,6 +215,10 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Traffic channel',
type: 'string',
},
+ hostname: {
+ description: 'Hostname of the first event',
+ type: 'string',
+ },
entry_page: {
description: 'First page visited',
type: 'string',
@@ -138,6 +235,30 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Number of custom events',
type: 'number',
},
+ errors: {
+ description: 'Number of errors',
+ type: 'number',
+ },
+ outbound: {
+ description: 'Number of outbound link clicks',
+ type: 'number',
+ },
+ button_clicks: {
+ description: 'Number of autocaptured button clicks',
+ type: 'number',
+ },
+ copies: {
+ description: 'Number of autocaptured copy events',
+ type: 'number',
+ },
+ form_submits: {
+ description: 'Number of autocaptured form submits',
+ type: 'number',
+ },
+ input_changes: {
+ description: 'Number of autocaptured input changes',
+ type: 'number',
+ },
session_duration: {
description: 'Duration in seconds',
type: 'number',
@@ -145,12 +266,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
session_start: {
description: 'Session start time',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
session_end: {
description: 'Session end time',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
utm_source: {
description: 'UTM source parameter',
@@ -164,6 +285,31 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'UTM campaign parameter',
type: 'string',
},
+ utm_term: {
+ description: 'UTM term parameter',
+ type: 'string',
+ },
+ utm_content: {
+ description: 'UTM content parameter',
+ type: 'string',
+ },
+ tag: {
+ description: 'Tag set on the tracking script, empty string if none',
+ type: 'string',
+ },
+ ip: {
+ description: 'IP address. null unless the site has IP tracking turned on.',
+ type: 'string | null',
+ },
+ has_replay: {
+ description: '1 when the session has a session replay, otherwise 0',
+ type: 'number',
+ },
+ converted_goals: {
+ description: 'Goals the session completed, most recent conversion first. Only present with include_goals=true or view=converted.',
+ type: '{ id: number; name: string | null }[]',
+ required: false,
+ },
}}
/>
@@ -296,23 +442,44 @@ var data = await response.Content.ReadAsStringAsync();
"identified_user_id": "[email protected]",
"traits": { "plan": "pro" },
"country": "US",
- "region": "California",
+ "region": "US-CA",
"city": "San Francisco",
+ "lat": 37.7749,
+ "lon": -122.4194,
+ "timezone": "America/Los_Angeles",
+ "language": "en-US",
"browser": "Chrome",
+ "browser_version": "120.0",
"operating_system": "macOS",
- "device_type": "desktop",
+ "operating_system_version": "14.2",
+ "device_type": "Desktop",
+ "screen_width": 1920,
+ "screen_height": 1080,
"referrer": "https://google.com",
- "channel": "organic",
+ "channel": "Organic Search",
+ "hostname": "example.com",
"entry_page": "/",
"exit_page": "/pricing",
"pageviews": 5,
"events": 2,
+ "errors": 0,
+ "outbound": 1,
+ "button_clicks": 3,
+ "copies": 0,
+ "form_submits": 0,
+ "input_changes": 0,
"session_duration": 245,
- "session_start": "2024-01-31T14:00:00.000Z",
- "session_end": "2024-01-31T14:04:05.000Z",
+ "session_start": "2024-01-31 14:00:00",
+ "session_end": "2024-01-31 14:04:05",
"utm_source": "google",
"utm_medium": "cpc",
- "utm_campaign": "brand"
+ "utm_campaign": "brand",
+ "utm_term": "",
+ "utm_content": "",
+ "tag": "",
+ "ip": null,
+ "has_replay": 1,
+ "converted_goals": [{ "id": 12, "name": "Signup" }]
}
]
}
diff --git a/docs/content/docs/api/sites/accept-transfer.mdx b/docs/content/docs/api/sites/accept-transfer.mdx
new file mode 100644
index 000000000..55f360bc3
--- /dev/null
+++ b/docs/content/docs/api/sites/accept-transfer.mdx
@@ -0,0 +1,273 @@
+---
+title: Accept Site Transfer
+description: Moves a transferred site into one of your organizations.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/site-transfers/:transferId/accept
+```
+
+Accepts a [site transfer](/docs/api/sites/create-transfer) and moves the site, with its data, into the organization you choose. The move has the same effects as [Move Site](/docs/api/sites/move), and the site's private link is also removed.
+
+**Authentication:** a signed-in dashboard session belonging to the recipient. API keys don't work here: the route names no site or organization to check a key against, so every API key (personal, scoped or organization) gets `401`. The examples send the session cookie. The JavaScript example is for Node.js: browsers don't let scripts set a `Cookie` header. You must be an `admin` or `owner` of the target organization, and the person who sent the transfer must still be able to transfer the site.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ transferId: {
+ description: "Transfer ID, the last segment of the emailed transfer link",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "ID of your organization to move the site into",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the site was moved",
+ type: "boolean",
+ },
+ siteId: {
+ description: "The transferred site",
+ type: "number",
+ },
+ organizationId: {
+ description: "The site's new organization",
+ type: "string",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "organizationId missing, or the site is already in that organization",
+ type: "object",
+ },
+ "401": {
+ description: "No signed-in session (including any request authenticated only with an API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Signed in with a different email address (reason \"wrong_account\", with a masked recipientEmailHint), or the address isn't verified on Rybbit Cloud (reason \"email_unverified\")",
+ type: "object",
+ },
+ "404": {
+ description: "The transfer doesn't exist, was cancelled, or has expired",
+ type: "object",
+ },
+ "409": {
+ description: "The site has moved since the transfer was sent",
+ type: "object",
+ },
+ }}
+/>
+
+A `403` is also returned when you aren't an admin or owner of the target organization, the target organization is at its plan's site limit, or the sender can no longer transfer the site (the transfer is then cancelled).
+
+</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 POST "https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "organizationId": "org_789"
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept',
+ {
+ method: 'POST',
+ headers: {
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ organizationId: 'org_789'
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept',
+ json={
+ 'organizationId': 'org_789'
+ },
+ headers={
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'organizationId' => 'org_789'
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept')
+request = Net::HTTP::Post.new(uri)
+request['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+request['Content-Type'] = 'application/json'
+request.body = {
+ organizationId: 'org_789'
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "organizationId": "org_789",
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept", bytes.NewBuffer(jsonBody))
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "organizationId": "org_789"
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "organizationId": "org_789"
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept"))
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ organizationId = "org_789"
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/accept", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true,
+ "siteId": 123,
+ "organizationId": "org_789"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/cancel-transfer.mdx b/docs/content/docs/api/sites/cancel-transfer.mdx
new file mode 100644
index 000000000..63dd1fe8d
--- /dev/null
+++ b/docs/content/docs/api/sites/cancel-transfer.mdx
@@ -0,0 +1,171 @@
+---
+title: Cancel Site Transfer
+description: Cancels the site's pending transfer so its link stops working.
+full: true
+method: DELETE
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+DELETE /api/sites/:site/transfer
+```
+
+Cancels the site's pending transfer. The emailed link stops working. Succeeds even when there is no pending transfer.
+
+**Permissions:** the `admin` role or above in the site's organization. API keys need the `sites:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Always true",
+ type: "boolean",
+ },
+ }}
+/>
+
+</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 DELETE "https://app.rybbit.io/api/sites/123/transfer" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/transfer',
+ {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.delete(
+ 'https://app.rybbit.io/api/sites/123/transfer',
+ 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://app.rybbit.io/api/sites/123/transfer');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
+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://app.rybbit.io/api/sites/123/transfer')
+request = Net::HTTP::Delete.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+req, _ := http.NewRequest("DELETE", "https://app.rybbit.io/api/sites/123/transfer", 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
+ .delete("https://app.rybbit.io/api/sites/123/transfer")
+ .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://app.rybbit.io/api/sites/123/transfer"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .DELETE()
+ .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.DeleteAsync("https://app.rybbit.io/api/sites/123/transfer");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/create-transfer.mdx b/docs/content/docs/api/sites/create-transfer.mdx
new file mode 100644
index 000000000..a5ed1a4fd
--- /dev/null
+++ b/docs/content/docs/api/sites/create-transfer.mdx
@@ -0,0 +1,287 @@
+---
+title: Create Site Transfer
+description: Starts handing a site to someone outside your organization by emailing them a transfer link.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/sites/:site/transfer
+```
+
+Emails the recipient a link that lets them move the site into one of their own organizations. Nothing moves until they [accept](/docs/api/sites/accept-transfer). A site has at most one pending transfer: creating a new one cancels the previous link. The link expires after 7 days.
+
+The link is also returned in the response, so you can pass it on yourself if the email doesn't arrive.
+
+**Permissions:** the `admin` role or above in the site's organization. API keys need the `sites:write` scope. A transfer must be started by a person, so organization API keys are rejected with `401`.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ email: {
+ description: "Recipient's email address. They must accept while signed in with this address",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+Returns `201` with the pending transfer.
+
+<TypeTable
+ type={{
+ id: {
+ description: "Transfer ID (the secret in the link)",
+ type: "string",
+ },
+ recipientEmail: {
+ description: "Recipient's email address, lowercased",
+ type: "string",
+ },
+ createdAt: {
+ description: "When the transfer was created",
+ type: "string",
+ typeDescription: "ISO 8601 UTC, e.g. 2026-10-31T14:22:05.000Z",
+ },
+ expiresAt: {
+ description: "When the link stops working, 7 days after creation",
+ type: "string",
+ typeDescription: "ISO 8601 UTC",
+ },
+ url: {
+ description: "Link the recipient opens to accept",
+ type: "string",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Missing or invalid email",
+ type: "object",
+ },
+ "401": {
+ description: "No user behind the credential (organization API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Not an admin or owner of the site's organization, or missing the sites:write scope",
+ type: "object",
+ },
+ "404": {
+ description: "Site not found",
+ type: "object",
+ },
+ "409": {
+ description: "The site moved while the request was in flight",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/sites/123/transfer" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "email": "[email protected]"
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/transfer',
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/sites/123/transfer',
+ json={
+ 'email': '[email protected]'
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'email' => '[email protected]'
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/sites/123/transfer');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/sites/123/transfer')
+request = Net::HTTP::Post.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "email": "[email protected]",
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/sites/123/transfer", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "email": "[email protected]"
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/sites/123/transfer")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "email": "[email protected]"
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/sites/123/transfer"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ email = "[email protected]"
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/sites/123/transfer", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "id": "q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a",
+ "recipientEmail": "[email protected]",
+ "createdAt": "2026-10-31T14:22:05.000Z",
+ "expiresAt": "2026-11-07T14:22:05.000Z",
+ "url": "https://app.rybbit.io/transfer/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/decline-transfer.mdx b/docs/content/docs/api/sites/decline-transfer.mdx
new file mode 100644
index 000000000..122e06f10
--- /dev/null
+++ b/docs/content/docs/api/sites/decline-transfer.mdx
@@ -0,0 +1,192 @@
+---
+title: Decline Site Transfer
+description: Turns down a site transfer sent to you.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/site-transfers/:transferId/decline
+```
+
+Declines a [site transfer](/docs/api/sites/create-transfer). The transfer is deleted and the site stays where it is.
+
+**Authentication:** a signed-in dashboard session belonging to the recipient. API keys don't work here: the route names no site or organization to check a key against, so every API key (personal, scoped or organization) gets `401`. The examples send the session cookie. The JavaScript example is for Node.js: browsers don't let scripts set a `Cookie` header.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ transferId: {
+ description: "Transfer ID, the last segment of the emailed transfer link",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the transfer was declined",
+ type: "boolean",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "401": {
+ description: "No signed-in session (including any request authenticated only with an API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Signed in with a different email address (reason \"wrong_account\", with a masked recipientEmailHint), or the address isn't verified on Rybbit Cloud (reason \"email_unverified\")",
+ type: "object",
+ },
+ "404": {
+ description: "The transfer doesn't exist, was cancelled, or has expired",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline',
+ {
+ method: 'POST',
+ headers: {
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+ }
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline',
+ headers={
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+]);
+
+$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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline')
+request = Net::HTTP::Post.new(uri)
+request['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline", nil)
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+
+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
+ .post("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline"))
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .POST(HttpRequest.BodyPublishers.noBody())
+ .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("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a/decline", null);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/delete.mdx b/docs/content/docs/api/sites/delete.mdx
index 6bbfa4f90..f7e20a2ad 100644
--- a/docs/content/docs/api/sites/delete.mdx
+++ b/docs/content/docs/api/sites/delete.mdx
@@ -1,6 +1,6 @@
---
title: Delete Site
-description: Permanently deletes a site and all its associated data. This action cannot be undone. Requires admin or owner role.
+description: Permanently deletes a site, its settings, saved reports, and session replays. Collected events and sessions are not deleted. Requires the admin or owner role.
full: true
method: DELETE
---
@@ -15,7 +15,17 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/sites/:siteId
```
-Permanently deletes a site and all its associated data. This action cannot be undone. Requires admin or owner role.
+Permanently deletes a site. This cannot be undone. Requires the admin or owner role (the `sites:delete` permission).
+
+What is deleted:
+
+- The site and its settings, including private link keys and exclusion lists.
+- Everything stored against it: goals, funnels, segments, annotations, dashboards, feature flags, experiments, the Search Console connection, member and team site access, pending transfers, import history, and identified-user profiles and aliases.
+- Session replay rows stored in ClickHouse. On Rybbit Cloud, replay event data kept in R2 object storage is not deleted.
+
+Events and sessions already collected are not deleted from ClickHouse.
+
+Returns `403` for a site that doesn't exist or that you can't access; `404` for a malformed ID or an unknown text site identifier.
### Path Parameters
diff --git a/docs/content/docs/api/sites/excluded-asns.mdx b/docs/content/docs/api/sites/excluded-asns.mdx
new file mode 100644
index 000000000..cb653e1b6
--- /dev/null
+++ b/docs/content/docs/api/sites/excluded-asns.mdx
@@ -0,0 +1,174 @@
+---
+title: Get Excluded ASNs
+description: Returns the list of autonomous system numbers (ASNs) that are excluded from tracking.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/excluded-asns
+```
+
+Returns the list of autonomous system numbers (ASNs) that are excluded from tracking. Set the list with [Update Site Config](/docs/api/sites/update-config).
+
+**Permissions:** the `viewer` role or above on the site. API keys need the `sites:read` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the request was successful",
+ type: "boolean",
+ },
+ excludedASNs: {
+ description: "Array of excluded ASNs, as entered: with or without the AS prefix (e.g. AS13335 or 13335)",
+ 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://app.rybbit.io/api/sites/123/excluded-asns" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/excluded-asns',
+ {
+ 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://app.rybbit.io/api/sites/123/excluded-asns',
+ 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://app.rybbit.io/api/sites/123/excluded-asns');
+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://app.rybbit.io/api/sites/123/excluded-asns')
+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://app.rybbit.io/api/sites/123/excluded-asns", 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://app.rybbit.io/api/sites/123/excluded-asns")
+ .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://app.rybbit.io/api/sites/123/excluded-asns"))
+ .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://app.rybbit.io/api/sites/123/excluded-asns");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true,
+ "excludedASNs": [
+ "AS13335",
+ "16509"
+ ]
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/excluded-query-params.mdx b/docs/content/docs/api/sites/excluded-query-params.mdx
new file mode 100644
index 000000000..c90b7c88c
--- /dev/null
+++ b/docs/content/docs/api/sites/excluded-query-params.mdx
@@ -0,0 +1,174 @@
+---
+title: Get Excluded Query Params
+description: Returns the list of query parameter rules that are excluded from tracking.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/excluded-query-params
+```
+
+Returns the list of query parameter rules that are excluded from tracking. Set the list with [Update Site Config](/docs/api/sites/update-config).
+
+**Permissions:** the `viewer` role or above on the site. API keys need the `sites:read` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the request was successful",
+ type: "boolean",
+ },
+ excludedQueryParams: {
+ description: "Array of query parameter rules: \"name\" excludes a request that has the parameter; \"name=value\" also matches the value, with * as a wildcard. Matching is case-insensitive",
+ 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://app.rybbit.io/api/sites/123/excluded-query-params" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/excluded-query-params',
+ {
+ 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://app.rybbit.io/api/sites/123/excluded-query-params',
+ 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://app.rybbit.io/api/sites/123/excluded-query-params');
+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://app.rybbit.io/api/sites/123/excluded-query-params')
+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://app.rybbit.io/api/sites/123/excluded-query-params", 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://app.rybbit.io/api/sites/123/excluded-query-params")
+ .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://app.rybbit.io/api/sites/123/excluded-query-params"))
+ .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://app.rybbit.io/api/sites/123/excluded-query-params");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true,
+ "excludedQueryParams": [
+ "preview",
+ "utm_source=internal-*"
+ ]
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/export-pdf.mdx b/docs/content/docs/api/sites/export-pdf.mdx
index 97dcc70a0..930495c65 100644
--- a/docs/content/docs/api/sites/export-pdf.mdx
+++ b/docs/content/docs/api/sites/export-pdf.mdx
@@ -17,6 +17,8 @@ GET /api/sites/:site/export/pdf
Generates a downloadable PDF analytics report for a date range.
+Needs a role on the site (any role, including viewer). Public-site and private-link visitors cannot call it. On Rybbit Cloud it needs a paid plan: organizations on the free plan or the `appsumo-1` and `appsumo-2` tiers get `403`.
+
### Path Parameters
<TypeTable
@@ -61,6 +63,8 @@ Generates a downloadable PDF analytics report for a date range.
Returns a binary PDF file (`Content-Type: application/pdf`). Save the response body to a `.pdf` file rather than parsing it as JSON.
+Errors come back as JSON: `400` for a missing or malformed `start_date`, `end_date`, `time_zone`, or `filters`; `403` when the plan does not include PDF export, or for a site that doesn't exist or that you can't access; `404` for a malformed site ID or an unknown text site identifier.
+
</div>
<div className="flex flex-col gap-4">
diff --git a/docs/content/docs/api/sites/get-incoming-transfer.mdx b/docs/content/docs/api/sites/get-incoming-transfer.mdx
new file mode 100644
index 000000000..5193fb292
--- /dev/null
+++ b/docs/content/docs/api/sites/get-incoming-transfer.mdx
@@ -0,0 +1,217 @@
+---
+title: Get Incoming Site Transfer
+description: Returns the site being offered to you in a transfer link.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/site-transfers/:transferId
+```
+
+The recipient's view of a [site transfer](/docs/api/sites/create-transfer): which site is being offered and by whom. Only the person the transfer was sent to can read it.
+
+**Authentication:** a signed-in dashboard session belonging to the recipient. API keys don't work here: the route names no site or organization to check a key against, so every API key (personal, scoped or organization) gets `401`. The examples send the session cookie. The JavaScript example is for Node.js: browsers don't let scripts set a `Cookie` header.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ transferId: {
+ description: "Transfer ID, the last segment of the emailed transfer link",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ id: {
+ description: "Transfer ID",
+ type: "string",
+ },
+ site: {
+ description: "The site being transferred",
+ type: "{ siteId: number, name: string, domain: string }",
+ },
+ sourceOrganizationId: {
+ description: "Organization the site is in now",
+ type: "string",
+ },
+ sourceOrganizationName: {
+ description: "Name of that organization",
+ type: "string",
+ },
+ sentBy: {
+ description: "Email of the person who sent the transfer, if known",
+ type: "string | null",
+ },
+ expiresAt: {
+ description: "When the link stops working",
+ type: "string",
+ typeDescription: "ISO 8601 UTC",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "401": {
+ description: "No signed-in session (including any request authenticated only with an API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Signed in with a different email address (reason \"wrong_account\", with a masked recipientEmailHint), or the address isn't verified on Rybbit Cloud (reason \"email_unverified\")",
+ type: "object",
+ },
+ "404": {
+ description: "The transfer doesn't exist, was cancelled, or has expired",
+ type: "object",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a" \
+ -H "Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a',
+ {
+ headers: {
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+ }
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.get(
+ 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a',
+ headers={
+ 'Cookie': '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Cookie: __Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+]);
+
+$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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a')
+req = Net::HTTP::Get.new(uri)
+req['Cookie'] = '__Secure-better-auth.session_token=YOUR_SESSION_TOKEN'
+
+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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a", nil)
+req.Header.Set("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+
+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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a")
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .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://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a"))
+ .header("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN")
+ .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("Cookie", "__Secure-better-auth.session_token=YOUR_SESSION_TOKEN");
+
+var response = await client.GetAsync("https://app.rybbit.io/api/site-transfers/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "id": "q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a",
+ "site": {
+ "siteId": 123,
+ "name": "Acme",
+ "domain": "acme.com"
+ },
+ "sourceOrganizationId": "org_123",
+ "sourceOrganizationName": "Acme Agency",
+ "sentBy": "[email protected]",
+ "expiresAt": "2026-11-07T14:22:05.000Z"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/get-private-link.mdx b/docs/content/docs/api/sites/get-private-link.mdx
index b46e300de..bc54097c0 100644
--- a/docs/content/docs/api/sites/get-private-link.mdx
+++ b/docs/content/docs/api/sites/get-private-link.mdx
@@ -15,7 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
GET /api/sites/:siteId/private-link-config
```
-Returns the private link key configuration. Private links allow sharing analytics with a secret key without requiring authentication.
+Returns the private link key configuration. Private links allow sharing analytics with a secret key without requiring authentication. Requires the editor role or above on the site (the `sites:configure` permission).
+
+A private-link viewer sends the key in the `x-private-key` request header. With it, read endpoints that allow public access answer as they would for a public site.
### Path Parameters
diff --git a/docs/content/docs/api/sites/get-transfer.mdx b/docs/content/docs/api/sites/get-transfer.mdx
new file mode 100644
index 000000000..41a55a59b
--- /dev/null
+++ b/docs/content/docs/api/sites/get-transfer.mdx
@@ -0,0 +1,201 @@
+---
+title: Get Site Transfer
+description: Returns the site's pending transfer, or null when there is none.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/transfer
+```
+
+Returns the site's pending transfer. Expired transfers are returned as `null`.
+
+**Permissions:** the `admin` role or above in the site's organization. API keys need the `sites:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ transfer: {
+ description: "The pending transfer, or null",
+ type: "SiteTransfer | null",
+ },
+ }}
+/>
+
+#### SiteTransfer Object
+
+<TypeTable
+ type={{
+ id: {
+ description: "Transfer ID (the secret in the link)",
+ type: "string",
+ },
+ recipientEmail: {
+ description: "Recipient's email address, lowercased",
+ type: "string",
+ },
+ createdAt: {
+ description: "When the transfer was created",
+ type: "string",
+ typeDescription: "ISO 8601 UTC, e.g. 2026-10-31T14:22:05.000Z",
+ },
+ expiresAt: {
+ description: "When the link stops working, 7 days after creation",
+ type: "string",
+ typeDescription: "ISO 8601 UTC",
+ },
+ url: {
+ description: "Link the recipient opens to accept",
+ 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://app.rybbit.io/api/sites/123/transfer" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/transfer',
+ {
+ 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://app.rybbit.io/api/sites/123/transfer',
+ 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://app.rybbit.io/api/sites/123/transfer');
+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://app.rybbit.io/api/sites/123/transfer')
+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://app.rybbit.io/api/sites/123/transfer", 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://app.rybbit.io/api/sites/123/transfer")
+ .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://app.rybbit.io/api/sites/123/transfer"))
+ .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://app.rybbit.io/api/sites/123/transfer");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "transfer": {
+ "id": "q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a",
+ "recipientEmail": "[email protected]",
+ "createdAt": "2026-10-31T14:22:05.000Z",
+ "expiresAt": "2026-11-07T14:22:05.000Z",
+ "url": "https://app.rybbit.io/transfer/q3Zt8xK2mVb7Lp0RfY1nWc4sHd9eJg6a"
+ }
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/get.mdx b/docs/content/docs/api/sites/get.mdx
index 80f2dac5b..88fe5784d 100644
--- a/docs/content/docs/api/sites/get.mdx
+++ b/docs/content/docs/api/sites/get.mdx
@@ -17,6 +17,8 @@ GET /api/sites/:siteId
Returns detailed information about a specific site including its configuration.
+Any role on the site can call this. Public sites, and private-link viewers who send the key in the `x-private-key` header, can call it too; for them `role` is `null` and `permissions` is empty.
+
### Path Parameters
<TypeTable
@@ -34,7 +36,7 @@ Returns detailed information about a specific site including its configuration.
<TypeTable
type={{
id: {
- description: 'Site UUID',
+ description: 'Site string identifier (12 hex characters)',
type: 'string | null',
},
siteId: {
@@ -45,32 +47,46 @@ Returns detailed information about a specific site including its configuration.
description: 'Site name',
type: 'string',
},
+ type: {
+ description: 'Site type',
+ type: 'string',
+ typeDescription: '"web" | "mobile"',
+ },
domain: {
- description: 'Site domain',
+ description: 'Site domain, or app identifier for mobile sites',
type: 'string',
},
createdAt: {
description: 'Creation timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
updatedAt: {
description: 'Last update timestamp',
- type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ type: 'string | null',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
createdBy: {
description: 'User ID who created the site',
- type: 'string',
+ type: 'string | null',
},
organizationId: {
description: 'Organization ID',
type: 'string | null',
},
+ claimExpiresAt: {
+ description: 'For a site created from the landing page and not yet claimed, when it will be deleted; otherwise null',
+ type: 'string | null',
+ typeDescription: 'ISO 8601 datetime',
+ },
public: {
description: 'Whether the site analytics are publicly accessible',
type: 'boolean',
},
+ embedEnabled: {
+ description: 'Whether the stats widget may be embedded',
+ type: 'boolean',
+ },
saltUserIds: {
description: 'Whether user IDs are salted for privacy',
type: 'boolean',
@@ -79,8 +95,29 @@ Returns detailed information about a specific site including its configuration.
description: 'Whether bot traffic is blocked',
type: 'boolean',
},
+ firstPartyProxy: {
+ description: 'Whether visitor IPs are read from first-party proxy headers',
+ type: 'boolean',
+ },
+ trackIp: {
+ description: 'Whether visitor IP addresses are stored',
+ type: 'boolean',
+ },
+ role: {
+ description: 'Your role on this site, or null for public and private-link viewers',
+ type: 'string | null',
+ typeDescription: '"owner" | "admin" | "editor" | "member" | "viewer" | null',
+ },
+ permissions: {
+ description: 'Permissions your role holds on this site (e.g. "goals:write", "sites:configure"). An API key\'s scopes can narrow what it may actually do.',
+ type: 'string[]',
+ },
isOwner: {
- description: 'Whether the current user owns this site',
+ description: 'True when your role is admin or owner',
+ type: 'boolean',
+ },
+ requiresPlan: {
+ description: 'Whether the site collects no data until its organization starts a plan',
type: 'boolean',
},
sessionReplay: {
@@ -107,9 +144,31 @@ Returns detailed information about a specific site including its configuration.
description: 'Whether ordinary URL fragments are included in tracked paths. Defaults to false.',
type: 'boolean',
},
+ trackInitialPageView: {
+ description: 'Whether a pageview is sent when the script loads',
+ type: 'boolean',
+ },
+ trackSpaNavigation: {
+ description: 'Whether single-page-app route changes are tracked',
+ type: 'boolean',
+ },
+ trackButtonClicks: {
+ description: 'Whether button clicks are captured automatically',
+ type: 'boolean',
+ },
+ trackCopy: {
+ description: 'Whether text copy events are captured',
+ type: 'boolean',
+ },
+ trackFormInteractions: {
+ description: 'Whether form interactions are captured',
+ type: 'boolean',
+ },
}}
/>
+Returns `403` for a site that doesn't exist or that you can't access; `404` for a malformed ID or an unknown text site identifier.
+
</div>
<div className="flex flex-col gap-4">
@@ -226,23 +285,37 @@ var data = await response.Content.ReadAsStringAsync();
```json title="Response"
{
- "id": "site_abc123",
+ "id": "a1b2c3d4e5f6",
"siteId": 123,
"name": "My Website",
+ "type": "web",
"domain": "example.com",
- "createdAt": "2024-01-15T10:30:00.000Z",
- "updatedAt": "2024-01-31T14:00:00.000Z",
+ "createdAt": "2024-01-15 10:30:00.123456",
+ "updatedAt": "2024-01-31 14:00:00.5",
"createdBy": "user_xyz789",
"organizationId": "org_def456",
- "public": false,
+ "claimExpiresAt": null,
"saltUserIds": false,
+ "public": false,
+ "embedEnabled": false,
"blockBots": true,
- "isOwner": true,
+ "firstPartyProxy": false,
+ "trackIp": false,
+ "isOwner": false,
+ "role": "editor",
+ "permissions": ["analytics:read", "sessions:read", "goals:write", "sites:configure"],
+ "requiresPlan": false,
"sessionReplay": true,
"webVitals": true,
"trackErrors": true,
"trackOutbound": true,
- "trackUrlParams": false
+ "trackUrlParams": false,
+ "trackUrlFragments": false,
+ "trackInitialPageView": true,
+ "trackSpaNavigation": true,
+ "trackButtonClicks": false,
+ "trackCopy": false,
+ "trackFormInteractions": false
}
```
diff --git a/docs/content/docs/api/sites/meta.json b/docs/content/docs/api/sites/meta.json
index 8322d6bd0..01b2fe6cc 100644
--- a/docs/content/docs/api/sites/meta.json
+++ b/docs/content/docs/api/sites/meta.json
@@ -1,4 +1,28 @@
{
"title": "Sites",
- "pages": ["get", "has-data", "is-public", "delete", "update-config", "excluded-ips", "excluded-countries", "excluded-paths", "excluded-hostnames", "excluded-user-agents", "get-private-link", "update-private-link", "export-pdf"]
+ "pages": [
+ "get",
+ "has-data",
+ "is-public",
+ "delete",
+ "update-config",
+ "excluded-ips",
+ "excluded-countries",
+ "excluded-paths",
+ "excluded-hostnames",
+ "excluded-user-agents",
+ "excluded-asns",
+ "excluded-query-params",
+ "usage",
+ "get-private-link",
+ "update-private-link",
+ "export-pdf",
+ "move",
+ "create-transfer",
+ "get-transfer",
+ "cancel-transfer",
+ "get-incoming-transfer",
+ "accept-transfer",
+ "decline-transfer"
+ ]
}
diff --git a/docs/content/docs/api/sites/move.mdx b/docs/content/docs/api/sites/move.mdx
new file mode 100644
index 000000000..bb592ddd4
--- /dev/null
+++ b/docs/content/docs/api/sites/move.mdx
@@ -0,0 +1,273 @@
+---
+title: Move Site
+description: Moves a site to another organization you administer.
+full: true
+method: PUT
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+PUT /api/sites/:site/move
+```
+
+Moves a site, with all its data, into another organization. You must administer both organizations. To hand a site to someone outside your organizations, use [Create Site Transfer](/docs/api/sites/create-transfer).
+
+Moving a site also:
+
+- removes per-member and per-team access grants for the site (the new organization's members reach it through their own roles)
+- moves the site's own segments, annotations and import history with it (organization-wide ones stay)
+- cancels any pending site transfer
+- disconnects Google Search Console
+
+**Permissions:** the `admin` role or above in the site's organization. API keys need the `sites:write` scope. You also need the `admin` or `owner` role in the target organization. The move is checked against your own memberships, so organization API keys are rejected with `401`; use a personal key or a session.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ organizationId: {
+ description: "ID of the organization to move the site into",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the site was moved",
+ type: "boolean",
+ },
+ organizationId: {
+ description: "The site's new organization",
+ type: "string",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid body, or the site is already in that organization",
+ type: "object",
+ },
+ "401": {
+ description: "No user behind the credential (organization API key)",
+ type: "object",
+ },
+ "403": {
+ description: "Not an admin or owner of the site's organization or the target organization, or the target organization is at its plan's site limit",
+ type: "object",
+ },
+ "404": {
+ description: "Site or target organization not found",
+ type: "object",
+ },
+ "409": {
+ description: "The site moved while the request was in flight",
+ type: "object",
+ },
+ }}
+/>
+
+</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 PUT "https://app.rybbit.io/api/sites/123/move" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "organizationId": "org_456"
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/move',
+ {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ organizationId: 'org_456'
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.put(
+ 'https://app.rybbit.io/api/sites/123/move',
+ json={
+ 'organizationId': 'org_456'
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'organizationId' => 'org_456'
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/sites/123/move');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/sites/123/move')
+request = Net::HTTP::Put.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ organizationId: 'org_456'
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "organizationId": "org_456",
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("PUT", "https://app.rybbit.io/api/sites/123/move", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "organizationId": "org_456"
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .put("https://app.rybbit.io/api/sites/123/move")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "organizationId": "org_456"
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/sites/123/move"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ organizationId = "org_456"
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PutAsync("https://app.rybbit.io/api/sites/123/move", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true,
+ "organizationId": "org_456"
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/sites/update-config.mdx b/docs/content/docs/api/sites/update-config.mdx
index 8f02663e9..5e3bbcaa2 100644
--- a/docs/content/docs/api/sites/update-config.mdx
+++ b/docs/content/docs/api/sites/update-config.mdx
@@ -15,7 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/sites/:siteId/config
```
-Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires the editor role or above on the site.
+Updates site configuration settings. All fields are optional - only include the fields you want to update. Requires the editor role or above on the site (the `sites:configure` permission).
+
+Fields you omit keep their current values. The `excluded*` lists and `tags` replace the stored list as a whole, so send the full list each time.
### Path Parameters
@@ -33,10 +35,22 @@ Updates site configuration settings. All fields are optional - only include the
<TypeTable
type={{
+ name: {
+ description: 'Display name',
+ type: 'string',
+ typeDescription: '1-255 characters',
+ required: false,
+ },
domain: {
- description: 'Site domain',
+ description: 'Site domain, or the app identifier for a mobile site. A leading http:// or https:// and trailing slashes are removed.',
type: 'string',
- typeDescription: 'Valid domain format (e.g., example.com)',
+ typeDescription: 'Valid domain (e.g., example.com) for web sites; bundle/package ID (e.g., com.example.app) for mobile sites',
+ required: false,
+ },
+ type: {
+ description: 'Site type. Switching to mobile turns off session replay and Web Vitals.',
+ type: 'string | null',
+ typeDescription: '"web" | "mobile" (null means web)',
required: false,
},
public: {
@@ -44,6 +58,11 @@ Updates site configuration settings. All fields are optional - only include the
type: 'boolean',
required: false,
},
+ embedEnabled: {
+ description: 'Allow embedding the stats widget',
+ type: 'boolean',
+ required: false,
+ },
saltUserIds: {
description: 'Salt user IDs for privacy',
type: 'boolean',
@@ -54,8 +73,13 @@ Updates site configuration settings. All fields are optional - only include the
type: 'boolean',
required: false,
},
+ firstPartyProxy: {
+ description: 'The site sends tracking through a first-party proxy (Cloudflare Worker, CloudFront, nginx), so the visitor IP is read from forwarded headers',
+ type: 'boolean',
+ required: false,
+ },
excludedIPs: {
- description: 'List of IP addresses or CIDR ranges to exclude',
+ description: 'IP addresses, CIDR ranges, or a-b ranges to exclude',
type: 'string[]',
typeDescription: 'Max 100 entries',
required: false,
@@ -63,16 +87,52 @@ Updates site configuration settings. All fields are optional - only include the
excludedCountries: {
description: 'List of country codes to exclude',
type: 'string[]',
- typeDescription: '2-letter ISO codes (e.g., US, GB)',
+ typeDescription: 'Uppercase 2-letter ISO codes (e.g., US, GB), max 250 entries',
+ required: false,
+ },
+ excludedPaths: {
+ description: 'Path patterns to exclude, case-insensitive, * matches anything (e.g., /admin/*)',
+ type: 'string[]',
+ typeDescription: 'Max 100 entries, 2048 characters each',
+ required: false,
+ },
+ excludedHostnames: {
+ description: 'Hostname patterns to exclude, case-insensitive, * matches anything (e.g., *.vercel.app)',
+ type: 'string[]',
+ typeDescription: 'Max 100 entries, 253 characters each',
+ required: false,
+ },
+ excludedUserAgents: {
+ description: 'Case-insensitive substrings; a request whose user agent contains one is excluded (e.g., HeadlessChrome)',
+ type: 'string[]',
+ typeDescription: 'Max 100 entries, 512 characters each',
+ required: false,
+ },
+ excludedASNs: {
+ description: 'Autonomous system numbers to exclude, with or without the AS prefix (e.g., AS13335 or 13335)',
+ type: 'string[]',
+ typeDescription: 'Max 100 entries, each at most 4294967295',
+ required: false,
+ },
+ excludedQueryParams: {
+ description: 'Query parameter rules: "name" excludes a request that has the parameter; "name=value" also matches the value, with * as a wildcard (e.g., utm_source=internal-*). Case-insensitive.',
+ type: 'string[]',
+ typeDescription: 'Max 100 entries, 512 characters each; must not start with =',
+ required: false,
+ },
+ tags: {
+ description: 'Labels for organizing sites',
+ type: 'string[]',
+ typeDescription: 'Max 20 tags, 50 characters each',
required: false,
},
sessionReplay: {
- description: 'Enable session replay',
+ description: 'Enable session replay. Web sites only.',
type: 'boolean',
required: false,
},
webVitals: {
- description: 'Enable Web Vitals tracking',
+ description: 'Enable Web Vitals tracking. Web sites only.',
type: 'boolean',
required: false,
},
@@ -96,6 +156,36 @@ Updates site configuration settings. All fields are optional - only include the
type: 'boolean',
required: false,
},
+ trackInitialPageView: {
+ description: 'Send a pageview when the tracking script loads. Enabled by default.',
+ type: 'boolean',
+ required: false,
+ },
+ trackSpaNavigation: {
+ description: 'Send a pageview on single-page-app route changes. Enabled by default.',
+ type: 'boolean',
+ required: false,
+ },
+ trackIp: {
+ description: 'Store visitor IP addresses. Disabled by default.',
+ type: 'boolean',
+ required: false,
+ },
+ trackButtonClicks: {
+ description: 'Capture button clicks automatically',
+ type: 'boolean',
+ required: false,
+ },
+ trackCopy: {
+ description: 'Capture text copy events automatically',
+ type: 'boolean',
+ required: false,
+ },
+ trackFormInteractions: {
+ description: 'Capture form submissions and input changes automatically',
+ type: 'boolean',
+ required: false,
+ },
}}
/>
@@ -112,12 +202,20 @@ Updates site configuration settings. All fields are optional - only include the
type: 'string',
},
config: {
- description: 'Updated site configuration',
+ description: 'The full site configuration after the update: every request field except name, plus id, siteId, privateLinkKey, and claimExpiresAt',
type: 'object',
},
}}
/>
+### Errors
+
+| Status | When |
+|--------|------|
+| `400` | The body fails validation (`details` lists the problems), an IP pattern is invalid, the domain does not fit the site type, `sessionReplay` or `webVitals` is `true` on a mobile site, or the body has no fields |
+| `403` | Rybbit Cloud only: turning on `sessionReplay` without a plan that includes replay, or turning on `webVitals`, `trackErrors`, `trackButtonClicks`, `trackCopy`, or `trackFormInteractions` without an active or trialing subscription. Turning these off is always allowed. The other features are checked only when the update turns them on, but `sessionReplay: true` is checked every time it is sent, even if replay is already on. |
+| `404` | Malformed site ID or unknown text site identifier (a site that doesn't exist or that you can't access gets `403`) |
+
</div>
<div className="flex flex-col gap-4">
@@ -275,16 +373,37 @@ var data = await response.Content.ReadAsStringAsync();
"success": true,
"message": "Site configuration updated successfully",
"config": {
+ "id": "a1b2c3d4e5f6",
+ "siteId": 123,
+ "type": "web",
+ "domain": "example.com",
"public": true,
+ "embedEnabled": false,
"saltUserIds": false,
"blockBots": true,
+ "firstPartyProxy": false,
"excludedIPs": [],
"excludedCountries": ["CN", "RU"],
+ "excludedPaths": [],
+ "excludedHostnames": [],
+ "excludedUserAgents": [],
+ "excludedASNs": [],
+ "excludedQueryParams": [],
+ "privateLinkKey": null,
+ "claimExpiresAt": null,
"sessionReplay": true,
"webVitals": true,
"trackErrors": true,
"trackOutbound": true,
- "trackUrlParams": false
+ "trackUrlParams": false,
+ "trackUrlFragments": false,
+ "trackInitialPageView": true,
+ "trackSpaNavigation": true,
+ "trackIp": false,
+ "trackButtonClicks": false,
+ "trackCopy": false,
+ "trackFormInteractions": false,
+ "tags": []
}
}
```
diff --git a/docs/content/docs/api/sites/update-private-link.mdx b/docs/content/docs/api/sites/update-private-link.mdx
index 64bc94e52..525658732 100644
--- a/docs/content/docs/api/sites/update-private-link.mdx
+++ b/docs/content/docs/api/sites/update-private-link.mdx
@@ -15,7 +15,9 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/sites/:siteId/private-link-config
```
-Generates or revokes a private link key for sharing analytics without authentication. Requires the editor role or above on the site.
+Generates or revokes a private link key for sharing analytics without authentication. Requires the editor role or above on the site (the `sites:configure` permission).
+
+Generating a new key replaces the old one, so links using the old key stop working. Viewers send the key in the `x-private-key` request header.
### Path Parameters
diff --git a/docs/content/docs/api/sites/usage.mdx b/docs/content/docs/api/sites/usage.mdx
new file mode 100644
index 000000000..7b61979a9
--- /dev/null
+++ b/docs/content/docs/api/sites/usage.mdx
@@ -0,0 +1,204 @@
+---
+title: Get Site Usage
+description: Returns this month's billable event count for a site and its organization, with month-end projections.
+full: true
+method: GET
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+GET /api/sites/:site/usage
+```
+
+Returns the number of billable events the site and its whole organization have recorded since the start of the current calendar month, the organization's monthly event limit, and a month-end projection at the current rate.
+
+Billable events are `pageview`, `custom_event`, `performance`, `outbound`, `button_click`, `copy`, `form_submit` and `input_change`. Errors are not counted.
+
+**Permissions:** the `viewer` role or above on the site. API keys need the `sites:read` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ periodStart: {
+ description: "First day of the current calendar month",
+ type: "string",
+ typeDescription: "YYYY-MM-DD",
+ },
+ daysInMonth: {
+ description: "Days in the current month",
+ type: "number",
+ },
+ daysElapsed: {
+ description: "Days since periodStart, fractional",
+ type: "number",
+ },
+ siteEventsThisMonth: {
+ description: "Billable events for this site this month",
+ type: "number",
+ },
+ orgEventsThisMonth: {
+ description: "Billable events for every site in the organization this month",
+ type: "number",
+ },
+ orgEventLimit: {
+ description: "The organization's monthly event limit. Always null on self-hosted instances",
+ type: "number | null",
+ },
+ projectedSiteEvents: {
+ description: "Month-end projection for the site; null during the first day of the month",
+ type: "number | null",
+ },
+ projectedOrgEvents: {
+ description: "Month-end projection for the organization; null during the first day of the month",
+ type: "number | null",
+ },
+ }}
+/>
+
+</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://app.rybbit.io/api/sites/123/usage" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/usage',
+ {
+ 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://app.rybbit.io/api/sites/123/usage',
+ 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://app.rybbit.io/api/sites/123/usage');
+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://app.rybbit.io/api/sites/123/usage')
+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://app.rybbit.io/api/sites/123/usage", 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://app.rybbit.io/api/sites/123/usage")
+ .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://app.rybbit.io/api/sites/123/usage"))
+ .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://app.rybbit.io/api/sites/123/usage");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "periodStart": "2026-10-01",
+ "daysInMonth": 31,
+ "daysElapsed": 30.4,
+ "siteEventsThisMonth": 182340,
+ "orgEventsThisMonth": 241875,
+ "orgEventLimit": 500000,
+ "projectedSiteEvents": 185939,
+ "projectedOrgEvents": 246649
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/teams/create.mdx b/docs/content/docs/api/teams/create.mdx
index 14c99c43d..9829156fe 100644
--- a/docs/content/docs/api/teams/create.mdx
+++ b/docs/content/docs/api/teams/create.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
POST /api/organizations/:organizationId/teams
```
-Creates a team in an organization. Requires admin/owner role.
+Creates a team in an organization. Requires admin/owner role; API keys need the `org:write` scope.
### Path Parameters
@@ -93,6 +93,11 @@ Returns the created team with HTTP 201.
description: 'Array of granted site IDs',
type: 'number[]',
},
+ siteRole: {
+ description: 'The role set on the team\'s site grants, or null',
+ type: 'string | null',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ },
}}
/>
@@ -272,7 +277,8 @@ var data = await response.Content.ReadAsStringAsync();
"createdAt": "2024-01-15T10:30:00.000Z",
"updatedAt": "2024-01-15T10:30:00.000Z",
"members": ["user_123"],
- "siteIds": [123]
+ "siteIds": [123],
+ "siteRole": null
}
```
diff --git a/docs/content/docs/api/teams/delete.mdx b/docs/content/docs/api/teams/delete.mdx
index b64263d11..a4a390256 100644
--- a/docs/content/docs/api/teams/delete.mdx
+++ b/docs/content/docs/api/teams/delete.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
DELETE /api/organizations/:organizationId/teams/:teamId
```
-Deletes a team. Requires admin/owner role.
+Deletes a team. Requires admin/owner role; API keys need the `org:write` scope.
### Path Parameters
diff --git a/docs/content/docs/api/teams/list.mdx b/docs/content/docs/api/teams/list.mdx
index 4ad06040c..5df9b279e 100644
--- a/docs/content/docs/api/teams/list.mdx
+++ b/docs/content/docs/api/teams/list.mdx
@@ -17,7 +17,7 @@ GET /api/organizations/:organizationId/teams
Returns the teams in an organization, with their members and accessible sites.
-Any organization member may call this. Callers who are not an admin or owner only see the teams they belong to.
+Any organization member may call this (`viewer` or above); API keys need the `org:read` scope. Callers who are not an admin or owner only see the teams they belong to. Organization API keys see every team.
### Path Parameters
@@ -82,6 +82,11 @@ Each team in the `teams` array contains:
description: 'Sites the team can access',
type: 'array',
},
+ siteRole: {
+ description: "The role every one of the team's site grants raises members to; null when the grants carry no role (each member's organization role applies) or carry different roles",
+ type: 'string | null',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ },
}}
/>
@@ -120,6 +125,11 @@ Each team in the `teams` array contains:
description: 'Site name',
type: 'string',
},
+ role: {
+ description: "Role this grant raises the team's members to on the site, or null",
+ type: 'string | null',
+ typeDescription: '"editor" | "member" | "viewer" | null',
+ },
}}
/>
@@ -265,9 +275,11 @@ var data = await response.Content.ReadAsStringAsync();
{
"siteId": 123,
"domain": "example.com",
- "name": "Example Site"
+ "name": "Example Site",
+ "role": null
}
- ]
+ ],
+ "siteRole": null
}
]
}
diff --git a/docs/content/docs/api/teams/update.mdx b/docs/content/docs/api/teams/update.mdx
index f2704018f..ce6a53287 100644
--- a/docs/content/docs/api/teams/update.mdx
+++ b/docs/content/docs/api/teams/update.mdx
@@ -15,7 +15,7 @@ import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
PUT /api/organizations/:organizationId/teams/:teamId
```
-Updates a team's name, members, or site access. Requires admin/owner role.
+Updates a team's name, members, or site access. Requires admin/owner role; API keys need the `org:write` scope.
When `memberUserIds` or `siteIds` is provided, it **replaces** the team's entire existing set (it is not merged). Omit a field to leave it unchanged.
diff --git a/docs/content/docs/api/user-traits/users.mdx b/docs/content/docs/api/user-traits/users.mdx
index 1dac8cd25..3ddc73249 100644
--- a/docs/content/docs/api/user-traits/users.mdx
+++ b/docs/content/docs/api/user-traits/users.mdx
@@ -44,12 +44,12 @@ Returns users matching a specific trait key and value, with location and session
required: true,
},
limit: {
- description: 'Maximum number of users to return',
+ description: 'Maximum number of users to return. Values above 1,000 are capped at 1,000; a non-integer or a value below 1 returns 400.',
type: 'number',
default: '50',
},
offset: {
- description: 'Number of users to skip',
+ description: 'Number of users to skip. Must be a non-negative integer.',
type: 'number',
default: '0',
},
diff --git a/docs/content/docs/api/user-traits/values.mdx b/docs/content/docs/api/user-traits/values.mdx
index e8b8b0d85..578571cac 100644
--- a/docs/content/docs/api/user-traits/values.mdx
+++ b/docs/content/docs/api/user-traits/values.mdx
@@ -39,12 +39,12 @@ Returns the distinct values for a given trait key, with user counts.
required: true,
},
limit: {
- description: 'Maximum number of values to return',
+ description: 'Maximum number of values to return. Values above 10,000 are capped at 10,000; a non-integer or a value below 1 returns 400.',
type: 'number',
default: '1000',
},
offset: {
- description: 'Number of values to skip',
+ description: 'Number of values to skip. Must be a non-negative integer.',
type: 'number',
default: '0',
},
diff --git a/docs/content/docs/api/users/delete.mdx b/docs/content/docs/api/users/delete.mdx
new file mode 100644
index 000000000..cf7c9a53c
--- /dev/null
+++ b/docs/content/docs/api/users/delete.mdx
@@ -0,0 +1,204 @@
+---
+title: Delete User
+description: Permanently deletes a user's analytics data on a site, for GDPR erasure requests. This cannot be undone.
+full: true
+method: DELETE
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+DELETE /api/sites/:site/users/:userId
+```
+
+Permanently deletes a user's data on this site, for erasure requests. `userId` can be an identified user ID or an anonymous device ID. The following is removed:
+
+- Events identified as this user
+- Anonymous (never identified) events from this ID and from every device linked to it with `identify()`
+- Session replay events and recordings for the same rows. On Rybbit Cloud, deleting the stored recording files is best effort: a failure there is logged, not reported, so the response can be `success: true` while some recording payloads remain
+- The user's profile (traits) and device links
+
+Events a linked device recorded while identified as a *different* user are kept, so a shared device doesn't erase someone else's history. This action cannot be undone.
+
+**Permissions:** the `editor` role or above on the site. API keys need the `users:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ userId: {
+ description: "Identified user ID or anonymous device ID",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the data was deleted",
+ type: "boolean",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "userId is empty",
+ type: "object",
+ },
+ "403": {
+ description: "Missing role on the site (editor or above) or the users:write scope",
+ type: "object",
+ },
+ "500": {
+ description: "Failed to delete user",
+ type: "object",
+ },
+ }}
+/>
+
+</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 DELETE "https://app.rybbit.io/api/sites/123/users/user_8421" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/users/user_8421',
+ {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.delete(
+ 'https://app.rybbit.io/api/sites/123/users/user_8421',
+ 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://app.rybbit.io/api/sites/123/users/user_8421');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
+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://app.rybbit.io/api/sites/123/users/user_8421')
+request = Net::HTTP::Delete.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+req, _ := http.NewRequest("DELETE", "https://app.rybbit.io/api/sites/123/users/user_8421", 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
+ .delete("https://app.rybbit.io/api/sites/123/users/user_8421")
+ .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://app.rybbit.io/api/sites/123/users/user_8421"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .DELETE()
+ .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.DeleteAsync("https://app.rybbit.io/api/sites/123/users/user_8421");
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/users/identify.mdx b/docs/content/docs/api/users/identify.mdx
new file mode 100644
index 000000000..31180ee96
--- /dev/null
+++ b/docs/content/docs/api/users/identify.mdx
@@ -0,0 +1,314 @@
+---
+title: Identify User
+description: Links an anonymous device ID to a user ID from your backend, optionally merging traits into the user's profile.
+full: true
+method: POST
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+POST /api/sites/:site/users/identify
+```
+
+Links an anonymous visitor (the device fingerprint shown as `user_id` in sessions and events) to an identified user ID, the same link the tracking script's `identify()` call makes. Past events from that device are attributed to the user in the background; expect them to update within a few minutes. Events already attributed to another identified user keep that attribution.
+
+This is the management endpoint. To identify a visitor as part of tracking (from a browser or server sending events), use [Sending Events](/docs/api/sending-events) or the script's [`identify()`](/docs/identify-users).
+
+**Permissions:** the `member` role or above on the site. API keys need the `users:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ anonymous_id: {
+ description: "The anonymous device ID to link",
+ type: "string",
+ typeDescription: "1-255 characters",
+ required: true,
+ },
+ user_id: {
+ description: "Your user ID. Must differ from anonymous_id",
+ type: "string",
+ typeDescription: "1-255 characters",
+ required: true,
+ },
+ traits: {
+ description: "Traits to merge into the user's existing traits. Keys with a null value are dropped. Without traits, an empty profile is created if none exists",
+ type: "object",
+ typeDescription: "Max 2 KB as JSON",
+ required: false,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the user was identified",
+ type: "boolean",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid payload (missing or oversized fields, traits over 2 KB), or user_id equal to anonymous_id",
+ type: "object",
+ },
+ "403": {
+ description: "Missing role on the site or the users:write scope",
+ type: "object",
+ },
+ "500": {
+ description: "Failed to identify user",
+ type: "object",
+ },
+ }}
+/>
+
+</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 POST "https://app.rybbit.io/api/sites/123/users/identify" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "anonymous_id": "abc123def456",
+ "user_id": "user_8421",
+ "traits": {
+ "email": "[email protected]",
+ "plan": "pro"
+ }
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/users/identify',
+ {
+ method: 'POST',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ anonymous_id: 'abc123def456',
+ user_id: 'user_8421',
+ traits: {
+ email: '[email protected]',
+ plan: 'pro'
+ }
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.post(
+ 'https://app.rybbit.io/api/sites/123/users/identify',
+ json={
+ 'anonymous_id': 'abc123def456',
+ 'user_id': 'user_8421',
+ 'traits': {
+ 'email': '[email protected]',
+ 'plan': 'pro'
+ }
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'anonymous_id' => 'abc123def456',
+ 'user_id' => 'user_8421',
+ 'traits' => [
+ 'email' => '[email protected]',
+ 'plan' => 'pro'
+ ]
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/sites/123/users/identify');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/sites/123/users/identify')
+request = Net::HTTP::Post.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ anonymous_id: 'abc123def456',
+ user_id: 'user_8421',
+ traits: {
+ email: '[email protected]',
+ plan: 'pro'
+ }
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "anonymous_id": "abc123def456",
+ "user_id": "user_8421",
+ "traits": map[string]interface{}{
+ "email": "[email protected]",
+ "plan": "pro",
+ },
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/sites/123/users/identify", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "anonymous_id": "abc123def456",
+ "user_id": "user_8421",
+ "traits": {
+ "email": "[email protected]",
+ "plan": "pro"
+ }
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .post("https://app.rybbit.io/api/sites/123/users/identify")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "anonymous_id": "abc123def456",
+ "user_id": "user_8421",
+ "traits": {
+ "email": "[email protected]",
+ "plan": "pro"
+ }
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/sites/123/users/identify"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .POST(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ anonymous_id = "abc123def456",
+ user_id = "user_8421",
+ traits = new
+ {
+ email = "[email protected]",
+ plan = "pro"
+ }
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PostAsync("https://app.rybbit.io/api/sites/123/users/identify", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/users/info.mdx b/docs/content/docs/api/users/info.mdx
index b2d1855f6..90703749e 100644
--- a/docs/content/docs/api/users/info.mdx
+++ b/docs/content/docs/api/users/info.mdx
@@ -34,6 +34,12 @@ Returns detailed information about a specific user, including their profile trai
}}
/>
+### Query Parameters
+
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters). Without a time range or filters, the response covers the user's full history. With them, only the user's sessions inside the range that match the filters count, so `sessions`, `pageviews`, `first_seen`, `vitals`, `locations`, `devices` and the rest describe that slice. Filters select sessions; every event of a selected session that falls inside the range counts.
+
+Returns `404` with `{"error": "User not found"}` when the user has no events in that slice. A device ID whose events were all claimed by an identified user resolves to that user.
+
### Response
<TypeTable
@@ -124,12 +130,12 @@ Returns detailed information about a specific user, including their profile trai
first_seen: {
description: 'First activity timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
last_seen: {
description: 'Most recent activity timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
timezone: {
description: 'Timezone reported by the browser',
@@ -176,11 +182,11 @@ Returns detailed information about a specific user, including their profile trai
type: 'UserVitals | null',
},
locations: {
- description: 'Per-location breakdown of sessions',
+ description: 'Per-location breakdown of sessions, at most 20 rows, most sessions first',
type: 'UserLocation[]',
},
devices: {
- description: 'Per-device breakdown of sessions',
+ description: 'Per-device breakdown of sessions, at most 20 rows, most sessions first',
type: 'UserDevice[]',
},
linked_devices: {
@@ -244,7 +250,7 @@ Returns detailed information about a specific user, including their profile trai
last_seen: {
description: 'Most recent activity from this location',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
}}
/>
@@ -288,7 +294,7 @@ Returns detailed information about a specific user, including their profile trai
last_seen: {
description: 'Most recent activity on this device',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
}}
/>
@@ -304,7 +310,7 @@ Returns detailed information about a specific user, including their profile trai
created_at: {
description: 'When the device was linked',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: '"YYYY-MM-DD HH:MM:SS.ffffff", no time zone suffix',
},
}}
/>
@@ -448,8 +454,8 @@ var data = await response.Content.ReadAsStringAsync();
"device_type": "desktop",
"screen_width": 2560,
"screen_height": 1440,
- "first_seen": "2024-01-15T10:30:00.000Z",
- "last_seen": "2024-01-31T14:22:00.000Z",
+ "first_seen": "2024-01-15 10:30:00",
+ "last_seen": "2024-01-31 14:22:00",
"timezone": "America/Los_Angeles",
"ip": "203.0.113.42",
"first_referrer": "https://google.com",
@@ -474,7 +480,7 @@ var data = await response.Content.ReadAsStringAsync();
"region": "California",
"city": "San Francisco",
"sessions": 10,
- "last_seen": "2024-01-31T14:22:00.000Z"
+ "last_seen": "2024-01-31 14:22:00"
}
],
"devices": [
@@ -487,13 +493,13 @@ var data = await response.Content.ReadAsStringAsync();
"screen_width": 2560,
"screen_height": 1440,
"sessions": 9,
- "last_seen": "2024-01-31T14:22:00.000Z"
+ "last_seen": "2024-01-31 14:22:00"
}
],
"linked_devices": [
{
"anonymous_id": "xyz789ghi012",
- "created_at": "2024-01-20T08:15:00.000Z"
+ "created_at": "2024-01-20 08:15:00.482113"
}
]
}
diff --git a/docs/content/docs/api/users/list.mdx b/docs/content/docs/api/users/list.mdx
index def88e790..7672a9e0b 100644
--- a/docs/content/docs/api/users/list.mdx
+++ b/docs/content/docs/api/users/list.mdx
@@ -31,7 +31,7 @@ Returns a paginated list of users with their analytics data. Supports filtering
### Query Parameters
-Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plus the following:
+Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plus the following. A malformed `page`, `page_size`, `min_sessions`, or flag value returns `400`.
<TypeTable
type={{
@@ -41,12 +41,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
default: 1,
},
page_size: {
- description: 'Number of results per page',
+ description: 'Number of results per page, capped at 1000',
type: 'number',
default: 100,
},
sort_by: {
- description: 'Field to sort by',
+ description: 'Field to sort by. Unknown values fall back to last_seen.',
type: 'string',
typeDescription: '"first_seen" | "last_seen" | "pageviews" | "sessions" | "events"',
default: 'last_seen',
@@ -63,9 +63,50 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
typeDescription: '"true" | "false"',
default: 'false',
},
+ new_only: {
+ description: 'Only users not seen in the 90 days before the requested period. For an all-time request every user counts as new.',
+ type: 'string',
+ typeDescription: '"true" | "false"',
+ default: 'false',
+ },
+ min_sessions: {
+ description: 'Only users with at least this many sessions in the period',
+ type: 'number',
+ typeDescription: '1 to 1,000,000',
+ required: false,
+ },
+ search: {
+ description: 'Case-insensitive substring search, at most 200 characters. Searches the field named by search_field.',
+ type: 'string',
+ required: false,
+ },
+ search_field: {
+ description: 'What search matches. user_id matches the listed ID (identified ID, or device ID for anonymous users). username, name, and email match profile traits, so they only find identified users; at most 10,000 matching profiles are used (see searchLimited).',
+ type: 'string',
+ typeDescription: '"username" | "name" | "email" | "user_id"',
+ default: 'username',
+ },
+ trait_key: {
+ description: 'Limit to one group of a trait breakdown: users whose trait has this key. Needs trait_value or trait_missing=true, otherwise 400.',
+ type: 'string',
+ required: false,
+ },
+ trait_value: {
+ description: 'With trait_key: only users whose trait equals this value',
+ type: 'string',
+ required: false,
+ },
+ trait_missing: {
+ description: 'With trait_key: only users with no value for that trait (anonymous users included)',
+ type: 'string',
+ typeDescription: '"true" | "false"',
+ default: 'false',
+ },
}}
/>
+Filters qualify sessions; each user's totals then count every event in their matching sessions.
+
### Response
<TypeTable
@@ -83,9 +124,18 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'number',
},
pageSize: {
- description: 'Number of results per page',
+ description: 'Number of results per page, after the cap',
type: 'number',
},
+ searchLimited: {
+ description: 'True when more than 10,000 profiles matched a username, name, or email search, so the results are partial',
+ type: 'boolean',
+ },
+ breakdownLimited: {
+ description: 'Only on an empty response for a trait_key request: true when more than 10,000 identified users match the filters and time range, so no rows are returned. The count is taken before the trait group is applied, so even a small trait group can come back empty',
+ type: 'boolean',
+ required: false,
+ },
}}
/>
@@ -93,8 +143,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
<TypeTable
type={{
+ effective_user_id: {
+ description: 'The ID the user is listed by: identified_user_id when identified, otherwise user_id',
+ type: 'string',
+ },
user_id: {
- description: 'Device fingerprint identifier',
+ description: 'Device fingerprint identifier (latest seen)',
type: 'string',
},
identified_user_id: {
@@ -102,7 +156,7 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
type: 'string',
},
traits: {
- description: 'Custom user traits/properties',
+ description: 'Custom user traits/properties, null for anonymous users',
type: 'object | null',
},
country: {
@@ -125,12 +179,40 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
description: 'Browser name',
type: 'string',
},
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
operating_system: {
description: 'Operating system name',
type: 'string',
},
+ operating_system_version: {
+ description: 'Operating system version',
+ type: 'string',
+ },
device_type: {
- description: 'Device type (desktop, mobile, tablet)',
+ description: 'Device type',
+ type: 'string',
+ },
+ screen_width: {
+ description: 'Screen width in pixels',
+ type: 'number',
+ },
+ screen_height: {
+ description: 'Screen height in pixels',
+ type: 'number',
+ },
+ referrer: {
+ description: 'Referrer of the first event that has one',
+ type: 'string',
+ },
+ channel: {
+ description: 'Traffic channel',
+ type: 'string',
+ },
+ tag: {
+ description: 'Tag set on the tracking script, empty string if none',
type: 'string',
},
pageviews: {
@@ -152,12 +234,12 @@ Accepts all [Common Parameters](/docs/api/getting-started#common-parameters) plu
first_seen: {
description: 'First activity timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
last_seen: {
description: 'Most recent activity timestamp',
type: 'string',
- typeDescription: 'ISO 8601 datetime',
+ typeDescription: 'UTC, "YYYY-MM-DD HH:MM:SS"',
},
}}
/>
@@ -286,6 +368,7 @@ var data = await response.Content.ReadAsStringAsync();
{
"data": [
{
+ "effective_user_id": "[email protected]",
"user_id": "abc123def456",
"identified_user_id": "[email protected]",
"traits": {
@@ -293,23 +376,31 @@ var data = await response.Content.ReadAsStringAsync();
"company": "Acme Inc"
},
"country": "US",
- "region": "California",
+ "region": "US-CA",
"city": "San Francisco",
"language": "en-US",
"browser": "Chrome",
+ "browser_version": "120.0",
"operating_system": "macOS",
- "device_type": "desktop",
+ "operating_system_version": "14.2",
+ "device_type": "Desktop",
+ "screen_width": 1920,
+ "screen_height": 1080,
+ "referrer": "https://google.com",
+ "channel": "Organic Search",
+ "tag": "",
"pageviews": 156,
"events": 23,
"sessions": 12,
"hostname": "example.com",
- "first_seen": "2024-01-15T10:30:00.000Z",
- "last_seen": "2024-01-31T14:22:00.000Z"
+ "first_seen": "2024-01-15 10:30:00",
+ "last_seen": "2024-01-31 14:22:00"
}
],
"totalCount": 1247,
"page": 1,
- "pageSize": 10
+ "pageSize": 10,
+ "searchLimited": false
}
```
diff --git a/docs/content/docs/api/users/meta.json b/docs/content/docs/api/users/meta.json
index 305cc4786..7b3b3e5c6 100644
--- a/docs/content/docs/api/users/meta.json
+++ b/docs/content/docs/api/users/meta.json
@@ -1,4 +1,11 @@
{
"title": "Users",
- "pages": ["list", "session-count", "info"]
+ "pages": [
+ "list",
+ "session-count",
+ "info",
+ "identify",
+ "update-traits",
+ "delete"
+ ]
}
diff --git a/docs/content/docs/api/users/session-count.mdx b/docs/content/docs/api/users/session-count.mdx
index 79fc11f10..ed7624f47 100644
--- a/docs/content/docs/api/users/session-count.mdx
+++ b/docs/content/docs/api/users/session-count.mdx
@@ -44,9 +44,16 @@ Returns the number of sessions per day for a specific user. Useful for visualizi
default: 'UTC',
typeDescription: 'IANA timezone (e.g., "America/New_York")',
},
+ filters: {
+ description: 'JSON-encoded filter array, same format as the Common Parameters filters. Only sessions that match count.',
+ type: 'string',
+ required: false,
+ },
}}
/>
+The counts always cover the user's full history: `start_date`, `end_date`, and the other time-range parameters are ignored. Days with no sessions are left out. Returns `400` without `user_id`.
+
### Response
<TypeTable
@@ -63,7 +70,7 @@ Returns the number of sessions per day for a specific user. Useful for visualizi
<TypeTable
type={{
date: {
- description: 'Date',
+ description: 'Day the sessions started, in time_zone',
type: 'string',
typeDescription: 'YYYY-MM-DD format',
},
diff --git a/docs/content/docs/api/users/update-traits.mdx b/docs/content/docs/api/users/update-traits.mdx
new file mode 100644
index 000000000..f34d389af
--- /dev/null
+++ b/docs/content/docs/api/users/update-traits.mdx
@@ -0,0 +1,296 @@
+---
+title: Update User Traits
+description: Replaces all stored traits for an identified user.
+full: true
+method: PUT
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
+
+<div className="grid grid-cols-1 xl:grid-cols-2 gap-8">
+<div>
+
+```
+PUT /api/sites/:site/users/:userId/traits
+```
+
+Replaces the user's stored traits with the object you send. Unlike `identify()`, which merges, this overwrites: traits you leave out are removed. Keys with a null value are dropped. The profile is created if the user doesn't have one yet.
+
+**Permissions:** the `member` role or above on the site. API keys need the `users:write` scope.
+
+### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: "Site ID or site identifier",
+ type: "string | number",
+ required: true,
+ },
+ userId: {
+ description: "Identified user ID (the ID passed to identify())",
+ type: "string",
+ required: true,
+ },
+ }}
+/>
+
+### Request Body
+
+<TypeTable
+ type={{
+ traits: {
+ description: "The complete set of traits to store",
+ type: "object",
+ typeDescription: "Max 2 KB as JSON",
+ required: true,
+ },
+ }}
+/>
+
+### Response
+
+<TypeTable
+ type={{
+ success: {
+ description: "Whether the traits were saved",
+ type: "boolean",
+ },
+ }}
+/>
+
+### Error Responses
+
+Errors use the standard body `{ error, code, message, resolution }`.
+
+<TypeTable
+ type={{
+ "400": {
+ description: "Invalid payload (traits missing, not an object, or over 2 KB)",
+ type: "object",
+ },
+ "403": {
+ description: "Missing role on the site or the users:write scope",
+ type: "object",
+ },
+ "500": {
+ description: "Failed to update user traits",
+ type: "object",
+ },
+ }}
+/>
+
+</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 PUT "https://app.rybbit.io/api/sites/123/users/user_8421/traits" \
+ -H "Authorization: Bearer your_api_key_here" \
+ -H "Content-Type: application/json" \
+ -d '{
+ "traits": {
+ "email": "[email protected]",
+ "plan": "enterprise",
+ "company": "Acme Inc"
+ }
+ }'
+```
+ </Tab>
+ <Tab value="JavaScript">
+```javascript title="Request"
+const response = await fetch(
+ 'https://app.rybbit.io/api/sites/123/users/user_8421/traits',
+ {
+ method: 'PUT',
+ headers: {
+ 'Authorization': 'Bearer your_api_key_here',
+ 'Content-Type': 'application/json'
+ },
+ body: JSON.stringify({
+ traits: {
+ email: '[email protected]',
+ plan: 'enterprise',
+ company: 'Acme Inc'
+ }
+ })
+ }
+);
+
+const data = await response.json();
+```
+ </Tab>
+ <Tab value="Python">
+```python title="Request"
+import requests
+
+response = requests.put(
+ 'https://app.rybbit.io/api/sites/123/users/user_8421/traits',
+ json={
+ 'traits': {
+ 'email': '[email protected]',
+ 'plan': 'enterprise',
+ 'company': 'Acme Inc'
+ }
+ },
+ headers={
+ 'Authorization': 'Bearer your_api_key_here'
+ }
+)
+
+data = response.json()
+```
+ </Tab>
+ <Tab value="PHP">
+```php title="Request"
+$body = [
+ 'traits' => [
+ 'email' => '[email protected]',
+ 'plan' => 'enterprise',
+ 'company' => 'Acme Inc'
+ ]
+];
+
+$ch = curl_init();
+curl_setopt($ch, CURLOPT_URL, 'https://app.rybbit.io/api/sites/123/users/user_8421/traits');
+curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
+curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
+curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($body));
+curl_setopt($ch, CURLOPT_HTTPHEADER, [
+ 'Authorization: Bearer your_api_key_here',
+ 'Content-Type: application/json'
+]);
+
+$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://app.rybbit.io/api/sites/123/users/user_8421/traits')
+request = Net::HTTP::Put.new(uri)
+request['Authorization'] = 'Bearer your_api_key_here'
+request['Content-Type'] = 'application/json'
+request.body = {
+ traits: {
+ email: '[email protected]',
+ plan: 'enterprise',
+ company: 'Acme Inc'
+ }
+}.to_json
+
+response = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) do |http|
+ http.request(request)
+end
+
+data = JSON.parse(response.body)
+```
+ </Tab>
+ <Tab value="Go">
+```go title="Request"
+body := map[string]interface{}{
+ "traits": map[string]interface{}{
+ "email": "[email protected]",
+ "plan": "enterprise",
+ "company": "Acme Inc",
+ },
+}
+jsonBody, _ := json.Marshal(body)
+
+req, _ := http.NewRequest("PUT", "https://app.rybbit.io/api/sites/123/users/user_8421/traits", bytes.NewBuffer(jsonBody))
+req.Header.Set("Authorization", "Bearer your_api_key_here")
+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)
+```
+ </Tab>
+ <Tab value="Rust">
+```rust title="Request"
+let body = serde_json::json!({
+ "traits": {
+ "email": "[email protected]",
+ "plan": "enterprise",
+ "company": "Acme Inc"
+ }
+});
+
+let client = reqwest::Client::new();
+let res = client
+ .put("https://app.rybbit.io/api/sites/123/users/user_8421/traits")
+ .header("Authorization", "Bearer your_api_key_here")
+ .json(&body)
+ .send()
+ .await?;
+
+let data: serde_json::Value = res.json().await?;
+```
+ </Tab>
+ <Tab value="Java">
+```java title="Request"
+String json = """
+{
+ "traits": {
+ "email": "[email protected]",
+ "plan": "enterprise",
+ "company": "Acme Inc"
+ }
+}
+""";
+
+HttpClient client = HttpClient.newHttpClient();
+HttpRequest request = HttpRequest.newBuilder()
+ .uri(URI.create("https://app.rybbit.io/api/sites/123/users/user_8421/traits"))
+ .header("Authorization", "Bearer your_api_key_here")
+ .header("Content-Type", "application/json")
+ .PUT(HttpRequest.BodyPublishers.ofString(json))
+ .build();
+
+HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());
+```
+ </Tab>
+ <Tab value=".NET">
+```csharp title="Request"
+var body = new
+{
+ traits = new
+ {
+ email = "[email protected]",
+ plan = "enterprise",
+ company = "Acme Inc"
+ }
+};
+
+using var client = new HttpClient();
+client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
+
+var content = new StringContent(
+ JsonSerializer.Serialize(body),
+ Encoding.UTF8,
+ "application/json");
+
+var response = await client.PutAsync("https://app.rybbit.io/api/sites/123/users/user_8421/traits", content);
+var data = await response.Content.ReadAsStringAsync();
+```
+ </Tab>
+</Tabs>
+
+```json title="Response"
+{
+ "success": true
+}
+```
+
+</div>
+</div>
diff --git a/docs/content/docs/api/weekly-report.mdx b/docs/content/docs/api/weekly-report.mdx
index 73cf3e761..994484a69 100644
--- a/docs/content/docs/api/weekly-report.mdx
+++ b/docs/content/docs/api/weekly-report.mdx
@@ -7,7 +7,7 @@ import { Callout } from 'fumadocs-ui/components/callout';
import { Tab, Tabs } from 'fumadocs-ui/components/tabs';
import { Step, Steps } from 'fumadocs-ui/components/steps';
-This guide builds a script you can run on a schedule (a cron job, GitHub Action, or serverless function) that pulls last week's numbers, compares them to the week before, and posts a digest to Slack, email, or anywhere else.
+This guide builds a script you can run on a schedule (a cron job, GitHub Action, or serverless function) that pulls the last seven complete days, compares them to the seven days before, and posts a digest to Slack, email, or anywhere else.
**Endpoints used:**
@@ -15,17 +15,19 @@ This guide builds a script you can run on a schedule (a cron job, GitHub Action,
- [`GET /metric`](/docs/api/overview/metric) β€” top pages and traffic sources
<Callout type="info">
-Every analytics endpoint takes the same [time parameters](/docs/api/getting-started#time-parameters). The trick behind any comparison report is simply calling the same endpoint twice with two adjacent date ranges.
+Every analytics endpoint takes the same [time parameters](/docs/api/getting-started#time-parameters). The trick behind any comparison report is calling the same endpoint twice with two adjacent date ranges of the same length.
</Callout>
+`start_date` and `end_date` are both inclusive, and they are days in `time_zone`. So `start_date` 7 days ago with `end_date` today covers 8 days (7 full days plus today so far), which would inflate every change against a 7-day prior week. The scripts below end both ranges on complete days and work out the dates in the report's timezone.
+
## The workflow
<Steps>
<Step>
-**Fetch this week's overview** for the last 7 days.
+**Fetch this week's overview** for the last 7 complete days (yesterday and the six days before it).
</Step>
<Step>
-**Fetch last week's overview** for the 7 days before that, so you can compute the change.
+**Fetch last week's overview** for the 7 days before that, so you can compute the change on equal-length periods.
</Step>
<Step>
**Fetch top pages and top sources** from the `metric` endpoint to add context.
@@ -48,8 +50,15 @@ const API_KEY = process.env.RYBBIT_API_KEY;
const SLACK_WEBHOOK = process.env.SLACK_WEBHOOK;
const TZ = 'America/New_York';
-// Helper: format a Date as YYYY-MM-DD
-const ymd = (d) => d.toISOString().slice(0, 10);
+// Today's date in the report's timezone, as YYYY-MM-DD
+const today = new Intl.DateTimeFormat('en-CA', { timeZone: TZ }).format(new Date());
+
+// Shift a YYYY-MM-DD date by n days
+function addDays(date, n) {
+ const d = new Date(`${date}T00:00:00Z`);
+ d.setUTCDate(d.getUTCDate() + n);
+ return d.toISOString().slice(0, 10);
+}
async function get(path, params) {
const url = new URL(`${API}/api/sites/${SITE}${path}`);
@@ -63,8 +72,8 @@ async function get(path, params) {
async function overview(start, end) {
const { data } = await get('/overview', {
- start_date: ymd(start),
- end_date: ymd(end),
+ start_date: start,
+ end_date: end,
time_zone: TZ,
});
return data;
@@ -73,8 +82,8 @@ async function overview(start, end) {
async function topMetric(parameter, start, end, limit = 5) {
const { data } = await get('/metric', {
parameter,
- start_date: ymd(start),
- end_date: ymd(end),
+ start_date: start,
+ end_date: end,
time_zone: TZ,
limit,
});
@@ -87,16 +96,17 @@ function pctChange(current, previous) {
}
async function buildReport() {
- const now = new Date();
- const thisWeekStart = new Date(now); thisWeekStart.setDate(now.getDate() - 7);
- const lastWeekEnd = new Date(now); lastWeekEnd.setDate(now.getDate() - 8);
- const lastWeekStart = new Date(now); lastWeekStart.setDate(now.getDate() - 14);
+ // Two 7-day ranges of complete days; end_date is inclusive
+ const thisWeekEnd = addDays(today, -1);
+ const thisWeekStart = addDays(today, -7);
+ const lastWeekEnd = addDays(today, -8);
+ const lastWeekStart = addDays(today, -14);
const [thisWeek, lastWeek, topPages, topSources] = await Promise.all([
- overview(thisWeekStart, now),
+ overview(thisWeekStart, thisWeekEnd),
overview(lastWeekStart, lastWeekEnd),
- topMetric('pathname', thisWeekStart, now),
- topMetric('referrer', thisWeekStart, now),
+ topMetric('pathname', thisWeekStart, thisWeekEnd),
+ topMetric('referrer', thisWeekStart, thisWeekEnd),
]);
return {
@@ -122,13 +132,14 @@ async function postToSlack(r) {
`β€’ Sessions: *${r.sessions.value.toLocaleString()}*${arrow(r.sessions.change)}`,
`β€’ Unique users: *${r.users.value.toLocaleString()}*${arrow(r.users.change)}`,
`β€’ Pageviews: *${r.pageviews.value.toLocaleString()}*${arrow(r.pageviews.change)}`,
- `β€’ Bounce rate: *${r.bounceRate.toFixed(1)}%*`,
+ // bounce_rate is null when there were no sessions
+ `β€’ Bounce rate: *${r.bounceRate == null ? 'n/a' : `${r.bounceRate.toFixed(1)}%`}*`,
``,
`*Top pages*`,
...r.topPages.map((p) => ` ${p.value} β€” ${p.count.toLocaleString()}`),
``,
`*Top sources*`,
- ...r.topSources.map((s) => ` ${s.value || 'Direct'} β€” ${s.count.toLocaleString()}`),
+ ...r.topSources.map((s) => ` ${s.value} β€” ${s.count.toLocaleString()}`),
];
await fetch(SLACK_WEBHOOK, {
method: 'POST',
@@ -143,7 +154,8 @@ buildReport().then(postToSlack).catch(console.error);
<Tab value="Python">
```python title="weekly_report.py"
import os
-from datetime import datetime, timedelta
+from datetime import date, datetime, timedelta
+from zoneinfo import ZoneInfo
import requests
API = "https://app.rybbit.io"
@@ -156,8 +168,8 @@ session = requests.Session()
session.headers["Authorization"] = f"Bearer {API_KEY}"
-def ymd(d: datetime) -> str:
- return d.strftime("%Y-%m-%d")
+def ymd(d: date) -> str:
+ return d.isoformat()
def get(path: str, **params):
@@ -181,12 +193,14 @@ def pct_change(current, previous):
def build_report():
- now = datetime.utcnow()
- this_start = now - timedelta(days=7)
- last_end = now - timedelta(days=8)
- last_start = now - timedelta(days=14)
-
- this_week = overview(this_start, now)
+ # Two 7-day ranges of complete days in the report's timezone; end_date is inclusive
+ today = datetime.now(ZoneInfo(TZ)).date()
+ this_end = today - timedelta(days=1)
+ this_start = today - timedelta(days=7)
+ last_end = today - timedelta(days=8)
+ last_start = today - timedelta(days=14)
+
+ this_week = overview(this_start, this_end)
last_week = overview(last_start, last_end)
return {
@@ -194,8 +208,8 @@ def build_report():
"users": (this_week["users"], pct_change(this_week["users"], last_week["users"])),
"pageviews": (this_week["pageviews"], pct_change(this_week["pageviews"], last_week["pageviews"])),
"bounce_rate": this_week["bounce_rate"],
- "top_pages": top_metric("pathname", this_start, now),
- "top_sources": top_metric("referrer", this_start, now),
+ "top_pages": top_metric("pathname", this_start, this_end),
+ "top_sources": top_metric("referrer", this_start, this_end),
}
@@ -206,16 +220,18 @@ def arrow(change):
def post_to_slack(r):
+ # bounce_rate is None when there were no sessions
+ bounce = "n/a" if r["bounce_rate"] is None else f"{r['bounce_rate']:.1f}%"
lines = [
"*πŸ“Š Weekly Analytics Report*", "",
f"β€’ Sessions: *{r['sessions'][0]:,}*{arrow(r['sessions'][1])}",
f"β€’ Unique users: *{r['users'][0]:,}*{arrow(r['users'][1])}",
f"β€’ Pageviews: *{r['pageviews'][0]:,}*{arrow(r['pageviews'][1])}",
- f"β€’ Bounce rate: *{r['bounce_rate']:.1f}%*", "",
+ f"β€’ Bounce rate: *{bounce}*", "",
"*Top pages*",
*[f" {p['value']} β€” {p['count']:,}" for p in r["top_pages"]], "",
"*Top sources*",
- *[f" {s['value'] or 'Direct'} β€” {s['count']:,}" for s in r["top_sources"]],
+ *[f" {s['value']} β€” {s['count']:,}" for s in r["top_sources"]],
]
requests.post(SLACK_WEBHOOK, json={"text": "\n".join(lines)})
@@ -242,10 +258,12 @@ Top pages
Top sources
google.com β€” 6,410
- Direct β€” 4,220
twitter.com β€” 1,180
+ news.ycombinator.com β€” 640
```
+`referrer` lists only sessions that arrived with a referrer; direct visits have an empty referrer and are left out of the metric. To show direct traffic, use `topMetric('channel', ...)`, which includes a `Direct` row.
+
## Schedule it
Run the script every Monday morning with cron:
@@ -256,10 +274,10 @@ Run the script every Monday morning with cron:
```
<Callout type="info">
-**Want a richer report?** The same pattern extends naturally. Add `topMetric('channel', ...)` for marketing channels, `topMetric('country', ...)` for geography, or call the [`time-series` endpoint](/docs/api/overview/time-series) with `bucket=day` to attach a 7-point trend line.
+**Want a richer report?** The same pattern extends naturally. Add `topMetric('channel', ...)` for marketing channels, `topMetric('country', ...)` for geography, or call the [`time-series` endpoint](/docs/api/overview/time-series) with `bucket=day` to attach a 7-point trend line (use the same `start_date` and `end_date`).
</Callout>
## Next steps
- [Compare Marketing Channel Performance](/docs/api/channel-performance) β€” go beyond traffic counts and rank sources by how well they convert.
-- [Export Raw Events to Your Warehouse](/docs/api/export-events) β€” if you'd rather build reports in your own BI tool.
+- [Events API reference](/docs/api/events/list) β€” page through raw events if you'd rather build reports in your own BI tool.