Skip to content

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

api key (#416)

Bill Yang4e502fc8e65b
diff --git a/client/src/components/SiteSettings/ApiKeyManager.tsx b/client/src/components/SiteSettings/ApiKeyManager.tsx
index ae6002196..d64a0486b 100644
--- a/client/src/components/SiteSettings/ApiKeyManager.tsx
+++ b/client/src/components/SiteSettings/ApiKeyManager.tsx
@@ -18,6 +18,7 @@ import {
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,
@@ -50,8 +51,23 @@ export function ApiKeyManager({
<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 using the API endpoint or from
- localhost during development.
+ Generate an API key to track events from{" "}
+ <Link
+ href="https://rybbit.io/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.io/docs/api"
+ target="_blank"
+ className="text-indigo-300 hover:underline"
+ >
+ API endpoint
+ </Link>
+ .
</p>
</div>
@@ -106,8 +122,7 @@ export function ApiKeyManager({
</div>
</div>
</div>
-
- <div>
+ <div className="space-y-4">
<AlertDialog>
<AlertDialogTrigger asChild>
<Button
diff --git a/docs/src/content/_meta.js b/docs/src/content/_meta.js
index 2a010af1d..e243cb25a 100644
--- a/docs/src/content/_meta.js
+++ b/docs/src/content/_meta.js
@@ -9,6 +9,7 @@ export default {
"track-events": "",
sdks: "SDKs",
guides: "",
+ api: "",
"localhost-tracking": "",
"hiding-own-traffic": "",
_4: {
diff --git a/docs/src/content/api.mdx b/docs/src/content/api.mdx
new file mode 100644
index 000000000..93ccb5dd5
--- /dev/null
+++ b/docs/src/content/api.mdx
@@ -0,0 +1,858 @@
+import { Steps } from 'nextra/components'
+import { Callout } from 'nextra/components'
+import { Tabs } from 'nextra/components'
+
+# API
+
+Track events from server-side applications, mobile apps, or any platform using the HTTP API with authentication.
+
+## 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.
+
+### Data Enrichment
+
+- **Geolocation**: IP addresses are resolved to country, region, city, and coordinates using MaxMind GeoLite2 database
+- **Device Info**: User agent strings are parsed to extract browser, operating system, and device type information
+
+## Steps
+
+<Steps>
+### Generate API Key
+
+In your site dashboard: Settings β†’ API Key tab β†’ Generate API Key
+
+### Include in Requests
+
+<Tabs items={['Pageview', 'Custom Event']}>
+ <Tabs.Tab>
+```bash
+curl -X POST 'https://app.rybbit.io/api/track' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "api_key": "rb_your_api_key_here",
+ "site_id": "123",
+ "type": "pageview",
+ "pathname": "/api/users",
+ "hostname": "api.example.com",
+ "page_title": "User API Endpoint",
+ "user_agent": "MyApp/1.0 (Linux; x64)",
+ "ip_address": "192.168.1.1"
+ }'
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+```bash
+curl -X POST 'https://app.rybbit.io/api/track' \
+ -H 'Content-Type: application/json' \
+ -d '{
+ "api_key": "rb_your_api_key_here",
+ "site_id": "123",
+ "type": "custom_event",
+ "pathname": "/checkout",
+ "event_name": "purchase",
+ "properties": "{\"amount\": 99.99, \"currency\": \"USD\", \"product_id\": \"abc123\"}"
+ }'
+```
+ </Tabs.Tab>
+</Tabs>
+
+</Steps>
+
+## 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) |
+
+## Language Examples
+
+<Tabs items={['Node.js', 'Python', 'Go', 'Java', 'PHP', 'Ruby', 'C#/.NET', 'Rust', 'iOS (Swift)', 'Android (Kotlin)', 'Flutter']}>
+ <Tabs.Tab>
+```javascript
+const trackEvent = async (eventData) => {
+ const response = await fetch('https://app.rybbit.io/api/track', {
+ method: 'POST',
+ headers: {
+ 'Content-Type': 'application/json',
+ },
+ body: JSON.stringify({
+ api_key: process.env.RYBBIT_API_KEY,
+ site_id: process.env.RYBBIT_SITE_ID,
+ ...eventData
+ })
+ });
+
+ return response.json();
+};
+
+// Track a pageview
+await trackEvent({
+ type: 'pageview',
+ pathname: '/api/users',
+ hostname: 'api.example.com'
+});
+
+// Track a custom event
+await trackEvent({
+ type: 'custom_event',
+ pathname: '/checkout',
+ event_name: 'purchase',
+ properties: JSON.stringify({ amount: 99.99, currency: 'USD' })
+});
+```
+
+ </Tabs.Tab>
+ <Tabs.Tab>
+```python
+import requests
+import json
+import os
+
+def track_event(event_data):
+ response = requests.post(
+ 'https://app.rybbit.io/api/track',
+ headers={'Content-Type': 'application/json'},
+ json={
+ 'api_key': os.getenv('RYBBIT_API_KEY'),
+ 'site_id': os.getenv('RYBBIT_SITE_ID'),
+ **event_data
+ }
+ )
+ return response.json()
+
+# Track a pageview
+track_event({
+ 'type': 'pageview',
+ 'pathname': '/api/users',
+ 'hostname': 'api.example.com'
+})
+
+# Track a custom event
+track_event({
+ 'type': 'custom_event',
+ 'pathname': '/checkout',
+ 'event_name': 'purchase',
+ 'properties': json.dumps({'amount': 99.99, 'currency': 'USD'})
+})
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```go
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "os"
+)
+
+type TrackingEvent struct {
+ APIKey string `json:"api_key"`
+ SiteID string `json:"site_id"`
+ Type string `json:"type"`
+ Pathname string `json:"pathname"`
+ Hostname string `json:"hostname,omitempty"`
+ EventName string `json:"event_name,omitempty"`
+ Properties string `json:"properties,omitempty"`
+}
+
+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",
+ bytes.NewBuffer(jsonData),
+ )
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+
+ return nil
+}
+
+func main() {
+ // Track a pageview
+ trackEvent(TrackingEvent{
+ Type: "pageview",
+ Pathname: "/api/users",
+ Hostname: "api.example.com",
+ })
+
+ // Track a custom event
+ trackEvent(TrackingEvent{
+ Type: "custom_event",
+ Pathname: "/checkout",
+ EventName: "purchase",
+ Properties: `{"amount": 99.99, "currency": "USD"}`,
+ })
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```java
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.net.URI;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import java.util.Map;
+import java.util.HashMap;
+
+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.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");
+ customEvent.put("pathname", "/checkout");
+ customEvent.put("event_name", "purchase");
+ customEvent.put("properties", "{\"amount\": 99.99, \"currency\": \"USD\"}");
+ tracker.trackEvent(customEvent);
+ }
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```php
+<?php
+
+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);
+ }
+}
+
+// Usage
+$tracker = new RybbitTracker();
+
+// Track a pageview
+$tracker->trackEvent([
+ 'type' => 'pageview',
+ 'pathname' => '/api/users',
+ 'hostname' => 'api.example.com'
+]);
+
+// Track a custom event
+$tracker->trackEvent([
+ 'type' => 'custom_event',
+ 'pathname' => '/checkout',
+ 'event_name' => 'purchase',
+ 'properties' => json_encode(['amount' => 99.99, 'currency' => 'USD'])
+]);
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```ruby
+require 'net/http'
+require 'json'
+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
+
+# Usage
+tracker = RybbitTracker.new
+
+# Track a pageview
+tracker.track_event({
+ type: 'pageview',
+ pathname: '/api/users',
+ hostname: 'api.example.com'
+})
+
+# Track a custom event
+tracker.track_event({
+ type: 'custom_event',
+ pathname: '/checkout',
+ event_name: 'purchase',
+ properties: JSON.generate({ amount: 99.99, currency: 'USD' })
+})
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```csharp
+using System;
+using System.Net.Http;
+using System.Text;
+using System.Text.Json;
+using System.Threading.Tasks;
+using System.Collections.Generic;
+
+public class RybbitTracker
+{
+ private readonly HttpClient _httpClient;
+ 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>
+ {
+ ["type"] = "pageview",
+ ["pathname"] = "/api/users",
+ ["hostname"] = "api.example.com"
+ });
+
+ // Track a custom event
+ await tracker.TrackEventAsync(new Dictionary<string, object>
+ {
+ ["type"] = "custom_event",
+ ["pathname"] = "/checkout",
+ ["event_name"] = "purchase",
+ ["properties"] = JsonSerializer.Serialize(new { amount = 99.99, currency = "USD" })
+ });
+ }
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```rust
+use reqwest;
+use serde_json::{json, Value};
+use std::env;
+
+#[derive(Clone)]
+struct RybbitTracker {
+ client: reqwest::Client,
+ api_key: String,
+ site_id: String,
+ api_url: String,
+}
+
+impl RybbitTracker {
+ fn new() -> Self {
+ Self {
+ client: reqwest::Client::new(),
+ api_key: env::var("RYBBIT_API_KEY").expect("RYBBIT_API_KEY not set"),
+ site_id: env::var("RYBBIT_SITE_ID").expect("RYBBIT_SITE_ID not set"),
+ 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(())
+ }
+}
+
+#[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",
+ "pathname": "/checkout",
+ "event_name": "purchase",
+ "properties": r#"{"amount": 99.99, "currency": "USD"}"#
+ })).await?;
+
+ Ok(())
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```swift
+import Foundation
+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"],
+ !apiKey.isEmpty,
+ let siteId = ProcessInfo.processInfo.environment["RYBBIT_SITE_ID"],
+ !siteId.isEmpty else {
+ fatalError("RYBBIT_API_KEY and RYBBIT_SITE_ID environment variables must be set")
+ }
+ 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
+ data["screenWidth"] = Int(bounds.width)
+ data["screenHeight"] = Int(bounds.height)
+ } else {
+ // Fallback for older iOS versions
+ let bounds = UIScreen.main.bounds
+ 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
+ let model = UIDevice.current.model
+ return "MyApp/\(appVersion) (iOS \(osVersion); \(model))"
+ }
+}
+
+// Usage
+Task {
+ // Track a pageview
+ try await RybbitTracker.shared.trackEvent([
+ "type": "pageview",
+ "pathname": "/api/users",
+ "hostname": "api.example.com",
+ "page_title": "User API Endpoint"
+ ])
+
+ // Track a custom event
+ try await RybbitTracker.shared.trackEvent([
+ "type": "custom_event",
+ "pathname": "/checkout",
+ "event_name": "purchase",
+ "properties": "{\"amount\": 99.99, \"currency\": \"USD\"}"
+ ])
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```kotlin
+import kotlinx.coroutines.*
+import okhttp3.*
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.RequestBody.Companion.toRequestBody
+import org.json.JSONObject
+import android.content.Context
+import android.os.Build
+import java.util.Locale
+
+class RybbitTracker(private val context: Context) {
+ companion object {
+ 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
+ return "MyApp/$appVersion (Android ${Build.VERSION.RELEASE}; ${Build.MODEL})"
+ }
+}
+
+// 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(
+ "type" to "pageview",
+ "pathname" to "/api/users",
+ "hostname" to "api.example.com",
+ "page_title" to "User API Endpoint"
+ ))
+
+ // Track a custom event
+ tracker.trackEvent(mapOf(
+ "type" to "custom_event",
+ "pathname" to "/checkout",
+ "event_name" to "purchase",
+ "properties" to """{"amount": 99.99, "currency": "USD"}"""
+ ))
+ }
+ }
+}
+```
+ </Tabs.Tab>
+ <Tabs.Tab>
+
+```dart
+import 'package:http/http.dart' as http;
+import 'dart:convert';
+import 'dart:io';
+import 'package:flutter/material.dart';
+import 'package:device_info_plus/device_info_plus.dart';
+
+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})';
+ } else if (Platform.isIOS) {
+ final iosInfo = await _deviceInfoPlugin.iosInfo;
+ return 'MyApp/$appVersion (iOS ${iosInfo.systemVersion}; ${iosInfo.model})';
+ }
+
+ return 'MyApp/$appVersion (${Platform.operatingSystem})';
+ }
+}
+
+// Usage
+void main() {
+ runApp(MyApp());
+}
+
+class MyApp extends StatefulWidget {
+ @override
+ _MyAppState createState() => _MyAppState();
+}
+
+class _MyAppState extends State<MyApp> {
+ final tracker = RybbitTracker();
+
+ @override
+ void initState() {
+ super.initState();
+ // Track app launch once when the app initializes
+ tracker.trackEvent({
+ 'type': 'pageview',
+ 'pathname': '/api/users',
+ 'hostname': 'api.example.com',
+ 'page_title': 'User API Endpoint',
+ });
+ }
+
+ @override
+ Widget build(BuildContext context) {
+ return MaterialApp(
+ home: Scaffold(
+ body: Center(
+ child: ElevatedButton(
+ onPressed: () {
+ // Track custom event
+ tracker.trackEvent({
+ 'type': 'custom_event',
+ 'pathname': '/checkout',
+ 'event_name': 'purchase',
+ 'properties': json.encode({'amount': 99.99, 'currency': 'USD'}),
+ });
+ },
+ child: Text('Track Event'),
+ ),
+ ),
+ ),
+ );
+ }
+}
+```
+ </Tabs.Tab>
+</Tabs>
+
+
+## Response Format
+
+### Success Response
+```json
+{
+ "success": true
+}
+```
+
+### Error Response
+```json
+{
+ "success": false,
+ "error": "Invalid API key",
+ "details": {
+ "fieldErrors": {},
+ "formErrors": ["Custom events require event_name"]
+ }
+}
+```
+
+## 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:
+
+```json
+{
+ "success": false,
+ "error": "Rate limit exceeded. Maximum 20 requests per second per API key."
+}
+```
+
+## 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>
+
+## 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
+- **JSON parsing errors**: For custom events, ensure properties field contains valid JSON
+- **Rate limit exceeded**: Reduce request frequency or implement request queuing with delays
+
diff --git a/docs/src/content/guides/hugo.mdx b/docs/src/content/guides/hugo.mdx
index f92434b93..70a1adc55 100644
--- a/docs/src/content/guides/hugo.mdx
+++ b/docs/src/content/guides/hugo.mdx
@@ -23,13 +23,13 @@ Paste your Rybbit tracking script into this new file:
```html
{{/* layouts/partials/rybbit-analytics.html */}}
{{ if not .Site.IsServer }} {{/* Only include in production builds */}}
- <script async defer src="https://your-rybbit-instance.com/api/script.js" data-site-id="YOUR_SITE_ID"></script>
+ <script async defer src="https://app.rybbit.io/api/script.js" data-site-id="YOUR_SITE_ID"></script>
{{ end }}
```
**Explanation:**
- `{{ if not .Site.IsServer }}`: This Hugo condition ensures that the tracking script is only included when you build your site for production (`hugo`) and not during local development (`hugo server`). This prevents tracking your own local page views.
-- Replace `https://your-rybbit-instance.com` and `YOUR_SITE_ID` with your actual details.
+- Replace `https://app.rybbit.io` and `YOUR_SITE_ID` with your actual details.
## 3. Include the Partial in Your Footer
diff --git a/docs/src/content/localhost-tracking.mdx b/docs/src/content/localhost-tracking.mdx
index a9cd50ebc..4f6605c04 100644
--- a/docs/src/content/localhost-tracking.mdx
+++ b/docs/src/content/localhost-tracking.mdx
@@ -9,7 +9,7 @@ By default, Rybbit validates tracking events come from your registered domain. D
**Important**: Remember to remove the API key before deploying to production!
</Callout>
-## Setup
+## Localhost Tracking
<Steps>
### Generate API Key
@@ -21,7 +21,7 @@ In your site dashboard: Settings β†’ API Key tab β†’ Generate API Key
```html
<script
defer
- src="https://your-rybbit-instance.com/api/script.js"
+ src="https://app.rybbit.io/api/script.js"
data-site-id="YOUR_SITE_ID"
data-api-key="rb_your_api_key_here">
</script>
@@ -37,13 +37,17 @@ In your site dashboard: Settings β†’ API Key tab β†’ Generate API Key
<!-- Production: NO API KEY -->
<script
defer
- src="https://your-rybbit-instance.com/api/script.js"
+ src="https://app.rybbit.io/api/script.js"
data-site-id="YOUR_SITE_ID">
</script>
```
</Steps>
+## Server-Side & Mobile Tracking
+
+For server-side applications, mobile apps, or API-based tracking, see the dedicated [API](/api) documentation.
+
## Best Practice: Environment Variables
Use conditional loading to automatically handle development vs production:
@@ -56,7 +60,7 @@ export function Analytics() {
return (
<script
defer
- src="https://your-rybbit-instance.com/api/script.js"
+ src="https://app.rybbit.io/api/script.js"
data-site-id={process.env.NEXT_PUBLIC_RYBBIT_SITE_ID}
{...(isDev && { 'data-api-key': process.env.NEXT_PUBLIC_RYBBIT_API_KEY })}
/>
@@ -68,7 +72,7 @@ export function Analytics() {
// Vanilla JS example
const script = document.createElement('script');
script.defer = true;
-script.src = 'https://your-rybbit-instance.com/api/script.js';
+script.src = 'https://app.rybbit.io/api/script.js';
script.setAttribute('data-site-id', 'YOUR_SITE_ID');
// Only add API key in development
diff --git a/memory-bank/activeContext.md b/memory-bank/activeContext.md
index e12fffe03..7d8cefa7c 100644
--- a/memory-bank/activeContext.md
+++ b/memory-bank/activeContext.md
@@ -29,3 +29,16 @@ This file tracks the project's current status, including recent changes, current
- **Solution**: Added form.reset() and setUseProperties(false) after successful submission in onSubmit function
- **Files Modified**: [`client/src/app/[site]/goals/components/GoalFormModal.tsx`](client/src/app/[site]/goals/components/GoalFormModal.tsx:162)
- **Impact**: Form now properly clears all fields and state after successful goal creation/editing
+
+[2025-06-19 19:29:31] - **COMPLETED: API Documentation Language Examples Review and Fixes**
+
+- **Task**: Review and fix potential issues in language examples in API documentation
+- **Status**: βœ… COMPLETED
+- **Key Issues Addressed**:
+ 1. Screen pixel type inconsistencies across mobile platforms
+ 2. Deprecated iOS UIScreen.main API usage
+ 3. Poor Flutter app launch event tracking placement
+ 4. Inconsistent example data between platforms
+ 5. Poor API key handling in Swift example
+- **Impact**: All mobile platform examples now use consistent logical pixels, modern APIs, and standardized example data
+- **Files Modified**: [`docs/src/content/api.mdx`](docs/src/content/api.mdx:78)
diff --git a/memory-bank/decisionLog.md b/memory-bank/decisionLog.md
index b9c4266f4..9778ed982 100644
--- a/memory-bank/decisionLog.md
+++ b/memory-bank/decisionLog.md
@@ -188,3 +188,47 @@ This decision was made to:
- New installations will have better performance by default
- Reduced bandwidth usage for users who don't need performance metrics
- More granular control over tracking features
+
+[2025-06-19 19:29:17] - **API Documentation Mobile Platform Consistency**
+
+## Decision
+
+Standardized mobile platform examples in API documentation to use logical pixels consistently and modernized deprecated APIs across Swift, Kotlin, and Flutter examples.
+
+## Rationale
+
+This decision was made to:
+
+- Ensure consistency across all mobile platform examples in the API documentation
+- Replace deprecated iOS APIs with modern alternatives to prevent future compatibility issues
+- Clarify pixel type expectations for mobile developers to prevent implementation confusion
+- Improve code quality and best practices in documentation examples
+- Standardize example data across all platforms for better learning experience
+
+## Implementation Details
+
+- **Screen Pixel Type Clarification**: Updated API parameter documentation to specify "logical pixels (density-independent pixels)" for screenWidth/screenHeight parameters
+- **Swift Example Modernization**:
+ - Replaced deprecated `UIScreen.main` with modern `UIWindowScene.screen` approach with proper fallback
+ - Added API key validation to prevent empty string errors
+ - Standardized example data to match server-side examples
+- **Kotlin Example Updates**:
+ - Changed from physical pixels to logical pixels using `resources.displayMetrics.density` conversion
+ - Updated example data for consistency across platforms
+- **Flutter Example Improvements**:
+ - Changed from physical pixels to logical pixels using `MediaQuery.of(context).devicePixelRatio`
+ - Moved app launch tracking from `build()` method to `initState()` to prevent multiple triggers
+ - Changed from StatelessWidget to StatefulWidget for proper lifecycle management
+ - Updated example data to match other platforms
+
+## Files Modified
+
+- [`docs/src/content/api.mdx`](docs/src/content/api.mdx:78) - API parameter documentation and all mobile platform examples
+
+## Impact
+
+- Improved consistency and accuracy across all mobile platform documentation
+- Modernized deprecated APIs to ensure future compatibility
+- Clarified pixel type expectations to prevent developer confusion
+- Enhanced code quality and best practices in documentation examples
+- Provided standardized learning experience across all supported platforms
diff --git a/memory-bank/progress.md b/memory-bank/progress.md
index c0b40ab7d..49635e63b 100644
--- a/memory-bank/progress.md
+++ b/memory-bank/progress.md
@@ -233,3 +233,25 @@ This file tracks the project's progress using a task list format.
- Conditional script attribute generation (`data-web-vitals="true"` only when enabled)
- Consistent with existing opt-in behavior (disabled by default)
- **Impact**: Users can now easily enable Web Vitals performance metrics collection through the ScriptBuilder UI, matching the functionality documented in the script documentation
+
+[2025-06-19 19:28:32] - **COMPLETED: API Documentation Language Examples Fixes**
+
+- **Task**: Fix potential issues in language examples in API documentation
+- **Status**: βœ… COMPLETED
+- **Issues Fixed**:
+ 1. **Screen Pixel Type Clarification**: Updated API documentation to specify "logical pixels (density-independent pixels)" for screenWidth/screenHeight parameters
+ 2. **Swift Example Modernization**:
+ - Replaced deprecated `UIScreen.main` with modern `UIWindowScene.screen` approach
+ - Added proper API key validation to prevent empty string errors
+ - Updated example data to match server-side examples for consistency
+ 3. **Kotlin Example Consistency**:
+ - Changed from physical pixels to logical pixels using density conversion
+ - Updated example data to match server-side examples
+ 4. **Flutter Example Improvements**:
+ - Changed from physical pixels to logical pixels using devicePixelRatio
+ - Moved app launch tracking from `build()` method to `initState()` to prevent multiple triggers
+ - Updated example data to match server-side examples
+ - Changed from StatelessWidget to StatefulWidget for proper lifecycle management
+- **Files Modified**:
+ - [`docs/src/content/api.mdx`](docs/src/content/api.mdx:78) - API parameter documentation and all mobile platform examples
+- **Impact**: Improved consistency across platform examples, modernized deprecated APIs, and clarified pixel type expectations for mobile developers
diff --git a/server/package-lock.json b/server/package-lock.json
index c35fbbed6..e10d1c8b6 100644
--- a/server/package-lock.json
+++ b/server/package-lock.json
@@ -11,6 +11,7 @@
"@clickhouse/client": "1.11.1",
"@fastify/cors": "11.0.1",
"@fastify/one-line-logger": "2.0.2",
+ "@fastify/rate-limit": "^10.3.0",
"@fastify/static": "8.1.1",
"@maxmind/geoip2-node": "6.1.0",
"@rybbit/shared": "file:../shared",
@@ -1241,6 +1242,26 @@
"ipaddr.js": "^2.1.0"
}
},
+ "node_modules/@fastify/rate-limit": {
+ "version": "10.3.0",
+ "resolved": "https://registry.npmjs.org/@fastify/rate-limit/-/rate-limit-10.3.0.tgz",
+ "integrity": "sha512-eIGkG9XKQs0nyynatApA3EVrojHOuq4l6fhB4eeCk4PIOeadvOJz9/4w3vGI44Go17uaXOWEcPkaD8kuKm7g6Q==",
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/fastify"
+ },
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/fastify"
+ }
+ ],
+ "dependencies": {
+ "@lukeed/ms": "^2.0.2",
+ "fastify-plugin": "^5.0.0",
+ "toad-cache": "^3.7.0"
+ }
+ },
"node_modules/@fastify/send": {
"version": "3.3.1",
"resolved": "https://registry.npmjs.org/@fastify/send/-/send-3.3.1.tgz",
diff --git a/server/package.json b/server/package.json
index 1067d71be..6cda4f4d8 100644
--- a/server/package.json
+++ b/server/package.json
@@ -24,6 +24,7 @@
"@clickhouse/client": "1.11.1",
"@fastify/cors": "11.0.1",
"@fastify/one-line-logger": "2.0.2",
+ "@fastify/rate-limit": "^10.3.0",
"@fastify/static": "8.1.1",
"@maxmind/geoip2-node": "6.1.0",
"@rybbit/shared": "file:../shared",
diff --git a/server/src/lib/rateLimiter.ts b/server/src/lib/rateLimiter.ts
new file mode 100644
index 000000000..07775e8ed
--- /dev/null
+++ b/server/src/lib/rateLimiter.ts
@@ -0,0 +1,53 @@
+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);
+}
\ No newline at end of file
diff --git a/server/src/tracker/channelExamples.ts b/server/src/tracker/channelExamples.ts
deleted file mode 100644
index 40b2a10c1..000000000
--- a/server/src/tracker/channelExamples.ts
+++ /dev/null
@@ -1,175 +0,0 @@
-import { getChannel, getChannelDetails } from "./getChannel.js";
-import { getSourceType, getMediumType, isPaidTraffic } from "./const.js";
-
-/**
- * Examples of how to use the enhanced channel detection functions
- */
-
-// Example 1: Basic channel detection
-export function exampleBasicChannelDetection() {
- const examples = [
- {
- referrer: "https://google.com/search?q=analytics",
- querystring: "",
- expected: "Organic Search",
- },
- {
- referrer: "https://facebook.com",
- querystring:
- "utm_source=facebook&utm_medium=social&utm_campaign=awareness",
- expected: "Organic Social",
- },
- {
- referrer: "",
- querystring:
- "utm_source=google&utm_medium=cpc&utm_campaign=brand&gclid=123",
- expected: "Paid Search",
- },
- {
- referrer: "https://instagram.com",
- querystring:
- "utm_source=instagram&utm_medium=influencer&utm_campaign=creator_collab",
- expected: "Influencer",
- },
- ];
-
- examples.forEach(({ referrer, querystring, expected }) => {
- const channel = getChannel(referrer, querystring);
- console.log(`Channel: ${channel} (Expected: ${expected})`);
- });
-}
-
-// Example 2: Detailed channel analysis
-export function exampleDetailedAnalysis() {
- const referrer = "https://youtube.com/watch?v=abc123";
- const querystring =
- "utm_source=youtube&utm_medium=video&utm_campaign=product_demo";
-
- const details = getChannelDetails(referrer, querystring);
-
- console.log("Detailed Analysis:", {
- channel: details.channel, // "Organic Video"
- sourceType: details.sourceType, // "video"
- mediumType: details.mediumType, // "video"
- isPaid: details.isPaid, // false
- isMobile: details.isMobile, // false
- source: details.details.source, // "youtube"
- medium: details.details.medium, // "video"
- campaign: details.details.campaign, // "product_demo"
- });
-}
-
-// Example 3: Mobile app tracking
-export function exampleMobileAppTracking() {
- const mobileExamples = [
- {
- referrer: "",
- querystring: "utm_source=com.instagram.android&utm_medium=social",
- description: "Instagram Android app",
- },
- {
- referrer: "",
- querystring: "utm_source=com.google.android.youtube&utm_medium=video",
- description: "YouTube Android app",
- },
- {
- referrer: "",
- querystring: "utm_source=com.nytimes.android&utm_medium=news",
- description: "NY Times Android app",
- },
- ];
-
- mobileExamples.forEach(({ referrer, querystring, description }) => {
- const details = getChannelDetails(referrer, querystring);
- console.log(`${description}:`, {
- channel: details.channel,
- isMobile: details.isMobile,
- sourceType: details.sourceType,
- });
- });
-}
-
-// Example 4: Paid vs Organic detection
-export function examplePaidVsOrganic() {
- const trafficExamples = [
- "utm_medium=cpc",
- "utm_medium=social",
- "utm_medium=influencer&utm_source=sponsored_post",
- "utm_medium=email",
- "gclid=abc123",
- "utm_medium=display&utm_campaign=retargeting",
- ];
-
- trafficExamples.forEach((querystring) => {
- const details = getChannelDetails("", querystring);
- console.log(
- `${querystring} -> ${details.channel} (Paid: ${details.isPaid})`
- );
- });
-}
-
-// Example 5: Using utility functions directly
-export function exampleUtilityFunctions() {
- // Source type detection
- console.log("Source Types:");
- console.log("google.com ->", getSourceType("google.com")); // "search"
- console.log("facebook.com ->", getSourceType("facebook.com")); // "social"
- console.log("youtube.com ->", getSourceType("youtube.com")); // "video"
- console.log("amazon.com ->", getSourceType("amazon.com")); // "shopping"
-
- // Medium type detection
- console.log("\nMedium Types:");
- console.log("cpc ->", getMediumType("cpc")); // "cpc"
- console.log("social ->", getMediumType("social")); // "social"
- console.log("influencer ->", getMediumType("influencer")); // "influencer"
- console.log("email ->", getMediumType("email")); // "email"
-
- // Paid traffic detection
- console.log("\nPaid Traffic Detection:");
- console.log("cpc + google ->", isPaidTraffic("cpc", "google")); // true
- console.log("social + facebook ->", isPaidTraffic("social", "facebook")); // false
- console.log(
- "sponsored + instagram ->",
- isPaidTraffic("sponsored", "instagram")
- ); // true
-}
-
-// Example 6: Advanced campaign analysis
-export function exampleCampaignAnalysis() {
- const campaigns = [
- {
- name: "Google Ads Campaign",
- referrer: "",
- querystring:
- "utm_source=google&utm_medium=cpc&utm_campaign=brand_keywords&gclid=123",
- },
- {
- name: "Influencer Partnership",
- referrer: "https://instagram.com",
- querystring:
- "utm_source=instagram&utm_medium=influencer&utm_campaign=summer_collection&utm_content=creator_jane",
- },
- {
- name: "Content Marketing",
- referrer: "https://techcrunch.com",
- querystring:
- "utm_source=techcrunch&utm_medium=content&utm_campaign=thought_leadership",
- },
- {
- name: "Event Traffic",
- referrer: "",
- querystring:
- "utm_source=conference&utm_medium=event&utm_campaign=tech_summit_2024",
- },
- ];
-
- campaigns.forEach(({ name, referrer, querystring }) => {
- const details = getChannelDetails(referrer, querystring);
- console.log(`\n${name}:`);
- console.log(` Channel: ${details.channel}`);
- console.log(` Source Type: ${details.sourceType}`);
- console.log(` Medium Type: ${details.mediumType}`);
- console.log(` Is Paid: ${details.isPaid}`);
- console.log(` Campaign: ${details.details.campaign}`);
- });
-}
diff --git a/server/src/tracker/pageviewQueue.ts b/server/src/tracker/pageviewQueue.ts
index 06b894c9e..f8d4fbafd 100644
--- a/server/src/tracker/pageviewQueue.ts
+++ b/server/src/tracker/pageviewQueue.ts
@@ -1,10 +1,10 @@
import { DateTime } from "luxon";
import { clickhouse } from "../db/clickhouse/clickhouse.js";
import { getLocation } from "../db/geolocation/geolocation.js";
-import { TrackingPayload } from "../types.js";
import { getDeviceType } from "../utils.js";
import { getChannel } from "./getChannel.js";
import { clearSelfReferrer, getAllUrlParams } from "./trackingUtils.js";
+import { TrackingPayload } from "./types.js";
type TotalPayload = TrackingPayload & {
userId: string;
diff --git a/server/src/tracker/trackEvent.ts b/server/src/tracker/trackEvent.ts
index d36b6e567..0b1899cd8 100644
--- a/server/src/tracker/trackEvent.ts
+++ b/server/src/tracker/trackEvent.ts
@@ -15,77 +15,90 @@ import { getDeviceType, normalizeOrigin } from "../utils.js";
import { pageviewQueue } from "./pageviewQueue.js";
import { siteConfig } from "../lib/siteConfig.js";
import { DISABLE_ORIGIN_CHECK } from "./const.js";
+import { apiKeyRateLimiter } from "../lib/rateLimiter.js";
// Define Zod schema for validation
export const trackingPayloadSchema = z.discriminatedUnion("type", [
- z.object({
- type: z.literal("pageview"),
- site_id: z.string().min(1),
- hostname: z.string().max(253).optional(),
- pathname: z.string().max(2048).optional(),
- querystring: z.string().max(2048).optional(),
- screenWidth: z.number().int().positive().optional(),
- screenHeight: z.number().int().positive().optional(),
- language: z.string().max(35).optional(),
- page_title: z.string().max(512).optional(),
- referrer: z.string().max(2048).optional(),
- event_name: z.string().max(256).optional(),
- properties: z.string().max(2048).optional(),
- user_id: z.string().max(255).optional(),
- api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
- }),
- z.object({
- type: z.literal("custom_event"),
- site_id: z.string().min(1),
- hostname: z.string().max(253).optional(),
- pathname: z.string().max(2048).optional(),
- querystring: z.string().max(2048).optional(),
- screenWidth: z.number().int().positive().optional(),
- screenHeight: z.number().int().positive().optional(),
- language: z.string().max(35).optional(),
- page_title: z.string().max(512).optional(),
- referrer: z.string().max(2048).optional(),
- event_name: z.string().min(1).max(256),
- properties: z
- .string()
- .max(2048)
- .refine(
- (val) => {
- try {
- JSON.parse(val);
- return true;
- } catch (e) {
- return false;
- }
- },
- { message: "Properties must be a valid JSON string" }
- )
- .optional(), // Optional but must be valid JSON if present
- user_id: z.string().max(255).optional(),
- api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
- }),
- z.object({
- type: z.literal("performance"),
- site_id: z.string().min(1),
- hostname: z.string().max(253).optional(),
- pathname: z.string().max(2048).optional(),
- querystring: z.string().max(2048).optional(),
- screenWidth: z.number().int().positive().optional(),
- screenHeight: z.number().int().positive().optional(),
- language: z.string().max(35).optional(),
- page_title: z.string().max(512).optional(),
- referrer: z.string().max(2048).optional(),
- event_name: z.string().max(256).optional(),
- properties: z.string().max(2048).optional(),
- user_id: z.string().max(255).optional(),
- api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
- // Performance metrics (can be null if not collected)
- lcp: z.number().positive().nullable().optional(),
- cls: z.number().min(0).nullable().optional(),
- inp: z.number().positive().nullable().optional(),
- fcp: z.number().positive().nullable().optional(),
- ttfb: z.number().positive().nullable().optional(),
- }),
+ z
+ .object({
+ type: z.literal("pageview"),
+ site_id: z.string().min(1),
+ hostname: z.string().max(253).optional(),
+ pathname: z.string().max(2048).optional(),
+ querystring: z.string().max(2048).optional(),
+ screenWidth: z.number().int().positive().optional(),
+ screenHeight: z.number().int().positive().optional(),
+ language: z.string().max(35).optional(),
+ page_title: z.string().max(512).optional(),
+ referrer: z.string().max(2048).optional(),
+ event_name: z.string().max(256).optional(),
+ properties: z.string().max(2048).optional(),
+ user_id: z.string().max(255).optional(),
+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
+ ip_address: z.string().ip().optional(), // Custom IP for geolocation
+ user_agent: z.string().max(512).optional(), // Custom user agent
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("custom_event"),
+ site_id: z.string().min(1),
+ hostname: z.string().max(253).optional(),
+ pathname: z.string().max(2048).optional(),
+ querystring: z.string().max(2048).optional(),
+ screenWidth: z.number().int().positive().optional(),
+ screenHeight: z.number().int().positive().optional(),
+ language: z.string().max(35).optional(),
+ page_title: z.string().max(512).optional(),
+ referrer: z.string().max(2048).optional(),
+ event_name: z.string().min(1).max(256),
+ properties: z
+ .string()
+ .max(2048)
+ .refine(
+ (val) => {
+ try {
+ JSON.parse(val);
+ return true;
+ } catch (e) {
+ return false;
+ }
+ },
+ { message: "Properties must be a valid JSON string" }
+ )
+ .optional(), // Optional but must be valid JSON if present
+ user_id: z.string().max(255).optional(),
+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
+ ip_address: z.string().ip().optional(), // Custom IP for geolocation
+ user_agent: z.string().max(512).optional(), // Custom user agent
+ })
+ .strict(),
+ z
+ .object({
+ type: z.literal("performance"),
+ site_id: z.string().min(1),
+ hostname: z.string().max(253).optional(),
+ pathname: z.string().max(2048).optional(),
+ querystring: z.string().max(2048).optional(),
+ screenWidth: z.number().int().positive().optional(),
+ screenHeight: z.number().int().positive().optional(),
+ language: z.string().max(35).optional(),
+ page_title: z.string().max(512).optional(),
+ referrer: z.string().max(2048).optional(),
+ event_name: z.string().max(256).optional(),
+ properties: z.string().max(2048).optional(),
+ user_id: z.string().max(255).optional(),
+ api_key: z.string().max(35).optional(), // rb_ prefix + 32 hex chars
+ ip_address: z.string().ip().optional(), // Custom IP for geolocation
+ user_agent: z.string().max(512).optional(), // Custom user agent
+ // Performance metrics (can be null if not collected)
+ lcp: z.number().positive().nullable().optional(),
+ cls: z.number().min(0).nullable().optional(),
+ inp: z.number().positive().nullable().optional(),
+ fcp: z.number().positive().nullable().optional(),
+ ttfb: z.number().positive().nullable().optional(),
+ })
+ .strict(),
]);
// Update session for both pageviews and events
@@ -143,22 +156,37 @@ async function updateSession(
await db.insert(activeSessions).values(insertData);
}
-// Process tracking event and add to queue
-async function processTrackingEvent(
- payload: TotalTrackingPayload,
- existingSession: any | null,
- isPageview: boolean = true
-): Promise<void> {
- // If session exists, use its ID instead of generated one
- if (existingSession) {
- payload.sessionId = existingSession.sessionId;
+/**
+ * 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
+ */
+async function validateApiKey(siteId: string, apiKey?: string) {
+ if (!apiKey) {
+ return { success: false, error: null };
}
- // Add to queue for processing
- await pageviewQueue.add(payload);
+ try {
+ await siteConfig.ensureInitialized();
+ const numericSiteId =
+ typeof siteId === "string" ? parseInt(siteId, 10) : siteId;
+ const site = await siteConfig.getSiteConfig(numericSiteId);
+
+ if (!site) {
+ return { success: false, error: "Site not found" };
+ }
- // Update session data
- await updateSession(payload, existingSession, isPageview);
+ if (site.apiKey && apiKey === site.apiKey) {
+ console.info(`[Tracking] Valid API key for site ${siteId}`);
+ return { success: true };
+ }
+
+ return { success: false, error: "Invalid API key" };
+ } catch (error) {
+ console.error("Error validating API key:", error);
+ return { success: false, error: "Failed to validate API key" };
+ }
}
/**
@@ -167,7 +195,7 @@ async function processTrackingEvent(
* @param requestOrigin The origin header from the request
* @returns An object with success status and optional error message
*/
-async function validateOrigin(siteId: string, requestOrigin?: string, apiKey?: string) {
+async function validateOrigin(siteId: string, requestOrigin?: string) {
try {
// If origin checking is disabled, return success
if (DISABLE_ORIGIN_CHECK) {
@@ -188,7 +216,7 @@ async function validateOrigin(siteId: string, requestOrigin?: string, apiKey?: s
// Get the site configuration
const site = await siteConfig.getSiteConfig(numericSiteId);
-
+
if (!site) {
return {
success: false,
@@ -205,17 +233,6 @@ async function validateOrigin(siteId: string, requestOrigin?: string, apiKey?: s
}
try {
- // Parse the origin into URL components
- const originUrl = new URL(requestOrigin);
-
- // Check if this is a request with valid API key
- if (apiKey && site.apiKey && apiKey === site.apiKey) {
- console.info(
- `[Tracking] Allowing API key authenticated request for site ${siteId} from origin: ${requestOrigin}`
- );
- return { success: true };
- }
-
// Get the domain associated with this site
const siteDomain = site.domain;
@@ -264,29 +281,67 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
// Use validated data
const validatedPayload = validationResult.data;
- // Validate that the request is coming from the expected origin
- const originValidation = await validateOrigin(
+ // First check if API key is provided and valid
+ const apiKeyValidation = await validateApiKey(
validatedPayload.site_id,
- request.headers.origin as string,
validatedPayload.api_key
);
- if (!originValidation.success) {
+ // If API key validation failed with an error, reject the request
+ if (apiKeyValidation.error) {
console.warn(
- `[Tracking] Request rejected for site ${validatedPayload.site_id}: ${originValidation.error}`
+ `[Tracking] Request rejected for site ${validatedPayload.site_id}: ${apiKeyValidation.error}`
);
return reply.status(403).send({
success: false,
- error: originValidation.error,
+ error: apiKeyValidation.error,
});
}
+ // Check rate limit for API key authenticated requests
+ if (apiKeyValidation.success && validatedPayload.api_key) {
+ if (!apiKeyRateLimiter.isAllowed(validatedPayload.api_key)) {
+ console.warn(
+ `[Tracking] Rate limit exceeded for API key ${validatedPayload.api_key} on site ${validatedPayload.site_id}`
+ );
+ return reply.status(429).send({
+ success: false,
+ error: "Rate limit exceeded. Maximum 20 requests per second per API key.",
+ });
+ }
+ }
+
+ // If no valid API key, validate origin
+ if (!apiKeyValidation.success) {
+ const originValidation = await validateOrigin(
+ validatedPayload.site_id,
+ request.headers.origin as string
+ );
+
+ if (!originValidation.success) {
+ console.warn(
+ `[Tracking] Request rejected for site ${validatedPayload.site_id}: ${originValidation.error}`
+ );
+ return reply.status(403).send({
+ success: false,
+ error: originValidation.error,
+ });
+ }
+ }
+
// Make sure the site config is loaded
await siteConfig.ensureInitialized();
// Check if bot blocking is enabled for this site and if the request is from a bot
- if (siteConfig.shouldBlockBots(validatedPayload.site_id)) {
- const userAgent = request.headers["user-agent"] as string;
+ // Skip bot check for API key authenticated requests
+ if (
+ !validatedPayload.api_key &&
+ siteConfig.shouldBlockBots(validatedPayload.site_id)
+ ) {
+ // Use custom user agent if provided, otherwise fall back to header
+ const userAgent =
+ validatedPayload.user_agent ||
+ (request.headers["user-agent"] as string);
if (userAgent && isbot(userAgent)) {
console.log(
`[Tracking] Bot request filtered for site ${validatedPayload.site_id} from User-Agent: ${userAgent}`
@@ -321,8 +376,13 @@ export async function trackEvent(request: FastifyRequest, reply: FastifyReply) {
payload.site_id
);
- // Process the event
- await processTrackingEvent(
+ if (existingSession) {
+ payload.sessionId = existingSession.sessionId;
+ }
+
+ // Add to queue for processing
+ pageviewQueue.add(payload);
+ await updateSession(
payload,
existingSession,
validatedPayload.type === "pageview"
diff --git a/server/src/tracker/trackingUtils.ts b/server/src/tracker/trackingUtils.ts
index c6af26637..781945e96 100644
--- a/server/src/tracker/trackingUtils.ts
+++ b/server/src/tracker/trackingUtils.ts
@@ -6,18 +6,14 @@ import { z } from "zod";
import { sitesOverLimit } from "../cron/monthly-usage-checker.js";
import { db } from "../db/postgres/postgres.js";
import { activeSessions } from "../db/postgres/schema.js";
-import { TrackingPayload } from "../types.js";
import { trackingPayloadSchema } from "./trackEvent.js";
import { siteConfig } from "../lib/siteConfig.js";
+import { TrackingPayload } from "./types.js";
-// Define extended payload types
-type BaseTrackingPayload = TrackingPayload & {
+export type TotalTrackingPayload = TrackingPayload & {
type?: string;
event_name?: string;
properties?: string;
-};
-
-export type TotalTrackingPayload = BaseTrackingPayload & {
userId: string;
timestamp: string;
sessionId: string;
@@ -121,10 +117,15 @@ export function createBasePayload(
eventType: "pageview" | "custom_event" | "performance" = "pageview",
validatedBody: ValidatedTrackingPayload
): TotalTrackingPayload {
- const userAgent = request.headers["user-agent"] || "";
- const ipAddress = getIpAddress(request);
+ // Use custom user agent if provided, otherwise fall back to header
+ const userAgent =
+ validatedBody.user_agent || request.headers["user-agent"] || "";
+ // Override IP if provided in payload
+ const ipAddress = validatedBody.ip_address || getIpAddress(request);
const siteId = validatedBody.site_id;
+ console.log("ipAddress", ipAddress);
+
// Use custom user ID if provided, otherwise generate one
const userId = validatedBody.user_id
? validatedBody.user_id.trim()
diff --git a/server/src/types.ts b/server/src/tracker/types.ts
similarity index 100%
rename from server/src/types.ts
rename to server/src/tracker/types.ts