Skip to content

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

Add API key management functionality (#690)

Bill Yang3a7df2111b93
diff --git a/client/src/api/admin/apiKey.ts b/client/src/api/admin/apiKey.ts
deleted file mode 100644
index d2413786f..000000000
--- a/client/src/api/admin/apiKey.ts
+++ /dev/null
@@ -1,75 +0,0 @@
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { authedFetch } from "../utils";
-
-interface ApiConfigResponse {
- apiKey: string | null;
-}
-
-interface UpdateApiConfigResponse {
- apiKey: string | null;
-}
-
-// Get API config
-export const useGetApiConfig = (siteId: number) => {
- return useQuery({
- queryKey: ["apiConfig", siteId],
- queryFn: async () => {
- const response = await authedFetch<{
- success: boolean;
- data: ApiConfigResponse;
- }>(`/site/${siteId}/api-config`);
- return response.data;
- },
- enabled: !!siteId,
- });
-};
-
-// Generate API key
-export const useGenerateApiKey = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (siteId: number) => {
- const response = await authedFetch<{
- success: boolean;
- data: UpdateApiConfigResponse;
- }>(
- `/site/${siteId}/api-config`,
- {},
- {
- method: "POST",
- data: { action: "generate_api_key" },
- }
- );
- return response.data;
- },
- onSuccess: (_, siteId) => {
- queryClient.invalidateQueries({ queryKey: ["apiConfig", siteId] });
- },
- });
-};
-
-// Revoke API key
-export const useRevokeApiKey = () => {
- const queryClient = useQueryClient();
-
- return useMutation({
- mutationFn: async (siteId: number) => {
- const response = await authedFetch<{
- success: boolean;
- data: UpdateApiConfigResponse;
- }>(
- `/site/${siteId}/api-config`,
- {},
- {
- method: "POST",
- data: { action: "revoke_api_key" },
- }
- );
- return response.data;
- },
- onSuccess: (_, siteId) => {
- queryClient.invalidateQueries({ queryKey: ["apiConfig", siteId] });
- },
- });
-};
diff --git a/client/src/api/admin/userApiKeys.ts b/client/src/api/admin/userApiKeys.ts
new file mode 100644
index 000000000..fb4a5f7f1
--- /dev/null
+++ b/client/src/api/admin/userApiKeys.ts
@@ -0,0 +1,86 @@
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { authedFetch } from "../utils";
+
+// TypeScript interfaces for API keys
+export interface ApiKey {
+ id: string;
+ name: string | null;
+ start: string | null;
+ prefix: string | null;
+ userId: string;
+ enabled: boolean;
+ rateLimitEnabled: boolean;
+ rateLimitTimeWindow: number | null;
+ rateLimitMax: number | null;
+ requestCount: number;
+ remaining: number | null;
+ lastRequest: string | null;
+ expiresAt: string | null;
+ createdAt: string;
+ updatedAt: string;
+}
+
+export interface ApiKeyWithKey extends ApiKey {
+ key: string; // The full API key, only returned on creation
+}
+
+export interface CreateApiKeyRequest {
+ name: string;
+ expiresIn?: number;
+}
+
+// List all API keys for the current user
+export const useListApiKeys = () => {
+ return useQuery<ApiKey[]>({
+ queryKey: ["userApiKeys"],
+ queryFn: async () => {
+ const response = await authedFetch<ApiKey[]>("/user/api-keys");
+ return response;
+ },
+ });
+};
+
+// Create a new API key
+export const useCreateApiKey = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation<ApiKeyWithKey, Error, CreateApiKeyRequest>({
+ mutationFn: async (data) => {
+ try {
+ const response = await authedFetch<ApiKeyWithKey>("/user/api-keys", undefined, {
+ method: "POST",
+ data,
+ });
+ return response;
+ } catch (error) {
+ throw new Error(error instanceof Error ? error.message : "Failed to create API key");
+ }
+ },
+ onSuccess: () => {
+ // Invalidate the list to refresh
+ queryClient.invalidateQueries({ queryKey: ["userApiKeys"] });
+ },
+ });
+};
+
+// Delete an API key
+export const useDeleteApiKey = () => {
+ const queryClient = useQueryClient();
+
+ return useMutation<{ success: boolean }, Error, string>({
+ mutationFn: async (keyId) => {
+ try {
+ const response = await authedFetch<{ success: boolean }>(`/user/api-keys/${keyId}`, undefined, {
+ method: "DELETE",
+ });
+ return response;
+ } catch (error) {
+ throw new Error(error instanceof Error ? error.message : "Failed to delete API key");
+ }
+ },
+ onSuccess: () => {
+ // Invalidate the list to refresh
+ queryClient.invalidateQueries({ queryKey: ["userApiKeys"] });
+ },
+ });
+};
diff --git a/client/src/app/settings/account/components/AccountInner.tsx b/client/src/app/settings/account/components/AccountInner.tsx
index bab262301..9e5e86559 100644
--- a/client/src/app/settings/account/components/AccountInner.tsx
+++ b/client/src/app/settings/account/components/AccountInner.tsx
@@ -14,6 +14,7 @@ import { useQueryClient } from "@tanstack/react-query";
import { Switch } from "../../../../components/ui/switch";
import { useUpdateAccountSettings } from "../../../../api/admin/accountSettings";
import { IS_CLOUD } from "../../../../lib/const";
+import { ApiKeyManager } from "./ApiKeyManager";
export function AccountInner() {
const session = authClient.useSession();
@@ -193,6 +194,8 @@ export function AccountInner() {
</div>
</CardContent>
</Card>
+
+ {IS_CLOUD && <ApiKeyManager />}
</div>
);
}
diff --git a/client/src/app/settings/account/components/ApiKeyManager.tsx b/client/src/app/settings/account/components/ApiKeyManager.tsx
new file mode 100644
index 000000000..d87b5ce07
--- /dev/null
+++ b/client/src/app/settings/account/components/ApiKeyManager.tsx
@@ -0,0 +1,184 @@
+"use client";
+
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "../../../../components/ui/button";
+import { Card, CardContent, CardHeader, CardTitle } from "../../../../components/ui/card";
+import { Input } from "../../../../components/ui/input";
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from "../../../../components/ui/dialog";
+import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "../../../../components/ui/table";
+import { Label } from "../../../../components/ui/label";
+import { DateTime } from "luxon";
+import { useListApiKeys, useCreateApiKey, useDeleteApiKey } from "../../../../api/admin/userApiKeys";
+
+export function ApiKeyManager() {
+ const [apiKeyName, setApiKeyName] = useState("");
+ const [showApiKeyDialog, setShowApiKeyDialog] = useState(false);
+ const [createdApiKey, setCreatedApiKey] = useState<string | null>(null);
+
+ const { data: apiKeys, isLoading: isLoadingApiKeys, isError, error, refetch } = useListApiKeys();
+ const createApiKey = useCreateApiKey();
+ const deleteApiKey = useDeleteApiKey();
+
+ const handleCreateApiKey = async () => {
+ if (!apiKeyName.trim()) {
+ toast.error("Please enter a name for the API key");
+ return;
+ }
+
+ try {
+ const result = await createApiKey.mutateAsync({ name: apiKeyName });
+ setCreatedApiKey(result.key);
+ setShowApiKeyDialog(true);
+ setApiKeyName("");
+ toast.success("API key created successfully");
+ } catch (error) {
+ console.error("Error creating API key:", error);
+ toast.error(error instanceof Error ? error.message : "Failed to create API key");
+ }
+ };
+
+ const handleDeleteApiKey = async (keyId: string, keyName: string | null) => {
+ if (!confirm(`Are you sure you want to delete the API key "${keyName || "Unnamed"}"?`)) {
+ return;
+ }
+
+ try {
+ await deleteApiKey.mutateAsync(keyId);
+ toast.success("API key deleted successfully");
+ } catch (error) {
+ console.error("Error deleting API key:", error);
+ toast.error(error instanceof Error ? error.message : "Failed to delete API key");
+ }
+ };
+
+ const copyToClipboard = (text: string) => {
+ navigator.clipboard.writeText(text);
+ toast.success("Copied to clipboard");
+ };
+
+ return (
+ <>
+ <Card className="p-2">
+ <CardHeader>
+ <CardTitle className="text-xl">API Keys</CardTitle>
+ </CardHeader>
+ <CardContent className="space-y-6">
+ <div className="space-y-2">
+ <h4 className="text-sm font-medium">Create API Key</h4>
+ <p className="text-xs text-neutral-500">
+ Generate API keys to access analytics endpoints from your applications
+ </p>
+ <div className="flex space-x-2">
+ <Input
+ id="apiKeyName"
+ value={apiKeyName}
+ onChange={({ target }) => setApiKeyName(target.value)}
+ placeholder="API Key Name"
+ onKeyDown={e => {
+ if (e.key === "Enter") {
+ e.preventDefault();
+ handleCreateApiKey();
+ }
+ }}
+ />
+ <Button
+ variant="outline"
+ onClick={handleCreateApiKey}
+ disabled={createApiKey.isPending || !apiKeyName.trim()}
+ >
+ {createApiKey.isPending ? "Creating..." : "Create"}
+ </Button>
+ </div>
+ </div>
+
+ <div className="space-y-2">
+ <h4 className="text-sm font-medium">Your API Keys</h4>
+ {isLoadingApiKeys ? (
+ <p className="text-xs text-neutral-500">Loading API keys...</p>
+ ) : isError ? (
+ <div className="space-y-2">
+ <p className="text-xs text-red-500">
+ Failed to load API keys{error?.message ? `: ${error.message}` : ""}
+ </p>
+ <Button variant="outline" size="sm" onClick={() => refetch()}>
+ Retry
+ </Button>
+ </div>
+ ) : apiKeys && apiKeys.length > 0 ? (
+ <div className=" rounded-lg">
+ <Table>
+ <TableHeader>
+ <TableRow>
+ <TableHead>Name</TableHead>
+ <TableHead>Key</TableHead>
+ <TableHead>Created</TableHead>
+ <TableHead className="text-right">Actions</TableHead>
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {apiKeys.map(key => (
+ <TableRow key={key.id}>
+ <TableCell className="font-medium">{key.name || "Unnamed"}</TableCell>
+ <TableCell className="font-mono text-xs">{key.start || "****"}...</TableCell>
+ <TableCell>{DateTime.fromISO(key.createdAt).toLocaleString(DateTime.DATETIME_SHORT)}</TableCell>
+ <TableCell className="text-right">
+ <Button
+ variant="destructive"
+ size="sm"
+ onClick={() => handleDeleteApiKey(key.id, key.name)}
+ disabled={deleteApiKey.isPending}
+ >
+ Delete
+ </Button>
+ </TableCell>
+ </TableRow>
+ ))}
+ </TableBody>
+ </Table>
+ </div>
+ ) : (
+ <p className="text-xs text-neutral-500">No API keys created yet</p>
+ )}
+ </div>
+ </CardContent>
+ </Card>
+
+ <Dialog open={showApiKeyDialog} onOpenChange={setShowApiKeyDialog}>
+ <DialogContent className="max-w-md">
+ <DialogHeader>
+ <DialogTitle>API Key Created</DialogTitle>
+ <DialogDescription>Save this API key securely. You won&apos;t be able to see it again.</DialogDescription>
+ </DialogHeader>
+ <div className="space-y-4">
+ <div className="space-y-2">
+ <Label>Your API Key</Label>
+ <div className="flex space-x-2">
+ <Input value={createdApiKey || ""} readOnly className="font-mono text-xs" />
+ <Button variant="outline" onClick={() => createdApiKey && copyToClipboard(createdApiKey)}>
+ Copy
+ </Button>
+ </div>
+ </div>
+ <div className="rounded-lg bg-yellow-50 dark:bg-yellow-950 p-3 border border-yellow-200 dark:border-yellow-800">
+ <p className="text-xs text-yellow-800 dark:text-yellow-200">
+ <strong>Important:</strong> Store this key securely. It won&apos;t be displayed again.
+ </p>
+ </div>
+
+ <Button
+ className="w-full"
+ onClick={() => {
+ setShowApiKeyDialog(false);
+ setCreatedApiKey(null);
+ }}
+ variant="success"
+ >
+ Done
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ </>
+ );
+}
diff --git a/client/src/components/SiteSettings/ApiKeyManager.tsx b/client/src/components/SiteSettings/ApiKeyManager.tsx
deleted file mode 100644
index 5a0565263..000000000
--- a/client/src/components/SiteSettings/ApiKeyManager.tsx
+++ /dev/null
@@ -1,162 +0,0 @@
-"use client";
-
-import { Copy, Eye, EyeOff, Key } from "lucide-react";
-import { useState } from "react";
-import { toast } from "sonner";
-
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@/components/ui/alert-dialog";
-import { Button } from "@/components/ui/button";
-import { Input } from "@/components/ui/input";
-import { Skeleton } from "@/components/ui/skeleton";
-import Link from "next/link";
-
-import { useGenerateApiKey, useGetApiConfig, useRevokeApiKey } from "../../api/admin/apiKey";
-
-interface ApiKeyManagerProps {
- siteId: number;
- disabled?: boolean;
-}
-
-export function ApiKeyManager({ siteId, disabled = false }: ApiKeyManagerProps) {
- const [showApiKey, setShowApiKey] = useState(false);
-
- // API key hooks
- const { data: apiConfig, isLoading: isLoadingApiConfig } = useGetApiConfig(siteId);
- const generateApiKey = useGenerateApiKey();
- const revokeApiKey = useRevokeApiKey();
-
- // Use the API key from config or from newly generated key
- const apiKey = apiConfig?.apiKey || null;
-
- return (
- <div className="space-y-4">
- <div>
- <h4 className="text-sm font-semibold text-foreground">API Key</h4>
- <p className="text-xs text-muted-foreground mt-1">
- Generate an API key to track events from{" "}
- <Link
- href="https://rybbit.com/docs/local-tracking"
- target="_blank"
- className="text-indigo-300 hover:underline"
- >
- localhost
- </Link>
- , server-side applications, or mobile apps using the{" "}
- <Link href="https://rybbit.com/docs/api" target="_blank" className="text-indigo-300 hover:underline">
- API endpoint
- </Link>
- .
- </p>
- </div>
-
- {isLoadingApiConfig ? (
- <div className="flex space-x-2">
- <Skeleton className="h-9 w-32" />
- </div>
- ) : apiKey ? (
- <div className="space-y-4">
- <div className="flex items-center space-x-2">
- <div className="flex-1">
- <div className="relative">
- <Input
- type={showApiKey ? "text" : "password"}
- value={showApiKey && apiKey ? apiKey : "rb_••••••••••••••••••••••••••••••••••"}
- readOnly
- className="pr-20 font-mono text-xs"
- />
- <div className="absolute right-1 top-1 flex space-x-1">
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => setShowApiKey(!showApiKey)}
- className="h-7 px-2"
- >
- {showApiKey ? <EyeOff className="h-3 w-3" /> : <Eye className="h-3 w-3" />}
- </Button>
- {apiKey && (
- <Button
- type="button"
- variant="ghost"
- size="sm"
- onClick={() => {
- navigator.clipboard.writeText(apiKey);
- toast.success("API key copied to clipboard");
- }}
- className="h-7 px-2"
- >
- <Copy className="h-3 w-3" />
- </Button>
- )}
- </div>
- </div>
- </div>
- </div>
- <div className="space-y-4">
- <AlertDialog>
- <AlertDialogTrigger asChild>
- <Button variant="destructive" size="sm" disabled={disabled || revokeApiKey.isPending}>
- Revoke API Key
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Revoke API Key?</AlertDialogTitle>
- <AlertDialogDescription>
- This will immediately invalidate the current API key. Any applications using this key will stop
- working.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={async () => {
- try {
- await revokeApiKey.mutateAsync(siteId);
- setShowApiKey(false);
- toast.success("API key revoked successfully");
- } catch (error) {
- toast.error("Failed to revoke API key");
- }
- }}
- variant="destructive"
- >
- Revoke Key
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- </div>
- ) : (
- <Button
- onClick={async () => {
- try {
- const result = await generateApiKey.mutateAsync(siteId);
- if (result.apiKey) {
- setShowApiKey(true);
- toast.success("API key generated successfully");
- }
- } catch (error) {
- toast.error("Failed to generate API key");
- }
- }}
- disabled={disabled || generateApiKey.isPending}
- >
- <Key className="h-4 w-4 mr-2" />
- Generate API Key
- </Button>
- )}
- </div>
- );
-}
diff --git a/client/src/components/SiteSettings/SiteSettings.tsx b/client/src/components/SiteSettings/SiteSettings.tsx
index 8c7959a9b..95300edf5 100644
--- a/client/src/components/SiteSettings/SiteSettings.tsx
+++ b/client/src/components/SiteSettings/SiteSettings.tsx
@@ -18,7 +18,6 @@ import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { SiteResponse, useGetSite } from "@/api/admin/sites";
import { useUserOrganizations } from "../../api/admin/organizations";
-import { ApiKeyManager } from "./ApiKeyManager";
import { ScriptBuilder } from "./ScriptBuilder";
import { SiteConfiguration } from "./SiteConfiguration";
@@ -58,20 +57,15 @@ function SiteSettingsInner({ siteMetadata, trigger }: { siteMetadata: SiteRespon
<DialogDescription>Manage settings for {siteMetadata.domain}</DialogDescription>
</DialogHeader>
<Tabs value={activeTab} onValueChange={setActiveTab} className="pb-4">
- <TabsList className="grid w-full grid-cols-3">
+ <TabsList className="grid w-full grid-cols-2">
<TabsTrigger value="settings">Site Settings</TabsTrigger>
<TabsTrigger value="script">Tracking Script</TabsTrigger>
- <TabsTrigger value="apikey">API Key</TabsTrigger>
</TabsList>
<TabsContent value="script" className="pt-4 space-y-4 max-h-[70vh] overflow-y-auto">
<ScriptBuilder siteId={siteMetadata.id ?? String(siteMetadata.siteId)} />
</TabsContent>
- <TabsContent value="apikey" className="pt-4 space-y-4 max-h-[70vh] overflow-y-auto">
- <ApiKeyManager siteId={siteMetadata.siteId} disabled={disabled} />
- </TabsContent>
-
<TabsContent value="settings">
<SiteConfiguration siteMetadata={siteMetadata} disabled={disabled} onClose={() => setDialogOpen(false)} />
</TabsContent>
diff --git a/client/src/components/SiteSettings/index.ts b/client/src/components/SiteSettings/index.ts
index 6c3eaae41..cbd4e0e5c 100644
--- a/client/src/components/SiteSettings/index.ts
+++ b/client/src/components/SiteSettings/index.ts
@@ -1,4 +1,3 @@
export { SiteSettings } from "./SiteSettings";
export { ScriptBuilder } from "./ScriptBuilder";
-export { ApiKeyManager } from "./ApiKeyManager";
export { SiteConfiguration } from "./SiteConfiguration";
diff --git a/client/src/lib/auth.ts b/client/src/lib/auth.ts
index a7c142433..31f662cf5 100644
--- a/client/src/lib/auth.ts
+++ b/client/src/lib/auth.ts
@@ -1,9 +1,9 @@
-import { adminClient, organizationClient, emailOTPClient } from "better-auth/client/plugins";
+import { adminClient, organizationClient, emailOTPClient, apiKeyClient } from "better-auth/client/plugins";
import { createAuthClient } from "better-auth/react";
export const authClient = createAuthClient({
baseURL: process.env.NEXT_PUBLIC_BACKEND_URL,
- plugins: [adminClient(), organizationClient(), emailOTPClient()],
+ plugins: [adminClient(), organizationClient(), emailOTPClient(), apiKeyClient()],
fetchOptions: {
credentials: "include",
},
diff --git a/docs/content/docs/api/meta.json b/docs/content/docs/api/meta.json
new file mode 100644
index 000000000..01765b87c
--- /dev/null
+++ b/docs/content/docs/api/meta.json
@@ -0,0 +1,4 @@
+{
+ "title": "API",
+ "pages": ["sending-events", "stats-api"]
+}
diff --git a/docs/content/docs/api.mdx b/docs/content/docs/api/sending-events.mdx
similarity index 74%
rename from docs/content/docs/api.mdx
rename to docs/content/docs/api/sending-events.mdx
index 1cb1fac2b..01ea39b91 100644
--- a/docs/content/docs/api.mdx
+++ b/docs/content/docs/api/sending-events.mdx
@@ -1,18 +1,19 @@
---
-title: API
+title: Sending Events
description: Track events from server-side applications, mobile apps, or any platform using the HTTP API
---
import { Steps, Step } from 'fumadocs-ui/components/steps';
import { Callout } from 'fumadocs-ui/components/callout';
import { Tabs, Tab } from 'fumadocs-ui/components/tabs';
+import { TypeTable } from 'fumadocs-ui/components/type-table';
-Track events from server-side applications, mobile apps, or any platform using the HTTP API with authentication.
+Track events from server-side applications, mobile apps, or any platform using the HTTP API.
## Overview
-The `/api/track` endpoint accepts tracking requests with API key authentication, bypassing domain validation. This enables server-side tracking, mobile app analytics, and programmatic event collection.
+The `/api/track` endpoint accepts tracking requests for pageviews, custom events, and more. Using an API key is optional but recommended for server-side tracking as it bypasses bot detection and domain validation.
### Data Enrichment
@@ -23,13 +24,23 @@ The `/api/track` endpoint accepts tracking requests with API key authentication,
<Steps>
<Step>
-### Generate API Key
+### Generate API Key (Optional)
-In your site dashboard: Settings → API Key tab → Generate API Key
+API keys are recommended for server-side tracking to bypass bot detection.
+
+1. Navigate to **Settings → Account** in your Rybbit dashboard
+2. Scroll to the **API Keys** section
+3. Enter a name for your API key
+4. Click **Create**
+5. Copy the key immediately (it won't be shown again)
+
+<Callout type="info">
+API keys are user-scoped and grant access to all sites in your organization(s).
+</Callout>
</Step>
<Step>
-### Include in Requests
+### Send Tracking Requests
<Tabs items={['Pageview', 'Custom Event']}>
<Tab value="Pageview">
@@ -68,24 +79,262 @@ curl -X POST 'https://app.rybbit.io/api/track' \
## Parameters
-| Parameter | Type | Required | Description |
-| :-------- | :--- | :------- | :---------- |
-| `api_key` | string | **Required** | Your generated API key (starts with `rb_`) |
-| `site_id` | string | **Required** | Your site ID |
-| `type` | string | Optional | Event type: `pageview` or `custom_event` (defaults to `pageview`) |
-| `pathname` | string | Optional | Page path |
-| `hostname` | string | Optional | Domain name |
-| `page_title` | string | Optional | Page title (max 512 chars) |
-| `referrer` | string | Optional | Referrer URL (max 2048 chars) |
-| `user_id` | string | Optional | Custom user identifier (max 255 chars) |
-| `user_agent` | string | Optional | Custom user agent string (max 512 chars) - will be parsed for browser/OS/device info |
-| `ip_address` | string | Optional | Custom IP for geolocation - will be resolved to location data |
-| `querystring` | string | Optional | Query parameters |
-| `language` | string | Optional | Language code (e.g., "en") |
-| `screenWidth` | number | Optional | Screen width in logical pixels (density-independent pixels) |
-| `screenHeight` | number | Optional | Screen height in logical pixels (density-independent pixels) |
-| `event_name` | string | **Custom events only** | Event name (required for custom events, max 256 chars) |
-| `properties` | string | **Custom events only** | JSON string with event data (max 2048 chars) |
+All parameters are sent in the request body as JSON.
+
+<TypeTable
+ type={{
+ api_key: {
+ description: 'Your generated API key - bypasses bot detection',
+ type: 'string',
+ typeDescription: 'Starts with "rb_"',
+ required: false,
+ },
+ site_id: {
+ description: 'Your site ID',
+ type: 'string',
+ required: true,
+ },
+ type: {
+ description: 'Event type',
+ type: 'string',
+ typeDescription: '"pageview" | "custom_event" | "performance" | "outbound" | "error"',
+ default: 'pageview',
+ },
+ pathname: {
+ description: 'Page path',
+ type: 'string',
+ typeDescription: 'Max 2048 chars',
+ },
+ hostname: {
+ description: 'Domain name',
+ type: 'string',
+ typeDescription: 'Max 253 chars',
+ },
+ page_title: {
+ description: 'Page title',
+ type: 'string',
+ typeDescription: 'Max 512 chars',
+ },
+ referrer: {
+ description: 'Referrer URL',
+ type: 'string',
+ typeDescription: 'Max 2048 chars',
+ },
+ user_id: {
+ description: 'Custom user identifier',
+ type: 'string',
+ typeDescription: 'Max 255 chars',
+ },
+ user_agent: {
+ description: 'Custom user agent string - will be parsed for browser/OS/device info',
+ type: 'string',
+ typeDescription: 'Max 512 chars',
+ },
+ ip_address: {
+ description: 'Custom IP for geolocation - will be resolved to location data',
+ type: 'string',
+ typeDescription: 'Valid IPv4 or IPv6 address',
+ },
+ querystring: {
+ description: 'Query parameters',
+ type: 'string',
+ typeDescription: 'Max 2048 chars',
+ },
+ language: {
+ description: 'Language code',
+ type: 'string',
+ typeDescription: 'e.g., "en", "es", "fr"',
+ },
+ screenWidth: {
+ description: 'Screen width in logical pixels (density-independent pixels)',
+ type: 'number',
+ },
+ screenHeight: {
+ description: 'Screen height in logical pixels (density-independent pixels)',
+ type: 'number',
+ },
+ event_name: {
+ description: 'Event name (required for custom events)',
+ type: 'string',
+ typeDescription: 'Max 256 chars',
+ },
+ properties: {
+ description: 'JSON string with event data (for custom events, outbound, error)',
+ type: 'string',
+ typeDescription: 'Max 2048 chars (4096 for error events)',
+ },
+ }}
+/>
+
+### Event Types
+
+#### Pageview
+Standard page view tracking. Set `type: "pageview"` (default).
+
+#### Custom Event
+Track custom events with optional properties. Set `type: "custom_event"`.
+
+**Required fields:**
+<TypeTable
+ type={{
+ event_name: {
+ description: 'Name of the custom event',
+ type: 'string',
+ typeDescription: 'Max 256 chars',
+ required: true,
+ },
+ properties: {
+ description: 'Event data as JSON string',
+ type: 'string',
+ typeDescription: 'Valid JSON, max 2048 chars',
+ },
+ }}
+/>
+
+**Example:**
+```json
+{
+ "type": "custom_event",
+ "event_name": "purchase",
+ "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"
+}
+```
+
+#### Performance
+Track Core Web Vitals. Set `type: "performance"`.
+
+**Performance metrics:**
+<TypeTable
+ type={{
+ lcp: {
+ description: 'Largest Contentful Paint in milliseconds',
+ type: 'number',
+ typeDescription: 'nullable',
+ },
+ cls: {
+ description: 'Cumulative Layout Shift score',
+ type: 'number',
+ typeDescription: 'nullable, typically 0-1',
+ },
+ inp: {
+ description: 'Interaction to Next Paint in milliseconds',
+ type: 'number',
+ typeDescription: 'nullable',
+ },
+ fcp: {
+ description: 'First Contentful Paint in milliseconds',
+ type: 'number',
+ typeDescription: 'nullable',
+ },
+ ttfb: {
+ description: 'Time to First Byte in milliseconds',
+ type: 'number',
+ typeDescription: 'nullable',
+ },
+ }}
+/>
+
+**Example:**
+```json
+{
+ "type": "performance",
+ "lcp": 2500,
+ "cls": 0.1,
+ "inp": 200,
+ "fcp": 1800,
+ "ttfb": 600
+}
+```
+
+#### Outbound
+Track outbound link clicks. Set `type: "outbound"`.
+
+**Properties format:**
+<TypeTable
+ type={{
+ url: {
+ description: 'Destination URL',
+ type: 'string',
+ required: true,
+ },
+ text: {
+ description: 'Link text content',
+ type: 'string',
+ },
+ target: {
+ description: 'Link target attribute',
+ type: 'string',
+ typeDescription: 'e.g., "_blank", "_self"',
+ },
+ }}
+/>
+
+**Example:**
+```json
+{
+ "type": "outbound",
+ "properties": "{\"url\": \"https://example.com\", \"text\": \"Click here\", \"target\": \"_blank\"}"
+}
+```
+
+#### Error
+Track JavaScript errors. Set `type: "error"`.
+
+**Required fields:**
+<TypeTable
+ type={{
+ event_name: {
+ description: 'Error type',
+ type: 'string',
+ typeDescription: 'e.g., "TypeError", "ReferenceError"',
+ required: true,
+ },
+ properties: {
+ description: 'Error details as JSON string',
+ type: 'string',
+ typeDescription: 'Valid JSON, max 4096 chars',
+ required: true,
+ },
+ }}
+/>
+
+**Properties format:**
+<TypeTable
+ type={{
+ message: {
+ description: 'Error message',
+ type: 'string',
+ typeDescription: 'Max 500 chars',
+ required: true,
+ },
+ stack: {
+ description: 'Stack trace',
+ type: 'string',
+ typeDescription: 'Max 2000 chars',
+ },
+ fileName: {
+ description: 'File where error occurred',
+ type: 'string',
+ },
+ lineNumber: {
+ description: 'Line number',
+ type: 'number',
+ },
+ columnNumber: {
+ description: 'Column number',
+ type: 'number',
+ },
+ }}
+/>
+
+**Example:**
+```json
+{
+ "type": "error",
+ "event_name": "TypeError",
+ "properties": "{\"message\": \"Cannot read property\", \"stack\": \"...\", \"fileName\": \"app.js\", \"lineNumber\": 42}"
+}
+```
## Language Examples
@@ -104,7 +353,7 @@ const trackEvent = async (eventData) => {
...eventData
})
});
-
+
return response.json();
};
@@ -184,12 +433,12 @@ type TrackingEvent struct {
func trackEvent(event TrackingEvent) error {
event.APIKey = os.Getenv("RYBBIT_API_KEY")
event.SiteID = os.Getenv("RYBBIT_SITE_ID")
-
+
jsonData, err := json.Marshal(event)
if err != nil {
return err
}
-
+
resp, err := http.Post(
"https://app.rybbit.io/api/track",
"application/json",
@@ -199,7 +448,7 @@ func trackEvent(event TrackingEvent) error {
return err
}
defer resp.Body.Close()
-
+
return nil
}
@@ -210,7 +459,7 @@ func main() {
Pathname: "/api/users",
Hostname: "api.example.com",
})
-
+
// Track a custom event
trackEvent(TrackingEvent{
Type: "custom_event",
@@ -236,40 +485,40 @@ public class RybbitTracker {
private static final String API_URL = "https://app.rybbit.io/api/track";
private static final String API_KEY = System.getenv("RYBBIT_API_KEY");
private static final String SITE_ID = System.getenv("RYBBIT_SITE_ID");
-
+
private final HttpClient httpClient = HttpClient.newHttpClient();
private final ObjectMapper objectMapper = new ObjectMapper();
-
+
public void trackEvent(Map<String, Object> eventData) throws Exception {
eventData.put("api_key", API_KEY);
eventData.put("site_id", SITE_ID);
-
+
String json = objectMapper.writeValueAsString(eventData);
-
+
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(API_URL))
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
-
- HttpResponse<String> response = httpClient.send(request,
+
+ HttpResponse<String> response = httpClient.send(request,
HttpResponse.BodyHandlers.ofString());
-
+
if (response.statusCode() != 200) {
throw new Exception("Tracking failed: " + response.body());
}
}
-
+
public static void main(String[] args) throws Exception {
RybbitTracker tracker = new RybbitTracker();
-
+
// Track a pageview
Map<String, Object> pageview = new HashMap<>();
pageview.put("type", "pageview");
pageview.put("pathname", "/api/users");
pageview.put("hostname", "api.example.com");
tracker.trackEvent(pageview);
-
+
// Track a custom event
Map<String, Object> customEvent = new HashMap<>();
customEvent.put("type", "custom_event");
@@ -290,30 +539,30 @@ class RybbitTracker {
private $apiUrl = 'https://app.rybbit.io/api/track';
private $apiKey;
private $siteId;
-
+
public function __construct() {
$this->apiKey = getenv('RYBBIT_API_KEY');
$this->siteId = getenv('RYBBIT_SITE_ID');
}
-
+
public function trackEvent($eventData) {
$eventData['api_key'] = $this->apiKey;
$eventData['site_id'] = $this->siteId;
-
+
$ch = curl_init($this->apiUrl);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($eventData));
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
-
+
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
-
+
if ($httpCode !== 200) {
throw new Exception('Tracking failed: ' . $response);
}
-
+
return json_decode($response, true);
}
}
@@ -346,30 +595,30 @@ require 'uri'
class RybbitTracker
API_URL = 'https://app.rybbit.io/api/track'
-
+
def initialize
@api_key = ENV['RYBBIT_API_KEY']
@site_id = ENV['RYBBIT_SITE_ID']
end
-
+
def track_event(event_data)
event_data[:api_key] = @api_key
event_data[:site_id] = @site_id
-
+
uri = URI(API_URL)
http = Net::HTTP.new(uri.host, uri.port)
http.use_ssl = true
-
+
request = Net::HTTP::Post.new(uri.path)
request['Content-Type'] = 'application/json'
request.body = event_data.to_json
-
+
response = http.request(request)
-
+
unless response.code == '200'
raise "Tracking failed: #{response.body}"
end
-
+
JSON.parse(response.body)
end
end
@@ -409,35 +658,35 @@ public class RybbitTracker
private readonly string _apiKey;
private readonly string _siteId;
private const string ApiUrl = "https://app.rybbit.io/api/track";
-
+
public RybbitTracker()
{
_httpClient = new HttpClient();
_apiKey = Environment.GetEnvironmentVariable("RYBBIT_API_KEY");
_siteId = Environment.GetEnvironmentVariable("RYBBIT_SITE_ID");
}
-
+
public async Task TrackEventAsync(Dictionary<string, object> eventData)
{
eventData["api_key"] = _apiKey;
eventData["site_id"] = _siteId;
-
+
var json = JsonSerializer.Serialize(eventData);
var content = new StringContent(json, Encoding.UTF8, "application/json");
-
+
var response = await _httpClient.PostAsync(ApiUrl, content);
-
+
if (!response.IsSuccessStatusCode)
{
var error = await response.Content.ReadAsStringAsync();
throw new Exception($"Tracking failed: {error}");
}
}
-
+
static async Task Main(string[] args)
{
var tracker = new RybbitTracker();
-
+
// Track a pageview
await tracker.TrackEventAsync(new Dictionary<string, object>
{
@@ -445,7 +694,7 @@ public class RybbitTracker
["pathname"] = "/api/users",
["hostname"] = "api.example.com"
});
-
+
// Track a custom event
await tracker.TrackEventAsync(new Dictionary<string, object>
{
@@ -482,22 +731,22 @@ impl RybbitTracker {
api_url: "https://app.rybbit.io/api/track".to_string(),
}
}
-
+
async fn track_event(&self, mut event_data: Value) -> Result<(), Box<dyn std::error::Error>> {
event_data["api_key"] = json!(self.api_key);
event_data["site_id"] = json!(self.site_id);
-
+
let response = self.client
.post(&self.api_url)
.json(&event_data)
.send()
.await?;
-
+
if !response.status().is_success() {
let error_text = response.text().await?;
return Err(format!("Tracking failed: {}", error_text).into());
}
-
+
Ok(())
}
}
@@ -505,14 +754,14 @@ impl RybbitTracker {
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let tracker = RybbitTracker::new();
-
+
// Track a pageview
tracker.track_event(json!({
"type": "pageview",
"pathname": "/api/users",
"hostname": "api.example.com"
})).await?;
-
+
// Track a custom event
tracker.track_event(json!({
"type": "custom_event",
@@ -520,7 +769,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
"event_name": "purchase",
"properties": r#"{"amount": 99.99, "currency": "USD"}"#
})).await?;
-
+
Ok(())
}
```
@@ -533,11 +782,11 @@ import UIKit
class RybbitTracker {
static let shared = RybbitTracker()
-
+
private let apiUrl = "https://app.rybbit.io/api/track"
private let apiKey: String
private let siteId: String
-
+
init() {
// Ensure API key and site ID are available
guard let apiKey = ProcessInfo.processInfo.environment["RYBBIT_API_KEY"],
@@ -549,15 +798,15 @@ class RybbitTracker {
self.apiKey = apiKey
self.siteId = siteId
}
-
+
func trackEvent(_ eventData: [String: Any]) async throws {
var data = eventData
data["api_key"] = apiKey
data["site_id"] = siteId
-
+
// Add device info
data["user_agent"] = getUserAgent()
-
+
// Get screen dimensions in logical pixels (points)
if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene {
let bounds = windowScene.screen.bounds
@@ -569,22 +818,22 @@ class RybbitTracker {
data["screenWidth"] = Int(bounds.width)
data["screenHeight"] = Int(bounds.height)
}
-
+
data["language"] = Locale.current.languageCode ?? "en"
-
+
var request = URLRequest(url: URL(string: apiUrl)!)
request.httpMethod = "POST"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONSerialization.data(withJSONObject: data)
-
+
let (_, response) = try await URLSession.shared.data(for: request)
-
+
guard let httpResponse = response as? HTTPURLResponse,
httpResponse.statusCode == 200 else {
throw NSError(domain: "RybbitTracker", code: 1, userInfo: [NSLocalizedDescriptionKey: "Tracking failed"])
}
}
-
+
private func getUserAgent() -> String {
let appVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0"
let osVersion = UIDevice.current.systemVersion
@@ -602,7 +851,7 @@ Task {
"hostname": "api.example.com",
"page_title": "User API Endpoint"
])
-
+
// Track a custom event
try await RybbitTracker.shared.trackEvent([
"type": "custom_event",
@@ -630,39 +879,39 @@ class RybbitTracker(private val context: Context) {
private const val API_URL = "https://app.rybbit.io/api/track"
private val JSON = "application/json; charset=utf-8".toMediaType()
}
-
+
private val client = OkHttpClient()
private val apiKey = BuildConfig.RYBBIT_API_KEY // Set in build.gradle
private val siteId = BuildConfig.RYBBIT_SITE_ID
-
+
suspend fun trackEvent(eventData: Map<String, Any>) = withContext(Dispatchers.IO) {
val data = eventData.toMutableMap().apply {
put("api_key", apiKey)
put("site_id", siteId)
put("user_agent", getUserAgent())
-
+
// Get screen dimensions in logical pixels (density-independent pixels)
val displayMetrics = context.resources.displayMetrics
put("screenWidth", (displayMetrics.widthPixels / displayMetrics.density).toInt())
put("screenHeight", (displayMetrics.heightPixels / displayMetrics.density).toInt())
put("language", Locale.getDefault().language)
}
-
+
val json = JSONObject(data).toString()
val body = json.toRequestBody(JSON)
-
+
val request = Request.Builder()
.url(API_URL)
.post(body)
.build()
-
+
client.newCall(request).execute().use { response ->
if (!response.isSuccessful) {
throw Exception("Tracking failed: ${response.code}")
}
}
}
-
+
private fun getUserAgent(): String {
val appVersion = context.packageManager
.getPackageInfo(context.packageName, 0).versionName
@@ -673,10 +922,10 @@ class RybbitTracker(private val context: Context) {
// Usage
class MainActivity : AppCompatActivity() {
private val tracker = RybbitTracker(this)
-
+
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
-
+
lifecycleScope.launch {
// Track a pageview
tracker.trackEvent(mapOf(
@@ -685,7 +934,7 @@ class MainActivity : AppCompatActivity() {
"hostname" to "api.example.com",
"page_title" to "User API Endpoint"
))
-
+
// Track a custom event
tracker.trackEvent(mapOf(
"type" to "custom_event",
@@ -711,41 +960,41 @@ class RybbitTracker {
static final RybbitTracker _instance = RybbitTracker._internal();
factory RybbitTracker() => _instance;
RybbitTracker._internal();
-
+
static const String _apiUrl = 'https://app.rybbit.io/api/track';
static const String _apiKey = String.fromEnvironment('RYBBIT_API_KEY');
static const String _siteId = String.fromEnvironment('RYBBIT_SITE_ID');
-
+
final _deviceInfoPlugin = DeviceInfoPlugin();
-
+
Future<void> trackEvent(Map<String, dynamic> eventData) async {
final data = Map<String, dynamic>.from(eventData);
data['api_key'] = _apiKey;
data['site_id'] = _siteId;
-
+
// Add device info
data['user_agent'] = await _getUserAgent();
-
+
// Get screen dimensions in logical pixels (density-independent pixels)
final view = WidgetsBinding.instance.platformDispatcher.views.first;
data['screenWidth'] = (view.physicalSize.width / view.devicePixelRatio).round();
data['screenHeight'] = (view.physicalSize.height / view.devicePixelRatio).round();
data['language'] = Platform.localeName.split('_')[0];
-
+
final response = await http.post(
Uri.parse(_apiUrl),
headers: {'Content-Type': 'application/json'},
body: json.encode(data),
);
-
+
if (response.statusCode != 200) {
throw Exception('Tracking failed: ${response.statusCode}');
}
}
-
+
Future<String> _getUserAgent() async {
const appVersion = '1.0.0'; // Get from package_info_plus if needed
-
+
if (Platform.isAndroid) {
final androidInfo = await _deviceInfoPlugin.androidInfo;
return 'MyApp/$appVersion (Android ${androidInfo.version.release}; ${androidInfo.model})';
@@ -753,7 +1002,7 @@ class RybbitTracker {
final iosInfo = await _deviceInfoPlugin.iosInfo;
return 'MyApp/$appVersion (iOS ${iosInfo.systemVersion}; ${iosInfo.model})';
}
-
+
return 'MyApp/$appVersion (${Platform.operatingSystem})';
}
}
@@ -770,7 +1019,7 @@ class MyApp extends StatefulWidget {
class _MyAppState extends State<MyApp> {
final tracker = RybbitTracker();
-
+
@override
void initState() {
super.initState();
@@ -782,7 +1031,7 @@ class _MyAppState extends State<MyApp> {
'page_title': 'User API Endpoint',
});
}
-
+
@override
Widget build(BuildContext context) {
return MaterialApp(
@@ -822,7 +1071,7 @@ class _MyAppState extends State<MyApp> {
```json
{
"success": false,
- "error": "Invalid API key",
+ "error": "Invalid payload",
"details": {
"fieldErrors": {},
"formErrors": ["Custom events require event_name"]
@@ -832,111 +1081,43 @@ class _MyAppState extends State<MyApp> {
## Rate Limiting
-API key authenticated requests are rate limited to **20 requests per second per API key** on Rybbit Cloud. Self-hosted instances have no rate limits.
-
-When you exceed the rate limit, you'll receive a `429` status code:
+API keys have built-in rate limiting:
+- **500 requests per 10 minutes** per API key
+- When exceeded, you'll receive a `429` status code
```json
{
"success": false,
- "error": "Rate limit exceeded. Maximum 20 requests per second per API key."
-}
-```
-
-## Configuration Endpoints
-
-### Get Excluded IPs
-
-Retrieve the list of excluded IP addresses for a site.
-
-```bash
-GET /api/site/:siteId/excluded-ips
-Authorization: Bearer <your-token>
-```
-
-**Response:**
-```json
-{
- "success": true,
- "excludedIPs": ["192.168.1.0/24", "10.0.0.1"]
+ "error": "Rate limit exceeded. Maximum 500 requests per 10 minutes per API key."
}
```
-### Get Excluded Countries
-
-Retrieve the list of excluded countries for a site.
-
-```bash
-GET /api/site/:siteId/excluded-countries
-Authorization: Bearer <your-token>
-```
-
-**Response:**
-```json
-{
- "success": true,
- "excludedCountries": ["US", "GB", "CN"]
-}
-```
-
-### Update Site Configuration
-
-Update site configuration including IP and country exclusions.
-
-```bash
-POST /api/site/:siteId/config
-Authorization: Bearer <your-token>
-Content-Type: application/json
-
-{
- "excludedIPs": ["192.168.1.0/24", "10.0.0.1"],
- "excludedCountries": ["US", "GB"],
- "blockBots": true,
- "sessionReplay": false
-}
-```
-
-**Request Parameters:**
-- `excludedIPs` (string[]): List of IP addresses/ranges to exclude (max 100)
-- `excludedCountries` (string[]): List of 2-letter ISO country codes to exclude (max 250)
-- `blockBots` (boolean): Enable/disable bot traffic blocking
-- `sessionReplay` (boolean): Enable/disable session replay
-- Other site configuration options (see [Site Settings](/docs/site-settings))
-
-**Response:**
-```json
-{
- "success": true,
- "message": "Site configuration updated successfully",
- "config": {
- "excludedIPs": ["192.168.1.0/24"],
- "excludedCountries": ["US", "GB"],
- "blockBots": true
- }
-}
-```
-
-**Country Code Validation:**
-- Must be uppercase 2-letter ISO 3166-1 alpha-2 codes (e.g., `US`, `GB`, `CN`)
-- Invalid codes will return a 400 error with validation details
-
-See the [Filter Traffic](/docs/filter-traffic) documentation for more details on traffic filtering.
-
## Best Practices
<Callout type="info">
**Environment Variables**: Store your API key and site ID as environment variables to keep them secure.
</Callout>
-<Callout type="error">
-**API Key Security**: Never expose API keys in client-side code or public repositories.
+<Callout type="warn">
+**API Key Security**: Never expose API keys in client-side code or public repositories. Use them only for server-side tracking.
+</Callout>
+
+<Callout type="info">
+**Browser Tracking**: For standard browser-based tracking, use the [Rybbit Web SDK](/docs/sdks/web) instead. The HTTP API is designed for server-side applications, mobile apps, and custom integrations.
+</Callout>
+
+<Callout type="info">
+**Organization Access**: API keys are user-scoped and grant access to all sites in your organization(s). Ensure the API key owner is a member of the organization that owns the site you're tracking.
</Callout>
## Error Handling
Common error scenarios:
-- **Invalid API key**: Check that your API key starts with `rb_` and hasn't been revoked
-- **Site not found**: Verify your site ID is correct
- **Invalid payload**: Ensure required fields are present and data types match
+- **Site not found**: Verify your site ID is correct
+- **Invalid API key**: Check that your API key is valid and hasn't expired
+- **Access denied**: Ensure the API key owner is a member of the site's organization
+- **Rate limit exceeded**: Reduce request frequency or implement request queuing
- **JSON parsing errors**: For custom events, ensure properties field contains valid JSON
-- **Rate limit exceeded**: Reduce request frequency or implement request queuing with delays
\ No newline at end of file
+- **Bot detected**: Use an API key to bypass bot detection for server-side tracking
+- **Over monthly limit**: Your site has exceeded its monthly pageview limit
diff --git a/docs/content/docs/api/stats-api.mdx b/docs/content/docs/api/stats-api.mdx
new file mode 100644
index 000000000..6f7d836e3
--- /dev/null
+++ b/docs/content/docs/api/stats-api.mdx
@@ -0,0 +1,561 @@
+---
+title: Stats API
+description: Retrieve analytics data programmatically with the Rybbit Stats API
+---
+
+import { TypeTable } from 'fumadocs-ui/components/type-table';
+
+The Rybbit API allows you to programmatically access your analytics data. All analytics endpoints are read-only and require authentication via API keys.
+
+## Authentication
+
+All API requests must include authentication using one of the following methods:
+
+### Bearer Token (Recommended)
+
+```bash
+Authorization: Bearer your_api_key_here
+```
+
+### Query Parameter (Testing Only)
+
+```bash
+?api_key=your_api_key_here
+```
+
+<Callout type="warn">
+Query parameters expose API keys in server logs and browser history. Use only for quick testing.
+</Callout>
+
+## Generating API Keys
+
+API keys are user-scoped and grant organization-level access:
+
+1. Navigate to **Settings → Account** in your Rybbit dashboard
+2. Scroll to the **API Keys** section
+3. Enter a name for your API key
+4. Click **Create**
+5. Copy the key immediately (it won't be shown again)
+
+### Rate Limits
+
+- **500 requests per 10 minutes** per API key
+- Keys are tied to your user account and grant access to all sites in your organization(s)
+
+## Common Parameters
+
+The following parameters are shared across all analytics endpoints.
+
+### Time Parameters
+
+All endpoints require either date-based or relative time parameters:
+
+<TypeTable
+ type={{
+ start_date: {
+ description: 'Start date for the query period',
+ type: 'string',
+ typeDescription: 'Format: YYYY-MM-DD (e.g., "2024-01-15")',
+ required: false,
+ },
+ end_date: {
+ description: 'End date for the query period',
+ type: 'string',
+ typeDescription: 'Format: YYYY-MM-DD (e.g., "2024-01-31")',
+ required: false,
+ },
+ time_zone: {
+ description: 'IANA timezone identifier',
+ type: 'string',
+ typeDescription: 'e.g., "America/New_York", "Europe/London", "Asia/Tokyo"',
+ required: false,
+ },
+ past_minutes_start: {
+ description: 'Start of relative time range (older boundary)',
+ type: 'number',
+ typeDescription: 'Minutes ago from now. Must be greater than past_minutes_end.',
+ required: false,
+ },
+ past_minutes_end: {
+ description: 'End of relative time range (newer boundary)',
+ type: 'number',
+ typeDescription: 'Minutes ago from now. Must be less than past_minutes_start.',
+ required: false,
+ },
+ }}
+/>
+
+**Note:** You must provide either:
+- All three date parameters (`start_date`, `end_date`, `time_zone`), OR
+- Both relative parameters (`past_minutes_start`, `past_minutes_end`)
+
+#### Examples
+
+**Date-based query (last 30 days):**
+```
+?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York
+```
+
+**Relative query (last 60 minutes):**
+```
+?past_minutes_start=60&past_minutes_end=0
+```
+
+### Filter Parameters
+
+The `filters` parameter accepts a JSON-encoded array of filter objects to narrow down your data.
+
+#### Filter Object Structure
+
+<TypeTable
+ type={{
+ parameter: {
+ description: 'The dimension to filter on',
+ type: 'FilterParameter',
+ typeDescription: 'See Filter Parameters table below',
+ required: true,
+ },
+ type: {
+ description: 'The type of comparison to perform',
+ type: 'FilterType',
+ typeDescription: '"equals" | "not_equals" | "contains" | "not_contains"',
+ required: true,
+ },
+ value: {
+ description: 'Array of values to match against',
+ type: 'Array<string | number>',
+ typeDescription: 'Multiple values are treated as OR conditions',
+ required: true,
+ },
+ }}
+/>
+
+#### Available Filter Parameters
+
+<TypeTable
+ type={{
+ browser: {
+ description: 'Browser name',
+ type: 'string',
+ typeDescription: 'e.g., "Chrome", "Firefox", "Safari"',
+ },
+ operating_system: {
+ description: 'Operating system name',
+ type: 'string',
+ typeDescription: 'e.g., "Windows", "macOS", "Linux"',
+ },
+ language: {
+ description: 'Browser language',
+ type: 'string',
+ typeDescription: 'e.g., "en-US", "es-ES"',
+ },
+ country: {
+ description: 'Country code',
+ type: 'string',
+ typeDescription: 'ISO 3166-1 alpha-2 code, e.g., "US", "GB"',
+ },
+ region: {
+ description: 'Geographic region',
+ type: 'string',
+ },
+ city: {
+ description: 'City name',
+ type: 'string',
+ },
+ device_type: {
+ description: 'Device category',
+ type: 'string',
+ typeDescription: '"desktop", "mobile", "tablet"',
+ },
+ referrer: {
+ description: 'HTTP referrer URL',
+ type: 'string',
+ },
+ hostname: {
+ description: 'Website hostname',
+ type: 'string',
+ typeDescription: 'e.g., "example.com"',
+ },
+ pathname: {
+ description: 'URL pathname',
+ type: 'string',
+ typeDescription: 'e.g., "/blog/post-title"',
+ },
+ page_title: {
+ description: 'HTML page title',
+ type: 'string',
+ },
+ querystring: {
+ description: 'URL query string',
+ type: 'string',
+ typeDescription: 'e.g., "?ref=twitter"',
+ },
+ event_name: {
+ description: 'Custom event name',
+ type: 'string',
+ },
+ channel: {
+ description: 'Marketing channel',
+ type: 'string',
+ typeDescription: 'e.g., "Direct", "Organic Search", "Social"',
+ },
+ utm_source: {
+ description: 'UTM source parameter',
+ type: 'string',
+ },
+ utm_medium: {
+ description: 'UTM medium parameter',
+ type: 'string',
+ },
+ utm_campaign: {
+ description: 'UTM campaign parameter',
+ type: 'string',
+ },
+ utm_term: {
+ description: 'UTM term parameter',
+ type: 'string',
+ },
+ utm_content: {
+ description: 'UTM content parameter',
+ type: 'string',
+ },
+ entry_page: {
+ description: 'First page in session',
+ type: 'string',
+ },
+ exit_page: {
+ description: 'Last page in session',
+ type: 'string',
+ },
+ user_id: {
+ description: 'Custom user identifier',
+ type: 'string',
+ },
+ browser_version: {
+ description: 'Browser version',
+ type: 'string',
+ },
+ operating_system_version: {
+ description: 'OS version',
+ type: 'string',
+ },
+ }}
+/>
+
+#### Filter Examples
+
+**Single filter:**
+```json
+[
+ {
+ "parameter": "country",
+ "type": "equals",
+ "value": ["US"]
+ }
+]
+```
+
+**Multiple filters (AND logic):**
+```json
+[
+ {
+ "parameter": "country",
+ "type": "equals",
+ "value": ["US", "CA"]
+ },
+ {
+ "parameter": "device_type",
+ "type": "equals",
+ "value": ["mobile"]
+ }
+]
+```
+
+**URL-encoded:**
+```
+?filters=%5B%7B%22parameter%22%3A%22country%22%2C%22type%22%3A%22equals%22%2C%22value%22%3A%5B%22US%22%5D%7D%5D
+```
+
+---
+
+## Endpoints
+
+### Get Overview
+
+```
+GET /api/overview/:site
+```
+
+Returns high-level analytics metrics for a site.
+
+#### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: 'Site ID or site identifier',
+ type: 'string | number',
+ required: true,
+ },
+ }}
+/>
+
+#### Query Parameters
+
+Accepts all [Common Parameters](#common-parameters) (time and filters).
+
+#### Response
+
+<TypeTable
+ type={{
+ sessions: {
+ description: 'Total number of sessions',
+ type: 'number',
+ },
+ pageviews: {
+ description: 'Total number of pageviews',
+ type: 'number',
+ },
+ users: {
+ description: 'Total unique users',
+ type: 'number',
+ },
+ pages_per_session: {
+ description: 'Average pages viewed per session',
+ type: 'number',
+ },
+ bounce_rate: {
+ description: 'Percentage of single-page sessions',
+ type: 'number',
+ typeDescription: 'Range: 0-100',
+ },
+ session_duration: {
+ description: 'Average session duration in seconds',
+ type: 'number',
+ },
+ }}
+/>
+
+#### Example Request
+
+```bash
+curl -X GET "https://api.rybbit.com/api/overview/123?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+
+#### Example Response
+
+```json
+{
+ "data": {
+ "sessions": 15420,
+ "pageviews": 48933,
+ "users": 12847,
+ "pages_per_session": 3.17,
+ "bounce_rate": 42.8,
+ "session_duration": 182.5
+ }
+}
+```
+
+---
+
+### Get Metric
+
+```
+GET /api/metric/:site
+```
+
+Returns dimensional analytics data broken down by a specific parameter. Supports pagination.
+
+#### Path Parameters
+
+<TypeTable
+ type={{
+ site: {
+ description: 'Site ID or site identifier',
+ type: 'string | number',
+ required: true,
+ },
+ }}
+/>
+
+#### Query Parameters
+
+Accepts all [Common Parameters](#common-parameters) plus the following:
+
+<TypeTable
+ type={{
+ parameter: {
+ description: 'The dimension to break down by',
+ type: 'FilterParameter',
+ typeDescription: 'e.g., "pathname", "country", "browser", "event_name"',
+ required: true,
+ },
+ limit: {
+ description: 'Number of results per page',
+ type: 'number',
+ default: 100,
+ },
+ page: {
+ description: 'Page number (1-indexed)',
+ type: 'number',
+ default: 1,
+ },
+ }}
+/>
+
+#### Response
+
+<TypeTable
+ type={{
+ data: {
+ description: 'Array of metric results',
+ type: 'MetricItem[]',
+ typeDescription: 'See MetricItem structure below',
+ },
+ totalCount: {
+ description: 'Total number of unique values across all pages',
+ type: 'number',
+ },
+ }}
+/>
+
+#### MetricItem Structure
+
+<TypeTable
+ type={{
+ value: {
+ description: 'The dimension value',
+ type: 'string',
+ typeDescription: 'e.g., "/blog", "Chrome", "US"',
+ },
+ count: {
+ description: 'Number of sessions for this value',
+ type: 'number',
+ },
+ percentage: {
+ description: 'Percentage of total sessions',
+ type: 'number',
+ typeDescription: 'Range: 0-100',
+ },
+ pageviews: {
+ description: 'Total pageviews (for page-related parameters)',
+ type: 'number',
+ required: false,
+ },
+ pageviews_percentage: {
+ description: 'Percentage of total pageviews',
+ type: 'number',
+ required: false,
+ },
+ time_on_page_seconds: {
+ description: 'Average time on page (for page-related parameters)',
+ type: 'number',
+ required: false,
+ },
+ bounce_rate: {
+ description: 'Bounce rate percentage',
+ type: 'number',
+ typeDescription: 'Range: 0-100',
+ required: false,
+ },
+ pathname: {
+ description: 'Representative pathname (for page_title parameter)',
+ type: 'string',
+ required: false,
+ },
+ }}
+/>
+
+#### Example Request
+
+```bash
+curl -X GET "https://api.rybbit.com/api/metric/123?parameter=country&start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York&limit=10&page=1" \
+ -H "Authorization: Bearer your_api_key_here"
+```
+
+#### Example Response
+
+```json
+{
+ "data": {
+ "data": [
+ {
+ "value": "US",
+ "count": 8420,
+ "percentage": 54.63,
+ "pageviews": 26891,
+ "pageviews_percentage": 54.96,
+ "bounce_rate": 41.2
+ },
+ {
+ "value": "GB",
+ "count": 2150,
+ "percentage": 13.95,
+ "pageviews": 6847,
+ "pageviews_percentage": 13.99,
+ "bounce_rate": 43.8
+ }
+ ],
+ "totalCount": 87
+ }
+}
+```
+
+#### Pagination Example
+
+```bash
+# Page 1
+GET /api/metric/123?parameter=pathname&limit=50&page=1
+
+# Page 2
+GET /api/metric/123?parameter=pathname&limit=50&page=2
+```
+
+---
+
+## Error Responses
+
+All endpoints return 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
+
+### Error Response Format
+
+```json
+{
+ "error": "Error message describing what went wrong"
+}
+```
+
+---
+
+## Best Practices
+
+1. **Cache responses** - Analytics data doesn't change frequently. Cache for at least 5-10 minutes.
+2. **Use date ranges** - For recent data, use `past_minutes_start/end`. For historical data, use `start_date/end_date`.
+3. **Filter strategically** - Apply filters to reduce data transfer and improve performance.
+4. **Paginate results** - Use the `limit` and `page` parameters for large datasets.
+5. **Monitor rate limits** - Implement exponential backoff if you receive 429 responses.
+
+---
+
+## Rate Limiting
+
+When you exceed the rate limit, you'll receive a `429 Too Many Requests` response:
+
+```json
+{
+ "success": false,
+ "error": "Rate limit exceeded. Maximum 500 requests per 10 minutes per API key."
+}
+```
+
+Wait for the rate limit window to reset before making additional requests.
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.json
index ba4b1e2f6..d508e51ff 100644
--- a/docs/content/docs/meta.json
+++ b/docs/content/docs/meta.json
@@ -13,6 +13,8 @@
"api",
"hiding-own-traffic",
"filter-traffic",
+ "---API---",
+ "api",
"---User Guide---",
"web-analytics",
"product-analytics",
diff --git a/server/src/api/sessionReplay/recordSessionReplay.ts b/server/src/api/sessionReplay/recordSessionReplay.ts
index a862f07bf..05bbbdc8b 100644
--- a/server/src/api/sessionReplay/recordSessionReplay.ts
+++ b/server/src/api/sessionReplay/recordSessionReplay.ts
@@ -2,7 +2,6 @@ import { FastifyReply, FastifyRequest } from "fastify";
import { z } from "zod";
import { siteConfig } from "../../lib/siteConfig.js";
import { SessionReplayIngestService } from "../../services/replay/sessionReplayIngestService.js";
-import { validateApiKey } from "../../services/shared/requestValidation.js";
import { usageService } from "../../services/usageService.js";
import { RecordSessionReplayRequest } from "../../types/sessionReplay.js";
import { getIpAddress } from "../../utils.js";
@@ -56,33 +55,6 @@ export async function recordSessionReplay(
const body = recordSessionReplaySchema.parse(request.body) as RecordSessionReplayRequest;
- // First check if API key is provided and valid
- const apiKeyValidation = await validateApiKey(siteId, body.apiKey);
-
- // If API key validation failed with an error, reject the request
- if (apiKeyValidation.error) {
- logger.warn(`[SessionReplay] Request rejected for site ${siteId}: ${apiKeyValidation.error}`);
- return reply.status(403).send({
- success: false,
- error: apiKeyValidation.error,
- });
- }
-
- // Check rate limit for API key authenticated requests
- // ratelimit for session replays doesn't really work right now
-
- // if (apiKeyValidation.success && body.apiKey) {
- // if (!checkApiKeyRateLimit(body.apiKey)) {
- // console.warn(
- // `[SessionReplay] Rate limit exceeded for API key ${body.apiKey} on site ${siteId}`,
- // );
- // return reply.status(429).send({
- // success: false,
- // error: "Rate limit exceeded. Maximum 20 requests per second per API key.",
- // });
- // }
- // }
-
// Check if the IP should be excluded from tracking
const requestIP = getIpAddress(request);
diff --git a/server/src/api/sites/getSiteApiConfig.ts b/server/src/api/sites/getSiteApiConfig.ts
deleted file mode 100644
index b48a3c7f9..000000000
--- a/server/src/api/sites/getSiteApiConfig.ts
+++ /dev/null
@@ -1,51 +0,0 @@
-import { FastifyRequest, FastifyReply } from "fastify";
-import { db } from "../../db/postgres/postgres.js";
-import { sites } from "../../db/postgres/schema.js";
-import { eq, and } from "drizzle-orm";
-import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
-
-export async function getSiteApiConfig(request: FastifyRequest<{ Params: { siteId: string } }>, reply: FastifyReply) {
- try {
- if (!request.user) {
- return reply.status(401).send({ success: false, error: "Unauthorized" });
- }
-
- const { siteId } = request.params;
- const parsedSiteId = parseInt(siteId, 10);
-
- if (isNaN(parsedSiteId)) {
- return reply.status(400).send({ success: false, error: "Invalid site ID" });
- }
-
- const userHasAdminAccessToSite = await getUserHasAdminAccessToSite(request, String(parsedSiteId));
- if (!userHasAdminAccessToSite) {
- return reply.status(403).send({ error: "Forbidden" });
- }
-
- // Get site data
- const site = await db
- .select({
- apiKey: sites.apiKey,
- })
- .from(sites)
- .where(eq(sites.siteId, parsedSiteId))
- .limit(1);
-
- if (site.length === 0) {
- return reply.status(404).send({ success: false, error: "Site not found" });
- }
-
- return reply.send({
- success: true,
- data: {
- apiKey: site[0].apiKey,
- },
- });
- } catch (error) {
- console.error("Error getting site dev config:", error);
- return reply.status(500).send({
- success: false,
- error: "Failed to get site API configuration",
- });
- }
-}
diff --git a/server/src/api/sites/updateSiteApiConfig.ts b/server/src/api/sites/updateSiteApiConfig.ts
deleted file mode 100644
index 088d0f93f..000000000
--- a/server/src/api/sites/updateSiteApiConfig.ts
+++ /dev/null
@@ -1,74 +0,0 @@
-import crypto from "crypto";
-import { FastifyReply, FastifyRequest } from "fastify";
-import { z } from "zod";
-import { getUserHasAdminAccessToSite } from "../../lib/auth-utils.js";
-import { siteConfig } from "../../lib/siteConfig.js";
-
-// Schema for updating API configuration
-const updateApiConfigSchema = z.object({
- action: z.enum(["generate_api_key", "revoke_api_key"]),
-});
-
-export async function updateSiteApiConfig(request: FastifyRequest, reply: FastifyReply) {
- try {
- if (!request.user) {
- return reply.status(401).send({ success: false, error: "Unauthorized" });
- }
-
- const { siteId } = request.params as { siteId: string };
- const parsedSiteId = parseInt(siteId, 10);
-
- if (isNaN(parsedSiteId)) {
- return reply.status(400).send({ success: false, error: "Invalid site ID" });
- }
-
- const userHasAdminAccessToSite = await getUserHasAdminAccessToSite(request, String(parsedSiteId));
- if (!userHasAdminAccessToSite) {
- return reply.status(403).send({ error: "Forbidden" });
- }
-
- // Validate request body
- const validationResult = updateApiConfigSchema.safeParse(request.body);
- if (!validationResult.success) {
- return reply.status(400).send({
- success: false,
- error: "Invalid request body",
- details: validationResult.error.flatten(),
- });
- }
-
- const { action } = validationResult.data;
-
- let updateData: any = {};
-
- switch (action) {
- case "generate_api_key":
- // Generate a secure random API key with rb_ prefix
- const apiKey = `rb_${crypto.randomBytes(16).toString("hex")}`;
- updateData.apiKey = apiKey;
- break;
-
- case "revoke_api_key":
- updateData.apiKey = null;
- break;
- }
-
- // Update the site config cache
- if (action === "generate_api_key" || action === "revoke_api_key") {
- siteConfig.updateConfig(parsedSiteId, { apiKey: updateData.apiKey });
- }
-
- return reply.send({
- success: true,
- data: {
- apiKey: updateData.apiKey,
- },
- });
- } catch (error) {
- console.error("Error updating site dev config:", error);
- return reply.status(500).send({
- success: false,
- error: "Failed to update site API configuration",
- });
- }
-}
diff --git a/server/src/api/user/createApiKey.ts b/server/src/api/user/createApiKey.ts
new file mode 100644
index 000000000..abfa7743d
--- /dev/null
+++ b/server/src/api/user/createApiKey.ts
@@ -0,0 +1,53 @@
+import { FastifyRequest, FastifyReply } from "fastify";
+import { z } from "zod";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { auth } from "../../lib/auth.js";
+
+const createApiKeySchema = z.object({
+ name: z.string().min(1, "Name is required").max(100, "Name too long"),
+ expiresIn: z.number().optional(),
+});
+
+type CreateApiKeyBody = z.infer<typeof createApiKeySchema>;
+
+export const createApiKey = async (request: FastifyRequest<{ Body: CreateApiKeyBody }>, reply: FastifyReply) => {
+ try {
+ const session = await getSessionFromReq(request);
+
+ if (!session?.user.id) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Validate request body
+ const validation = createApiKeySchema.safeParse(request.body);
+ if (!validation.success) {
+ return reply.status(400).send({
+ error: "Invalid request",
+ details: validation.error.errors,
+ });
+ }
+
+ const { name, expiresIn } = validation.data;
+
+ // Create API key with Better Auth
+ // Default rate limiting: 10,000 requests per day
+ const apiKey = await auth.api.createApiKey({
+ body: {
+ name,
+ userId: session.user.id,
+ expiresIn,
+ rateLimitEnabled: true,
+ rateLimitTimeWindow: 1000 * 60 * 10, // 10 minutes
+ rateLimitMax: 500,
+ prefix: "rb_",
+ },
+ });
+
+ // Return the full API key (including the key value)
+ // This is the only time the key will be shown
+ return reply.send(apiKey);
+ } catch (error) {
+ console.error("Error creating API key:", error);
+ return reply.status(500).send({ error: "Failed to create API key" });
+ }
+};
diff --git a/server/src/api/user/deleteApiKey.ts b/server/src/api/user/deleteApiKey.ts
new file mode 100644
index 000000000..53f39c4e5
--- /dev/null
+++ b/server/src/api/user/deleteApiKey.ts
@@ -0,0 +1,35 @@
+import { FastifyRequest, FastifyReply } from "fastify";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { auth } from "../../lib/auth.js";
+
+export const deleteApiKey = async (
+ request: FastifyRequest<{ Params: { keyId: string } }>,
+ reply: FastifyReply
+) => {
+ try {
+ const session = await getSessionFromReq(request);
+
+ if (!session?.user.id) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Get keyId from URL params
+ const { keyId } = request.params;
+
+ if (!keyId) {
+ return reply.status(400).send({ error: "Key ID is required" });
+ }
+
+ // Delete API key with Better Auth
+ // Better Auth will verify that the key belongs to the authenticated user
+ const result = await auth.api.deleteApiKey({
+ body: { keyId },
+ headers: request.headers as any,
+ });
+
+ return reply.send(result);
+ } catch (error) {
+ console.error("Error deleting API key:", error);
+ return reply.status(500).send({ error: "Failed to delete API key" });
+ }
+};
diff --git a/server/src/api/user/listApiKeys.ts b/server/src/api/user/listApiKeys.ts
new file mode 100644
index 000000000..ec85880af
--- /dev/null
+++ b/server/src/api/user/listApiKeys.ts
@@ -0,0 +1,23 @@
+import { FastifyRequest, FastifyReply } from "fastify";
+import { getSessionFromReq } from "../../lib/auth-utils.js";
+import { auth } from "../../lib/auth.js";
+
+export const listApiKeys = async (request: FastifyRequest, reply: FastifyReply) => {
+ try {
+ const session = await getSessionFromReq(request);
+
+ if (!session?.user.id) {
+ return reply.status(401).send({ error: "Unauthorized" });
+ }
+
+ // Use Better Auth to list API keys for the current user
+ const apiKeys = await auth.api.listApiKeys({
+ headers: request.headers as any,
+ });
+
+ return reply.send(apiKeys);
+ } catch (error) {
+ console.error("Error fetching API keys:", error);
+ return reply.status(500).send({ error: "Failed to fetch API keys" });
+ }
+};
diff --git a/server/src/db/postgres/schema.ts b/server/src/db/postgres/schema.ts
index 282257fff..a2e52f8dc 100644
--- a/server/src/db/postgres/schema.ts
+++ b/server/src/db/postgres/schema.ts
@@ -14,7 +14,7 @@ import {
unique,
} from "drizzle-orm/pg-core";
-// User table
+// User table (BetterAuth)
export const user = pgTable(
"user",
{
@@ -42,6 +42,7 @@ export const user = pgTable(
table => [unique("user_username_unique").on(table.username), unique("user_email_unique").on(table.email)]
);
+// Verification table (BetterAuth)
export const verification = pgTable("verification", {
id: text().primaryKey().notNull(),
identifier: text().notNull(),
@@ -129,6 +130,7 @@ export const funnels = pgTable(
]
);
+// Account table (BetterAuth)
export const account = pgTable(
"account",
{
@@ -155,6 +157,7 @@ export const account = pgTable(
]
);
+// Organization table (BetterAuth)
export const organization = pgTable(
"organization",
{
@@ -171,6 +174,7 @@ export const organization = pgTable(
table => [unique("organization_slug_unique").on(table.slug)]
);
+// Member table (BetterAuth)
export const member = pgTable(
"member",
{
@@ -194,6 +198,7 @@ export const member = pgTable(
]
);
+// Invitation table (BetterAuth)
export const invitation = pgTable(
"invitation",
{
@@ -219,6 +224,7 @@ export const invitation = pgTable(
]
);
+// Session table (BetterAuth)
export const session = pgTable(
"session",
{
@@ -243,6 +249,41 @@ export const session = pgTable(
]
);
+// API Key table (BetterAuth)
+export const apiKey = pgTable(
+ "apikey",
+ {
+ id: text().primaryKey().notNull(),
+ name: text(),
+ start: text(),
+ prefix: text(),
+ key: text().notNull(),
+ userId: text().notNull(),
+ refillInterval: integer(),
+ refillAmount: integer(),
+ lastRefillAt: timestamp({ mode: "string" }),
+ enabled: boolean().notNull().default(true),
+ rateLimitEnabled: boolean().notNull().default(false),
+ rateLimitTimeWindow: integer(),
+ rateLimitMax: integer(),
+ requestCount: integer().notNull().default(0),
+ remaining: integer(),
+ lastRequest: timestamp({ mode: "string" }),
+ expiresAt: timestamp({ mode: "string" }),
+ createdAt: timestamp({ mode: "string" }).notNull(),
+ updatedAt: timestamp({ mode: "string" }).notNull(),
+ permissions: text(),
+ metadata: jsonb(),
+ },
+ table => [
+ foreignKey({
+ columns: [table.userId],
+ foreignColumns: [user.id],
+ name: "apiKey_userId_user_id_fk",
+ }),
+ ]
+);
+
// Goals table for tracking conversion goals
export const goals = pgTable(
"goals",
diff --git a/server/src/index.ts b/server/src/index.ts
index eaaa85763..6ca7bf9a5 100644
--- a/server/src/index.ts
+++ b/server/src/index.ts
@@ -52,13 +52,11 @@ import { addSite } from "./api/sites/addSite.js";
import { updateSiteConfig } from "./api/sites/updateSiteConfig.js";
import { deleteSite } from "./api/sites/deleteSite.js";
import { getSite } from "./api/sites/getSite.js";
-import { getSiteApiConfig } from "./api/sites/getSiteApiConfig.js";
import { getSiteExcludedIPs } from "./api/sites/getSiteExcludedIPs.js";
import { getSiteExcludedCountries } from "./api/sites/getSiteExcludedCountries.js";
import { getSiteHasData } from "./api/sites/getSiteHasData.js";
import { getSiteIsPublic } from "./api/sites/getSiteIsPublic.js";
import { getSitesFromOrg } from "./api/sites/getSitesFromOrg.js";
-import { updateSiteApiConfig } from "./api/sites/updateSiteApiConfig.js";
import { createCheckoutSession } from "./api/stripe/createCheckoutSession.js";
import { createPortalSession } from "./api/stripe/createPortalSession.js";
import { getSubscription } from "./api/stripe/getSubscription.js";
@@ -69,6 +67,9 @@ import { addUserToOrganization } from "./api/user/addUserToOrganization.js";
import { getUserOrganizations } from "./api/user/getUserOrganizations.js";
import { listOrganizationMembers } from "./api/user/listOrganizationMembers.js";
import { updateAccountSettings } from "./api/user/updateAccountSettings.js";
+import { listApiKeys } from "./api/user/listApiKeys.js";
+import { createApiKey } from "./api/user/createApiKey.js";
+import { deleteApiKey } from "./api/user/deleteApiKey.js";
import { initializeClickhouse } from "./db/clickhouse/clickhouse.js";
import { initPostgres } from "./db/postgres/initPostgres.js";
import { getSessionFromReq, getUserHasAccessToSitePublic, mapHeaders } from "./lib/auth-utils.js";
@@ -362,8 +363,6 @@ server.post("/api/update-site-config", updateSiteConfig);
server.post("/api/delete-site/:id", deleteSite);
server.get("/api/get-sites-from-org/:organizationId", getSitesFromOrg);
server.get("/api/get-site/:id", getSite);
-server.get("/api/site/:siteId/api-config", getSiteApiConfig);
-server.post("/api/site/:siteId/api-config", updateSiteApiConfig);
server.get("/api/site/:siteId/private-link-config", getSitePrivateLinkConfig);
server.post("/api/site/:siteId/private-link-config", updateSitePrivateLinkConfig);
server.get("/api/site/:siteId/tracking-config", getTrackingConfig);
@@ -373,6 +372,9 @@ server.get("/api/list-organization-members/:organizationId", listOrganizationMem
server.get("/api/user/organizations", getUserOrganizations);
server.post("/api/add-user-to-organization", addUserToOrganization);
server.post("/api/user/account-settings", updateAccountSettings);
+server.get("/api/user/api-keys", listApiKeys);
+server.post("/api/user/api-keys", createApiKey);
+server.delete("/api/user/api-keys/:keyId", deleteApiKey);
// GOOGLE SEARCH CONSOLE
server.get("/api/gsc/connect/:site", connectGSC);
diff --git a/server/src/lib/auth-utils.ts b/server/src/lib/auth-utils.ts
index 9e333904f..9a0feaa82 100644
--- a/server/src/lib/auth-utils.ts
+++ b/server/src/lib/auth-utils.ts
@@ -104,13 +104,10 @@ export async function getSitesUserHasAccessTo(req: FastifyRequest, adminOnly = f
// for routes that are potentially public
export async function getUserHasAccessToSitePublic(req: FastifyRequest, siteId: string | number) {
- const [sites, config] = await Promise.all([
- getSitesUserHasAccessTo(req),
- siteConfig.getConfig(siteId),
- ]);
+ const [userSites, config] = await Promise.all([getSitesUserHasAccessTo(req), siteConfig.getConfig(siteId)]);
// Check if user has direct access to the site
- const hasDirectAccess = sites.some(site => site.siteId === Number(siteId));
+ const hasDirectAccess = userSites.some(site => site.siteId === Number(siteId));
if (hasDirectAccess) {
return true;
}
@@ -126,6 +123,55 @@ export async function getUserHasAccessToSitePublic(req: FastifyRequest, siteId:
return true;
}
+ // Check if a valid API key was provided
+ // Priority: 1. Authorization: Bearer header (recommended), 2. Query parameter (testing only)
+ const authHeader = req.headers["authorization"];
+ const bearerToken = authHeader && typeof authHeader === "string" && authHeader.startsWith("Bearer ")
+ ? authHeader.substring(7)
+ : null;
+
+ const queryApiKey = (req.query as any)?.api_key;
+ const apiKey = bearerToken || queryApiKey;
+
+ if (apiKey && typeof apiKey === "string") {
+ try {
+ // Verify the API key using Better Auth
+ const result = await auth.api.verifyApiKey({
+ body: { key: apiKey },
+ });
+
+ if (result.valid && result.key) {
+ // Get the userId from the API key
+ const apiKeyUserId = result.key.userId;
+
+ // Get the site's organization
+ const siteRecords = await db
+ .select({
+ organizationId: sites.organizationId,
+ })
+ .from(sites)
+ .where(eq(sites.siteId, Number(siteId)))
+ .limit(1);
+
+ if (siteRecords.length > 0 && siteRecords[0].organizationId) {
+ // Check if the API key's user is a member of the organization
+ const userMembership = await db
+ .select()
+ .from(member)
+ .where(and(eq(member.userId, apiKeyUserId), eq(member.organizationId, siteRecords[0].organizationId)))
+ .limit(1);
+
+ if (userMembership.length > 0) {
+ return true;
+ }
+ }
+ }
+ } catch (error) {
+ console.error("Error verifying API key:", error);
+ // Continue to return false if API key verification fails
+ }
+ }
+
return false;
}
diff --git a/server/src/lib/auth.ts b/server/src/lib/auth.ts
index fe8bf292c..4f5641af8 100644
--- a/server/src/lib/auth.ts
+++ b/server/src/lib/auth.ts
@@ -1,5 +1,5 @@
import { betterAuth } from "better-auth";
-import { admin, captcha, emailOTP, organization } from "better-auth/plugins";
+import { admin, captcha, emailOTP, organization, apiKey } from "better-auth/plugins";
import dotenv from "dotenv";
import { asc, eq } from "drizzle-orm";
import pg from "pg";
@@ -16,6 +16,7 @@ type AuthType = ReturnType<typeof betterAuth> | null;
const pluginList = [
admin(),
+ apiKey(),
organization({
// Allow users to create organizations
allowUserToCreateOrganization: true,
@@ -92,7 +93,7 @@ const pluginList = [
: []),
];
-export let auth: AuthType | null = betterAuth({
+export const auth = betterAuth({
basePath: "/api/auth",
database: new pg.Pool({
host: process.env.POSTGRES_HOST || "postgres",
diff --git a/server/src/lib/rateLimiter.ts b/server/src/lib/rateLimiter.ts
deleted file mode 100644
index cf0cd2df0..000000000
--- a/server/src/lib/rateLimiter.ts
+++ /dev/null
@@ -1,56 +0,0 @@
-import { IS_CLOUD } from "./const.js";
-
-// In-memory rate limiter for API keys
-class ApiKeyRateLimiter {
- private limits: Map<string, { count: number; resetTime: number }> = new Map();
- private readonly maxRequests = 20; // 20 requests per second
- private readonly windowMs = 1000; // 1 second window
-
- isAllowed(apiKey: string): boolean {
- if (!IS_CLOUD) {
- return true; // No rate limiting for self-hosted
- }
-
- const now = Date.now();
- const existing = this.limits.get(apiKey);
-
- if (!existing || now >= existing.resetTime) {
- // New window or expired window
- this.limits.set(apiKey, {
- count: 1,
- resetTime: now + this.windowMs,
- });
- return true;
- }
-
- if (existing.count >= this.maxRequests) {
- return false; // Rate limit exceeded
- }
-
- // Increment counter
- existing.count++;
- return true;
- }
-
- // Clean up expired entries to prevent memory leaks
- cleanup(): void {
- const now = Date.now();
- for (const [key, value] of this.limits.entries()) {
- if (now >= value.resetTime) {
- this.limits.delete(key);
- }
- }
- }
-}
-
-export const apiKeyRateLimiter = new ApiKeyRateLimiter();
-
-// Clean up expired entries every 5 minutes
-if (IS_CLOUD) {
- setInterval(
- () => {
- apiKeyRateLimiter.cleanup();
- },
- 5 * 60 * 1000
- );
-}
diff --git a/server/src/lib/siteConfig.ts b/server/src/lib/siteConfig.ts
index ed9590fba..9f37afb08 100644
--- a/server/src/lib/siteConfig.ts
+++ b/server/src/lib/siteConfig.ts
@@ -14,7 +14,6 @@ export interface SiteConfigData {
blockBots: boolean;
excludedIPs: string[];
excludedCountries: string[];
- apiKey?: string | null;
privateLinkKey?: string | null;
sessionReplay: boolean;
webVitals: boolean;
@@ -61,7 +60,6 @@ class SiteConfig {
blockBots: sites.blockBots,
excludedIPs: sites.excludedIPs,
excludedCountries: sites.excludedCountries,
- apiKey: sites.apiKey,
privateLinkKey: sites.privateLinkKey,
sessionReplay: sites.sessionReplay,
webVitals: sites.webVitals,
@@ -89,7 +87,6 @@ class SiteConfig {
blockBots: site.blockBots === undefined ? true : site.blockBots,
excludedIPs: Array.isArray(site.excludedIPs) ? site.excludedIPs : [],
excludedCountries: Array.isArray(site.excludedCountries) ? site.excludedCountries : [],
- apiKey: site.apiKey,
privateLinkKey: site.privateLinkKey,
sessionReplay: site.sessionReplay || false,
webVitals: site.webVitals || false,
@@ -149,7 +146,6 @@ class SiteConfig {
saltUserIds: config.saltUserIds,
blockBots: config.blockBots,
excludedIPs: config.excludedIPs,
- apiKey: config.apiKey,
createdBy: "", // This would need to be provided
});
} catch (error) {
diff --git a/server/src/services/shared/requestValidation.test.ts b/server/src/services/shared/requestValidation.test.ts
deleted file mode 100644
index be31ec872..000000000
--- a/server/src/services/shared/requestValidation.test.ts
+++ /dev/null
@@ -1,251 +0,0 @@
-import { beforeEach, describe, expect, it, vi } from "vitest";
-
-// Define the expected site config type to match SiteConfigData
-interface SiteConfigData {
- id: string;
- siteId: number;
- domain: string;
- apiKey?: string | null;
- public: boolean;
- saltUserIds: boolean;
- blockBots: boolean;
- excludedIPs: string[];
- excludedCountries: string[];
- sessionReplay: boolean;
- webVitals: boolean;
- trackErrors: boolean;
- trackOutbound: boolean;
- trackUrlParams: boolean;
- trackInitialPageView: boolean;
- trackSpaNavigation: boolean;
- trackIp: boolean;
-}
-
-// Mock dependencies
-vi.mock("../../lib/rateLimiter.js", () => ({
- apiKeyRateLimiter: {
- isAllowed: vi.fn(),
- },
-}));
-
-vi.mock("../../lib/siteConfig.js", () => ({
- siteConfig: {
- getSiteConfig: vi.fn(),
- },
-}));
-
-vi.mock("../../utils.js", () => ({
- normalizeOrigin: vi.fn(),
-}));
-
-import { checkApiKeyRateLimit, validateApiKey } from "./requestValidation.js";
-
-// Import mocked modules
-import { apiKeyRateLimiter } from "../../lib/rateLimiter.js";
-import { siteConfig } from "../../lib/siteConfig.js";
-
-describe("validateApiKey", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("should return success false when no API key is provided", async () => {
- const result = await validateApiKey(1);
- expect(result).toEqual({ success: false });
- });
-
- it("should return success false when API key is empty string", async () => {
- const result = await validateApiKey(1, "");
- expect(result).toEqual({ success: false });
- });
-
- it("should return success false when site is not found", async () => {
- vi.mocked(siteConfig.getConfig).mockResolvedValue(undefined);
-
- const result = await validateApiKey(1, "test-api-key");
-
- expect(siteConfig.getConfig).toHaveBeenCalledWith(1);
- expect(result).toEqual({ success: false, error: "Site not found" });
- });
-
- it("should return success true when API key matches", async () => {
- const mockSite: SiteConfigData = {
- id: "test-id",
- siteId: 1,
- apiKey: "valid-api-key",
- domain: "example.com",
- public: true,
- saltUserIds: false,
- blockBots: true,
- excludedIPs: [],
- excludedCountries: [],
- sessionReplay: false,
- webVitals: false,
- trackErrors: false,
- trackOutbound: true,
- trackUrlParams: true,
- trackInitialPageView: true,
- trackSpaNavigation: true,
- trackIp: false,
- };
-
- vi.mocked(siteConfig.getConfig).mockResolvedValue(mockSite);
-
- // Mock console.info to avoid output during tests
- const consoleSpy = vi.spyOn(console, "info").mockImplementation(() => {});
-
- const result = await validateApiKey(1, "valid-api-key");
-
- expect(result).toEqual({ success: true });
- expect(consoleSpy).toHaveBeenCalledWith("[Validation] Valid API key for site 1");
-
- consoleSpy.mockRestore();
- });
-
- it("should return success false when API key does not match", async () => {
- const mockSite: SiteConfigData = {
- id: "test-id",
- siteId: 1,
- apiKey: "valid-api-key",
- domain: "example.com",
- public: true,
- saltUserIds: false,
- blockBots: true,
- excludedIPs: [],
- excludedCountries: [],
- sessionReplay: false,
- webVitals: false,
- trackErrors: false,
- trackOutbound: true,
- trackUrlParams: true,
- trackInitialPageView: true,
- trackSpaNavigation: true,
- trackIp: false,
- };
-
- vi.mocked(siteConfig.getConfig).mockResolvedValue(mockSite);
-
- const result = await validateApiKey(1, "invalid-api-key");
-
- expect(result).toEqual({ success: false, error: "Invalid API key" });
- });
-
- it("should handle string siteId by converting to number", async () => {
- const mockSite: SiteConfigData = {
- id: "test-id",
- siteId: 123,
- apiKey: "test-key",
- domain: "example.com",
- public: true,
- saltUserIds: false,
- blockBots: true,
- excludedIPs: [],
- excludedCountries: [],
- sessionReplay: false,
- webVitals: false,
- trackErrors: false,
- trackOutbound: true,
- trackUrlParams: true,
- trackInitialPageView: true,
- trackSpaNavigation: true,
- trackIp: false,
- };
-
- vi.mocked(siteConfig.getConfig).mockResolvedValue(mockSite);
-
- await validateApiKey("123", "test-key");
-
- expect(siteConfig.getConfig).toHaveBeenCalledWith(123);
- });
-
- it("should handle site with no API key configured", async () => {
- const mockSite: Partial<SiteConfigData> &
- Pick<
- SiteConfigData,
- | "id"
- | "siteId"
- | "domain"
- | "public"
- | "saltUserIds"
- | "blockBots"
- | "excludedIPs"
- | "sessionReplay"
- | "webVitals"
- | "trackErrors"
- | "trackOutbound"
- | "trackUrlParams"
- | "trackInitialPageView"
- | "trackSpaNavigation"
- > = {
- id: "test-id",
- siteId: 1,
- domain: "example.com",
- public: true,
- saltUserIds: false,
- blockBots: true,
- excludedIPs: [],
- excludedCountries: [],
- sessionReplay: false,
- webVitals: false,
- trackErrors: false,
- trackOutbound: true,
- trackUrlParams: true,
- trackInitialPageView: true,
- trackSpaNavigation: true,
- trackIp: false,
- }; // No apiKey property
-
- vi.mocked(siteConfig.getConfig).mockResolvedValue(mockSite as SiteConfigData);
-
- const result = await validateApiKey(1, "any-key");
-
- expect(result).toEqual({ success: false, error: "Invalid API key" });
- });
-
- it("should handle errors during validation", async () => {
- vi.mocked(siteConfig.getConfig).mockRejectedValue(new Error("Database error"));
-
- const consoleSpy = vi.spyOn(console, "error").mockImplementation(() => {});
-
- const result = await validateApiKey(1, "test-key");
-
- expect(result).toEqual({ success: false, error: "Failed to validate API key" });
- expect(consoleSpy).toHaveBeenCalledWith("Error validating API key:", expect.any(Error));
-
- consoleSpy.mockRestore();
- });
-});
-
-describe("checkApiKeyRateLimit", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- });
-
- it("should return true when rate limiter allows the request", () => {
- vi.mocked(apiKeyRateLimiter.isAllowed).mockReturnValue(true);
-
- const result = checkApiKeyRateLimit("test-api-key");
-
- expect(apiKeyRateLimiter.isAllowed).toHaveBeenCalledWith("test-api-key");
- expect(result).toBe(true);
- });
-
- it("should return false when rate limiter blocks the request", () => {
- vi.mocked(apiKeyRateLimiter.isAllowed).mockReturnValue(false);
-
- const result = checkApiKeyRateLimit("test-api-key");
-
- expect(apiKeyRateLimiter.isAllowed).toHaveBeenCalledWith("test-api-key");
- expect(result).toBe(false);
- });
-
- it("should handle different API keys", () => {
- vi.mocked(apiKeyRateLimiter.isAllowed).mockReturnValueOnce(true).mockReturnValueOnce(false);
-
- expect(checkApiKeyRateLimit("key1")).toBe(true);
- expect(checkApiKeyRateLimit("key2")).toBe(false);
-
- expect(apiKeyRateLimiter.isAllowed).toHaveBeenNthCalledWith(1, "key1");
- expect(apiKeyRateLimiter.isAllowed).toHaveBeenNthCalledWith(2, "key2");
- });
-});
diff --git a/server/src/services/shared/requestValidation.ts b/server/src/services/shared/requestValidation.ts
deleted file mode 100644
index fe7ac653b..000000000
--- a/server/src/services/shared/requestValidation.ts
+++ /dev/null
@@ -1,63 +0,0 @@
-import { createServiceLogger } from "../../lib/logger/logger.js";
-import { apiKeyRateLimiter } from "../../lib/rateLimiter.js";
-import { siteConfig } from "../../lib/siteConfig.js";
-import { normalizeOrigin } from "../../utils.js";
-import { DISABLE_ORIGIN_CHECK } from "../tracker/const.js";
-
-const logger = createServiceLogger("request-validation");
-
-/**
- * Result of API key validation
- */
-export interface ApiKeyValidationResult {
- success: boolean;
- error?: string;
-}
-
-/**
- * Result of origin validation
- */
-export interface OriginValidationResult {
- success: boolean;
- error?: string;
-}
-
-/**
- * Validates API key for the site
- * @param siteId The site ID from the tracking payload
- * @param apiKey The API key from the payload
- * @returns An object with success status and optional error message
- */
-export async function validateApiKey(siteId: string | number, apiKey?: string): Promise<ApiKeyValidationResult> {
- if (!apiKey) {
- return { success: false };
- }
-
- try {
- const numericSiteId = typeof siteId === "string" ? parseInt(siteId, 10) : siteId;
- const site = await siteConfig.getConfig(numericSiteId);
-
- if (!site) {
- return { success: false, error: "Site not found" };
- }
-
- if (site.apiKey && apiKey === site.apiKey) {
- logger.info({ siteId }, "Valid API key for site");
- return { success: true };
- }
-
- return { success: false, error: "Invalid API key" };
- } catch (error) {
- logger.error(error, "Error validating API key");
- return { success: false, error: "Failed to validate API key" };
- }
-}
-
-/**
- * Checks if the API key rate limit has been exceeded
- * @param apiKey The API key to check
- * @returns true if the request is allowed, false if rate limit exceeded
- */
-export function checkApiKeyRateLimit(apiKey: string): boolean {
- return apiKeyRateLimiter.isAllowed(apiKey);
-}
diff --git a/server/src/services/tracker/trackEvent.ts b/server/src/services/tracker/trackEvent.ts
index 8a4553f3b..b656c7b6f 100644
--- a/server/src/services/tracker/trackEvent.ts
+++ b/server/src/services/tracker/trackEvent.ts
@@ -4,7 +4,6 @@ import { z, ZodError } from "zod";
import { createServiceLogger } from "../../lib/logger/logger.js";
import { siteConfig } from "../../lib/siteConfig.js";
import { sessionsService } from "../sessions/sessionsService.js";
-import { checkApiKeyRateLimit, validateApiKey } from "../shared/requestValidation.js";
import { usageService } from "../usageService.js";
import { pageviewQueue } from "./pageviewQueue.js";
import { createBasePayload } from "./utils.js";
@@ -214,35 +213,6 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
// Use validated data
const validatedPayload = validationResult.data;
- // First check if API key is provided and valid
- const apiKeyValidation = await validateApiKey(validatedPayload.site_id, validatedPayload.api_key);
-
- // If API key validation failed with an error, reject the request
- if (apiKeyValidation.error) {
- logger.warn(
- { siteId: validatedPayload.site_id, error: apiKeyValidation.error },
- "Request rejected - API key validation failed"
- );
- return reply.status(403).send({
- success: false,
- error: apiKeyValidation.error,
- });
- }
-
- // Check rate limit for API key authenticated requests
- if (apiKeyValidation.success && validatedPayload.api_key) {
- if (!checkApiKeyRateLimit(validatedPayload.api_key)) {
- logger.warn(
- { apiKey: validatedPayload.api_key, siteId: validatedPayload.site_id },
- "Rate limit exceeded for API key"
- );
- return reply.status(429).send({
- success: false,
- error: "Rate limit exceeded. Maximum 20 requests per second per API key.",
- });
- }
- }
-
// Get the site configuration to get the numeric siteId
const siteConfiguration = await siteConfig.getConfig(validatedPayload.site_id);
if (!siteConfiguration) {