### Make Scripts Executable and Run Setup Script (Bash)
Source: https://rybbit.com/docs/self-hosting
Makes all shell scripts in the current directory executable and then runs the Rybbit setup script. The setup script requires a domain name as an argument and can optionally accept a Mapbox token for 3D map visualizations.
```bash
chmod +x *.sh
./setup.sh your.domain.name
```
```bash
chmod +x *.sh
./setup.sh your.domain.name --mapbox-token YOUR_MAPBOX_TOKEN
```
--------------------------------
### Start Node.js Server
Source: https://rybbit.com/docs/proxy-guide/express
This section provides commands to start the Node.js server. It includes instructions for a basic start and using nodemon for development, which automatically restarts the server on file changes. Nodemon needs to be installed as a dev dependency.
```bash
node server.js
```
```bash
npm install -D nodemon
npx nodemon server.js
```
--------------------------------
### Complete Rybbit Script Configuration Example
Source: https://rybbit.com/docs/script
A comprehensive example of the Rybbit script tag, including site ID, skip and mask patterns, debouncing, privacy controls, and session replay sampling and SlimDOM options. This illustrates a full setup for session recording and analysis.
```html
```
--------------------------------
### Clone Rybbit Repository (Bash)
Source: https://rybbit.com/docs/self-hosting
Clones the Rybbit project repository from GitHub. This is a prerequisite for running the setup script. It requires Git to be installed on the server.
```bash
git clone https://github.com/rybbit-io/rybbit.git
cd rybbit
```
--------------------------------
### Start Astro Development Server
Source: https://rybbit.com/docs/proxy-guide/astro
Command to start the local development server for your Astro project. This allows you to preview your site and test the integration in real-time.
```bash
npm run dev
```
--------------------------------
### Start Rybbit Docker Services
Source: https://rybbit.com/docs/self-hosting-guides/self-hosting-manual
Commands to start Rybbit services using Docker Compose. It includes options to start all services (including Caddy) or specific services like backend, client, clickhouse, and postgres when Caddy is excluded.
```bash
# Start all services
docker compose up -d
# Or start specific services (without Caddy)
docker compose up -d backend client clickhouse postgres
```
--------------------------------
### Default Rybbit Tracking Script Installation
Source: https://rybbit.com/docs/proxy-guide
The standard method for adding Rybbit's tracking script directly to a website. This script is loaded from Rybbit's domain and may be blocked by ad blockers.
```html
```
--------------------------------
### Install caddy-ratelimit Plugin
Source: https://rybbit.com/docs/proxy-guide/caddy
Command to build Caddy with the caddy-ratelimit plugin. This is a prerequisite for using the rate limiting feature in Caddy.
```bash
xcaddy build --with github.com/mholt/caddy-ratelimit
```
--------------------------------
### Set Environment Variables for Caddy
Source: https://rybbit.com/docs/proxy-guide/caddy
Example of how to set environment variables for Caddy configuration. These variables, such as `DOMAIN` and `RYBBIT_HOST`, can be used to dynamically configure Caddy settings.
```bash
export DOMAIN=yourdomain.com
export RYBBIT_HOST=https://app.rybbit.io
caddy run
```
--------------------------------
### Cache Control Headers
Source: https://rybbit.com/docs/proxy-guide/get-started
Example cache headers demonstrating recommended durations for different types of Rybbit requests. Proper caching reduces server load and improves performance.
```http
Cache-Control: public, max-age=3600 # For scripts
Cache-Control: public, max-age=300 # For config
Cache-Control: no-store # For tracking POSTs
```
--------------------------------
### Create Site with Go
Source: https://rybbit.com/docs/api/organizations
This Go example uses the `net/http` package to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response body is then decoded.
```go
package main
import (
"bytes"
"encoding/json"
"net/http"
)
func main() {
organizationId := "org_123"
body := bytes.NewBuffer([]byte(`{
"domain": "example.com",
"name": "My Website",
"blockBots": true
}`))
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/organizations/"+organizationId+"/sites", body)
req.Header.Set("Authorization", "Bearer your_api_key_here")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
var data map[string]interface{}
json.NewDecoder(resp.Body).Decode(&data)
}
```
--------------------------------
### Create Site with .NET
Source: https://rybbit.com/docs/api/organizations
This .NET example uses the `HttpClient` class to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response is then read as a string.
```csharp
using System.Net.Http.Headers;
using System.Text;
var organizationId = "org_123";
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
var content = new StringContent(
"{\"domain\": \"example.com\", \"name\": \"My Website\", \"blockBots\": true}",
Encoding.UTF8,
"application/json"
);
var response = await client.PostAsync($"https://app.rybbit.io/api/organizations/{organizationId}/sites", content);
var data = await response.Content.ReadAsStringAsync();
```
--------------------------------
### Proxying Rybbit Tracking Script via Custom Domain
Source: https://rybbit.com/docs/proxy-guide
An example of how the Rybbit tracking script is included when proxied through your own domain. This makes tracking requests appear as first-party traffic.
```html
```
--------------------------------
### Create Site with Java
Source: https://rybbit.com/docs/api/organizations
This Java example uses the `java.net.http` package to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response is then processed.
```java
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
public class CreateSite {
public static void main(String[] args) throws Exception {
String organizationId = "org_123";
HttpClient client = HttpClient.newHttpClient();
String json = "{\"domain\": \"example.com\", \"name\": \"My Website\", \"blockBots\": true}";
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create("https://app.rybbit.io/api/organizations/" + organizationId + "/sites"))
.header("Authorization", "Bearer your_api_key_here")
.header("Content-Type", "application/json")
.POST(HttpRequest.BodyPublishers.ofString(json))
.build();
HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString());
System.out.println(response.body());
}
}
```
--------------------------------
### Create Site with Python
Source: https://rybbit.com/docs/api/organizations
This Python example uses the `requests` library to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response is then parsed as JSON.
```python
import requests
organization_id = 'org_123'
response = requests.post(
f'https://app.rybbit.io/api/organizations/{organization_id}/sites',
json={
'domain': 'example.com',
'name': 'My Website',
'blockBots': True
},
headers={
'Authorization': 'Bearer your_api_key_here'
}
)
data = response.json()
```
--------------------------------
### Create Site with JavaScript
Source: https://rybbit.com/docs/api/organizations
This JavaScript example uses the `fetch` API to create a site. It constructs the request with the necessary headers, including authorization and content type, and sends a POST request with the site data in JSON format. The response is then parsed as JSON.
```javascript
const organizationId = 'org_123';
const response = await fetch(
`https://app.rybbit.io/api/organizations/${organizationId}/sites`,
{
method: 'POST',
headers: {
'Authorization': 'Bearer your_api_key_here',
'Content-Type': 'application/json'
},
body: JSON.stringify({
domain: 'example.com',
name: 'My Website',
blockBots: true
})
}
);
const data = await response.json();
```
--------------------------------
### Docker Compose: Start Services (no webserver)
Source: https://rybbit.com/docs/managing-your-installation
Starts services in detached mode without the webserver. This is used if you initially set up Rybbit with the --no-webserver option.
```docker
docker compose up -d
```
--------------------------------
### Get Organization Members
Source: https://rybbit.com/docs/api/organizations
This example shows how to retrieve all members of an organization using a GET request. It specifies the API endpoint and indicates that the request requires membership in the organization to be successful.
```text
GET /api/organizations/:organizationId/members
```
--------------------------------
### Create Site with cURL
Source: https://rybbit.com/docs/api/organizations
This cURL example demonstrates how to create a site by sending a POST request to the Rybbit API. It includes setting the authorization header and content type, along with the request body containing site details. The response is not explicitly handled in this example.
```bash
curl -X POST "https://app.rybbit.io/api/organizations/org_123/sites" \
-H "Authorization: Bearer your_api_key_here" \
-H "Content-Type: application/json" \
-d '{"domain": "example.com", "name": "My Website", "blockBots": true}'
```
--------------------------------
### Docker Compose: Start Services (with webserver)
Source: https://rybbit.com/docs/managing-your-installation
Starts services in detached mode, including the webserver profile. This is typically used if you initially set up Rybbit with the default webserver.
```docker
docker compose --profile with-webserver up -d
```
--------------------------------
### Create Site with Rust
Source: https://rybbit.com/docs/api/organizations
This Rust example uses the `reqwest` crate to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response is then parsed as JSON.
```rust
use reqwest;
use serde_json::json;
#[tokio::main]
async fn main() -> Result<(), Box> {
let organization_id = "org_123";
let client = reqwest::Client::new();
let res = client
.post(format!("https://app.rybbit.io/api/organizations/{}/sites", organization_id))
.header("Authorization", "Bearer your_api_key_here")
.json(&serde_json::json!({
"domain": "example.com",
"name": "My Website",
"blockBots": true
}))
.send()
.await?;
let data: serde_json::Value = res.json().await?;
println!("{:?}", data);
Ok(()
}
```
--------------------------------
### Create Site with PHP
Source: https://rybbit.com/docs/api/organizations
This PHP example uses cURL to create a site. It initializes a cURL session, sets the URL, headers (including authorization and content type), and the POST data. The response is then decoded from JSON.
```php
$organizationId = 'org_123';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://app.rybbit.io/api/organizations/{$organizationId}/sites");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode([
'domain' => 'example.com',
'name' => 'My Website',
'blockBots' => true
]));
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Authorization: Bearer your_api_key_here',
'Content-Type: application/json'
]);
$response = curl_exec($ch);
curl_close($ch);
$data = json_decode($response, true);
```
--------------------------------
### Create Site with Ruby
Source: https://rybbit.com/docs/api/organizations
This Ruby example uses the `net/http` and `json` libraries to create a site. It constructs a POST request with the necessary headers, including authorization and content type, and sends the site data as JSON. The response is then parsed as JSON.
```ruby
require 'net/http'
require 'json'
organization_id = 'org_123'
uri = URI("https://app.rybbit.io/api/organizations/#{organization_id}/sites")
req = Net::HTTP::Post.new(uri)
req['Authorization'] = 'Bearer your_api_key_here'
req['Content-Type'] = 'application/json'
req.body = {
domain: 'example.com',
name: 'My Website',
blockBots: true
}.to_json
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
```
--------------------------------
### Install http-proxy-middleware using npm or yarn
Source: https://rybbit.com/docs/proxy-guide/express
Installs the necessary http-proxy-middleware package for setting up a proxy in an Express.js application. This package is essential for routing requests to external services like Rybbit.
```bash
npm install http-proxy-middleware
```
```bash
yarn add http-proxy-middleware
```
--------------------------------
### Date-based Time Parameter Example
Source: https://rybbit.com/docs/api/getting-started
An example of how to specify a date range for analytics data using start date, end date, and timezone parameters. This is suitable for querying historical data.
```URL
?start_date=2024-01-01&end_date=2024-01-31&time_zone=America/New_York
```
--------------------------------
### Setup Script Command and Options
Source: https://rybbit.com/docs/self-hosting-guides/self-hosting-advanced
The Rybbit setup script accepts a domain name and various options to customize the self-hosting environment. Key options include disabling the built-in webserver, setting custom ports for backend and client services, and providing a Mapbox API token for enhanced map visualizations.
```bash
./setup.sh [options]
Available options:
* --no-webserver: Disable the built-in Caddy webserver
* --backend-port : Set custom host port for backend (default: 3001)
* --client-port : Set custom host port for client (default: 3002)
* --mapbox-token : Set Mapbox API token (optional but recommended for globe visualizations)
* --help: Show help message
Examples:
# With Mapbox token
./setup.sh tracking.example.com --mapbox-token YOUR_MAPBOX_TOKEN
# Custom ports with built-in webserver
./setup.sh tracking.example.com --backend-port 8080 --client-port 8081
# Custom ports with your own webserver
./setup.sh tracking.example.com --no-webserver --backend-port 8080 --client-port 8081
```
--------------------------------
### Install Certbot for Nginx (Shell)
Source: https://rybbit.com/docs/self-hosting-guides/custom-nginx
Installs Certbot and its Nginx plugin on Ubuntu/Debian and CentOS/RHEL systems. Certbot is a tool used to automate the process of obtaining and renewing SSL/TLS certificates from Let's Encrypt.
```shell
# Ubuntu/Debian
sudo apt update
sudo apt install certbot python3-certbot-nginx
# CentOS/RHEL
sudo yum install certbot python3-certbot-nginx
```
--------------------------------
### Express.js Proxy Setup for All Rybbit Endpoints (JavaScript)
Source: https://rybbit.com/docs/proxy-guide/express
Configures Express.js to proxy all requests starting with '/analytics' to the Rybbit host. It rewrites the path and forwards essential headers like client IP for accurate tracking. This setup handles the main analytics endpoints and a specific site configuration endpoint.
```javascript
// server.js
require('dotenv').config();
const express = require('express');
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
const RYBBIT_HOST = process.env.RYBBIT_HOST || 'https://app.rybbit.io';
// Rybbit Analytics Proxy
// Proxy all /analytics/* requests to Rybbit
app.use('/analytics', createProxyMiddleware({
target: RYBBIT_HOST,
changeOrigin: true,
pathRewrite: {
'^/analytics': '/api', // Rewrite /analytics/script.js to /api/script.js
},
onProxyReq: (proxyReq, req, res) => {
// Forward client IP for accurate geolocation
const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
proxyReq.setHeader('X-Forwarded-For', clientIp);
proxyReq.setHeader('X-Real-IP', clientIp);
},
logLevel: 'warn',
}));
// Exception for site config endpoint (different path structure)
app.use('/analytics/site/tracking-config', createProxyMiddleware({
target: RYBBIT_HOST,
changeOrigin: true,
pathRewrite: {
'^/analytics': '', // Keep /site/tracking-config path
},
onProxyReq: (proxyReq, req, res) => {
const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
proxyReq.setHeader('X-Forwarded-For', clientIp);
proxyReq.setHeader('X-Real-IP', clientIp);
},
}));
// Your other routes
app.get('/', (req, res) => {
res.send('Hello World');
});
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
--------------------------------
### Create Path Goal using Go (net/http)
Source: https://rybbit.com/docs/api/stats/goals
This Go code snippet demonstrates creating a 'path' goal by making an HTTP POST request. It marshals the goal configuration into JSON and sets the necessary headers, including authorization. The response is decoded into a map.
```go
import (
"bytes"
"encoding/json"
"net/http"
)
body := map[string]interface{}{
"name": "Checkout Complete",
"goalType": "path",
"config": map[string]string{
"pathPattern": "/checkout/success",
},
}
jsonBody, _ := json.Marshal(body)
req, _ := http.NewRequest("POST", "https://app.rybbit.io/api/sites/1/goals23", bytes.NewBuffer(jsonBody))
req.Header.Set("Authorization", "Bearer your_api_key_here")
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
resp, _ := client.Do(req)
defer resp.Body.Close()
var data map[string]interface{}
json.NewDecoder(resp.Body).Decode(&data)
```
--------------------------------
### Get Event Properties with cURL
Source: https://rybbit.com/docs/api/stats/events
This cURL example retrieves event properties from the specified API endpoint. It uses a GET request with query parameters for filtering events by name and date range, including an authorization header for authentication. The response is expected to be in JSON format.
```bash
curl -X GET "https://app.rybbit.io/api/sites/1/events/properties23?event_name=signup&start_date=2024-01-01&end_date=2024-01-31" \
-H "Authorization: Bearer your_api_key_here"
```
--------------------------------
### Get Sessions List - .NET (HttpClient)
Source: https://rybbit.com/docs/api/stats/sessions
Retrieves a paginated list of sessions using .NET's HttpClient. This example demonstrates setting the Authorization header and making a GET request asynchronously. The response content is read as a string.
```csharp
using var client = new HttpClient();
client.DefaultRequestHeaders.Add("Authorization", "Bearer your_api_key_here");
var response = await client.GetAsync("https://app.rybbit.io/api/sites/1/sessions23?page=1&limit=20&start_date=2024-01-01&end_date=2024-01-31");
var data = await response.Content.ReadAsStringAsync();
```
--------------------------------
### Express.js Proxy Setup for Rybbit (TypeScript)
Source: https://rybbit.com/docs/proxy-guide/express
Implements a Rybbit proxy using Express.js and http-proxy-middleware in TypeScript. This example defines proxy options separately for reusability and demonstrates how to proxy different Rybbit endpoints while forwarding client IP information.
```typescript
// server.ts
import 'dotenv/config';
import express, { Request, Response } from 'express';
import { createProxyMiddleware, Options } from 'http-proxy-middleware';
const app = express();
const RYBBIT_HOST = process.env.RYBBIT_HOST || 'https://app.rybbit.io';
const proxyOptions: Options = {
target: RYBBIT_HOST,
changeOrigin: true,
pathRewrite: {
'^/analytics': '/api',
},
onProxyReq: (proxyReq, req, res) => {
const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;
proxyReq.setHeader('X-Forwarded-For', clientIp as string);
proxyReq.setHeader('X-Real-IP', clientIp as string);
},
logLevel: 'warn',
};
app.use('/analytics', createProxyMiddleware(proxyOptions));
app.use('/analytics/site/tracking-config', createProxyMiddleware({
target: RYBBIT_HOST,
changeOrigin: true,
pathRewrite: {
'^/analytics': '',
},
onProxyReq: proxyOptions.onProxyReq,
}));
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
```
--------------------------------
### SDK Initialization
Source: https://rybbit.com/docs/sdks/web
Details on how to initialize the Rybbit SDK using `rybbit.init()`. Includes required and optional configuration parameters.
```APIDOC
## Initialization
`rybbit.init()` **must** be called once before any other tracking methods (`pageview`, `event`, etc.) can be used. Attempting to call other methods before `init` will result in errors or no tracking.
### Syntax
```javascript
async rybbit.init(config: RybbitConfig): Promise;
```
### Example
```javascript
import rybbit from "@rybbit/js";
await rybbit.init({
analyticsHost: "https://app.rybbit.io/api",
siteId: "1",
});
```
### Configuration Options
#### Required Options
Option| Type| Description
---|---|---
`analyticsHost`| `string`| URL of your Rybbit analytics instance (e.g., `https://rybbit.yourdomain.com/api`).
`siteId`| `string | number`| The Site ID for your website obtained from your Rybbit instance.
#### Local Configuration Options
These options are configured in your code and control SDK behavior locally:
Option| Type| Default| Description
---|---|---|---
`debounce`| `number`| `500`| Debounce time in milliseconds for tracking pageviews after route changes. Set to `0` to disable debouncing (track immediately).
`skipPatterns`| `string[]`| `[]`| Array of path patterns. Pageviews whose path matches any pattern will **not** be tracked. See Path Matching.
`maskPatterns`| `string[]`| `[]`| Array of path patterns. For matching pageview paths, the original path will be **replaced** by the pattern itself in tracked data. See Path Matching.
`debug`| `boolean`| `false`| Enable detailed logging to the browser console.
`replayPrivacyConfig`| `object`| -| Privacy settings for session replay. See Session Replay.
#### Remote Configuration
These settings are controlled through your Rybbit dashboard and cannot be set in the init config:
Dashboard Setting| Description| Default
---|---|---
Track Initial Pageview| Track pageview on initial page load| `true`
Track SPA Navigation| Track pageviews on Single Page Application route changes| `true`
Track URL Parameters| Include URL query strings in tracked data| `true`
Track Outbound Links| Automatically track clicks on external links| `true`
Track Web Vitals| Track Core Web Vitals performance metrics| `false`
Capture Errors| Enable automatic error tracking| `false`
Session Replay| Enable session replay recording| `false`
If fetching settings fails or times out, the SDK uses sensible defaults.
```
--------------------------------
### GET /api/sites/:site/error-bucketed
Source: https://rybbit.com/docs/api/stats/errors
Returns error occurrence counts over time for a specific error message. Useful for tracking error trends and identifying when issues started.
```APIDOC
## GET /api/sites/:site/error-bucketed
### Description
Returns error occurrence counts over time for a specific error message. Useful for tracking error trends and identifying when issues started.
### Method
GET
### Endpoint
`/api/sites/:site/error-bucketed`
### Parameters
#### Path Parameters
- **site** (string | number) - Required - The ID of the site.
#### Query Parameters
- **errorMessage** (string) - Required - The specific error message to query.
- **bucket** (TimeBucket) - Required - The time bucket for grouping errors (e.g., 'hour', 'day', 'week').
### Response
#### Success Response (200)
- **success** (boolean) - Indicates if the request was successful.
- **data** (ErrorBucket[]) - An array of objects, where each object represents a time bucket and the count of errors within that bucket.
#### ErrorBucket Object
(Details for ErrorBucket object structure are not provided in the input, but it would typically include a time field and a count field.)
```
--------------------------------
### Install and Run Wrangler for Local Development
Source: https://rybbit.com/docs/proxy-guide/cloudflare-workers
This snippet shows how to install Wrangler globally, log in to Cloudflare, initialize a new worker, run the development server, and deploy the worker. Wrangler is essential for local testing and deployment of Cloudflare Workers.
```bash
npm install -g wrangler
wrangler login
wrangler init rybbit-proxy
wrangler dev
wrangler deploy
```
--------------------------------
### Get Live User Count (Rust)
Source: https://rybbit.com/docs/api/stats/overview
Fetches the live user count using the Rust reqwest library. This example demonstrates making an asynchronous GET request, setting the authorization header, and deserializing the JSON response to retrieve the visitor count. Ensure you have the necessary dependencies.
```rust
let client = reqwest::Client::new();
let res = client
.get("https://app.rybbit.io/api/sites/123/live-user-count?minutes=5")
.header("Authorization", "Bearer your_api_key_here")
.send()
.await?;
let data: serde_json::Value = res.json().await?;
println!("Live visitors: {}", data["count"]);
```
--------------------------------
### Initialize Rybbit Node.js SDK
Source: https://rybbit.com/docs/sdks/node
Initialize the Rybbit SDK with your site's configuration. This requires essential parameters like analyticsHost, siteId, and apiKey. The constructor will validate these parameters.
```javascript
import { Rybbit } from "@rybbit/node";
const rybbit = new Rybbit(config: RybbitConfig);
```
```javascript
import { Rybbit } from "@rybbit/node";
const rybbit = new Rybbit({
analyticsHost: "https://app.rybbit.io/api",
siteId: "1",
apiKey: "your-secret-api-key",
});
```
--------------------------------
### Filter Journeys by Step (Rust)
Source: https://rybbit.com/docs/api/stats/misc
This Rust code snippet uses the `reqwest` and `serde_json` crates to filter journeys starting from the homepage. It constructs an asynchronous GET request with the authorization header.
```rust
let client = reqwest::Client::new();
let res = client
.get("https://app.rybbit.io/api/sites/1/journeys23?steps=3&stepFilters=%7B%220%22%3A%22%2F%22%7D")
.header("Authorization", "Bearer your_api_key_here")
.send()
.await?;
let data: serde_json::Value = res.json().await?;
```
--------------------------------
### JavaScript (Web) SDK Installation
Source: https://rybbit.com/docs/sdks/web
Instructions for installing the Rybbit JavaScript SDK using npm or yarn. Also includes optional peer dependency for session replay.
```APIDOC
## Installation
```
npm install @rybbit/js
```
```
yarn add @rybbit/js
```
## Peer Dependencies
The SDK has an optional peer dependency for session replay functionality:
```
npm install rrweb
```
```
yarn add rrweb
```
The `rrweb` package is only required if you enable session replay in your Rybbit dashboard. The SDK will work without it for all other tracking features.
```
--------------------------------
### Filter Journeys by Step (Ruby)
Source: https://rybbit.com/docs/api/stats/misc
This Ruby script demonstrates filtering journeys starting from the homepage using the `net/http` and `json` libraries. It constructs the HTTP GET request with the necessary headers.
```ruby
require 'net/http'
require 'json'
uri = URI('https://app.rybbit.io/api/sites/1/journeys23?steps=3&stepFilters=%7B%220%22%3A%22%2F%22%7D')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer your_api_key_here'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
```
--------------------------------
### Install Rybbit Node.js SDK
Source: https://rybbit.com/docs/sdks/node
Install the Rybbit Node.js SDK using either npm or yarn package managers. This is the first step to integrating server-side analytics.
```bash
npm install @rybbit/node
```
```bash
yarn add @rybbit/node
```
--------------------------------
### Create Path Goal using Rust (reqwest)
Source: https://rybbit.com/docs/api/stats/goals
An example using the Rust reqwest library to create a 'path' goal. It sends a POST request with the goal configuration serialized as JSON. Authentication is handled via the Authorization header.
```rust
use reqwest::Error;
use serde_json::json;
async fn create_goal() -> Result<(), Error> {
let body = json!({
"name": "Checkout Complete",
"goalType": "path",
"config": {
"pathPattern": "/checkout/success"
}
});
let client = reqwest::Client::new();
let res = client
.post("https://app.rybbit.io/api/sites/1/goals23")
.header("Authorization", "Bearer your_api_key_here")
.json(&body)
.send()
.await?;
let data: serde_json::Value = res.json().await?;
println!("{:?}", data);
Ok(())
}
```
--------------------------------
### Retrieve Outbound Link Data (Python)
Source: https://rybbit.com/docs/api/stats/events
This Python example uses the `requests` library to fetch outbound link analytics data. It demonstrates setting the request parameters, including the date range, and the 'Authorization' header. The response is then parsed as JSON. Make sure to install the `requests` library if you haven't already (`pip install requests`).
```python
import requests
response = requests.get(
'https://app.rybbit.io/api/sites/1/events/outbound23',
params={
'start_date': '2024-01-01',
'end_date': '2024-01-31'
},
headers={
'Authorization': 'Bearer your_api_key_here'
}
)
data = response.json()
```
--------------------------------
### Enable All SlimDOM Options
Source: https://rybbit.com/docs/script
Demonstrates how to enable all SlimDOM options by setting the `data-replay-slim-dom-options` attribute to `true`. This excludes script tags, comments, and various meta tags from the recorded DOM to reduce data size.
```html
data-replay-slim-dom-options="true"
```
--------------------------------
### Get Live User Count (Ruby)
Source: https://rybbit.com/docs/api/stats/overview
Fetches the live user count using Ruby's Net::HTTP library. This example constructs a GET request, sets the necessary authorization header, and sends it to the Rybbit API. The response body is parsed as JSON to extract the visitor count.
```ruby
require 'net/http'
require 'json'
uri = URI('https://app.rybbit.io/api/sites/123/live-user-count?minutes=5')
req = Net::HTTP::Get.new(uri)
req['Authorization'] = 'Bearer your_api_key_here'
res = Net::HTTP.start(uri.hostname, uri.port, use_ssl: true) { |http| http.request(req) }
data = JSON.parse(res.body)
puts "Live visitors: #{data['count']}"
```
--------------------------------
### Filter Journeys by Step (Python)
Source: https://rybbit.com/docs/api/stats/misc
This Python script uses the `requests` library to filter journeys starting from the homepage. It sends a GET request to the Rybbit API with the appropriate step filters and authorization.
```python
import requests
response = requests.get(
'https://app.rybbit.io/api/sites/1/journeys23?steps=3&stepFilters=%7B%220%22%3A%22%2F%22%7D',
headers={
'Authorization': 'Bearer your_api_key_here'
}
)
data = response.json()
```
--------------------------------
### Environment-Based Caddy Configuration
Source: https://rybbit.com/docs/proxy-guide/caddy
Demonstrates using environment variables for domain and Rybbit host configuration. This allows for flexible deployment across different environments by setting `DOMAIN` and `RYBBIT_HOST` variables.
```caddyfile
# /etc/caddy/Caddyfile
{$DOMAIN:yourdomain.com} {
handle_path /analytics/* {
reverse_proxy {$RYBBIT_HOST:https://app.rybbit.io} {
header_up Host {upstream_hostport}
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
}
rewrite * /api{uri}
}
}
```
--------------------------------
### JavaScript/TypeScript Layout/App Configuration for Rybbit Script
Source: https://rybbit.com/docs/proxy-guide/next-js
This example provides a JavaScript/TypeScript version for configuring the Rybbit tracking script in either the root layout (`app/layout.js`) or the App component (`pages/_app.js`). It's a fallback for projects not using TypeScript or specific Next.js versions. Ensure 'YOUR_SITE_ID' is replaced with your unique identifier.
```javascript
import Script from 'next/script';
export default function RootLayout({ children }) {
return (
{children}
);
}
```