πΈ Rybbit - open-source and privacy-friendly alternative to Google Analytics that is 10x more intuitive.
Add proxy guides
Edward Cui89abe4b0c183
diff --git a/docs/content/docs/meta.json b/docs/content/docs/meta.jsonindex fd3ea5d14..eda788c56 100644--- a/docs/content/docs/meta.json+++ b/docs/content/docs/meta.json@@ -10,6 +10,7 @@"track-events","identify-users","guides",+ "proxy-guide","sdks","api","hiding-own-traffic",diff --git a/docs/content/docs/proxy-guide/astro.mdx b/docs/content/docs/proxy-guide/astro.mdxnew file mode 100644index 000000000..cd67be9e9--- /dev/null+++ b/docs/content/docs/proxy-guide/astro.mdx@@ -0,0 +1,402 @@+---+title: Astro Proxy Setup+description: Configure Astro middleware to proxy Rybbit tracking requests+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';++Astro's middleware feature makes it simple to proxy Rybbit tracking. This guide shows how to set up server-side request proxying in your Astro application.++## Overview++Astro middleware allows you to intercept and modify requests before they're handled, making it perfect for creating a transparent analytics proxy.++**What you'll achieve:**+- Proxy Rybbit endpoints through your Astro site+- Forward necessary headers for accurate tracking+- Simple configuration in `astro.config.mjs`+- Support all Rybbit features++## Prerequisites++- Astro 2.0 or later (with SSR or hybrid rendering enabled)+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID++<Callout type="warn">+This guide requires SSR (Server-Side Rendering) or hybrid mode. Static sites cannot proxy requests server-side. For static sites on platforms like Vercel or Netlify, use their platform-specific proxy configurations.+</Callout>++## Implementation++<Steps>++### Enable SSR in Astro++Update `astro.config.mjs` to enable SSR:++```javascript+// astro.config.mjs+import { defineConfig } from 'astro/config';+import node from '@astrojs/node';++export default defineConfig({+ output: 'server', // or 'hybrid'+ adapter: node({+ mode: 'standalone',+ }),+});+```++Install the Node adapter if not already installed:++```bash+npm install @astrojs/node+```++### Configure Environment Variables++Create or update `.env`:++```bash+# .env+RYBBIT_HOST=https://app.rybbit.io+# For self-hosted: RYBBIT_HOST=https://analytics.yourcompany.com+```++### Create Middleware++Create `src/middleware.ts` (or `.js` for JavaScript):++```typescript+// src/middleware.ts+import type { MiddlewareHandler } from 'astro';++const RYBBIT_HOST = import.meta.env.RYBBIT_HOST || 'https://app.rybbit.io';++export const onRequest: MiddlewareHandler = async (context, next) => {+ const { request } = context;+ const url = new URL(request.url);++ // Check if this is an analytics request+ if (url.pathname.startsWith('/analytics/')) {+ return proxyToRybbit(request, url.pathname);+ }++ // Continue with normal request handling+ return next();+};++async function proxyToRybbit(request: Request, pathname: string): Promise<Response> {+ try {+ // Map paths+ let rybbitPath = pathname.replace('/analytics/', '/api/');++ // Special case for site config+ if (pathname.startsWith('/analytics/site/')) {+ rybbitPath = pathname.replace('/analytics/', '/');+ }++ const rybbitUrl = `${RYBBIT_HOST}${rybbitPath}`;++ // Get client IP from headers+ const forwardedFor = request.headers.get('x-forwarded-for');+ const clientIp = forwardedFor ? forwardedFor.split(',')[0].trim() : '127.0.0.1';++ // Forward request+ const proxyHeaders = new Headers(request.headers);+ proxyHeaders.set('X-Real-IP', clientIp);+ proxyHeaders.set('X-Forwarded-For', clientIp);++ const response = await fetch(rybbitUrl, {+ method: request.method,+ headers: proxyHeaders,+ body: request.method !== 'GET' ? await request.text() : undefined,+ });++ // Return proxied response+ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ });+ } catch (error) {+ console.error('Rybbit proxy error:', error);+ return new Response('Analytics proxy error', { status: 500 });+ }+}+```++For JavaScript projects:++```javascript+// src/middleware.js+const RYBBIT_HOST = import.meta.env.RYBBIT_HOST || 'https://app.rybbit.io';++export const onRequest = async (context, next) => {+ const { request } = context;+ const url = new URL(request.url);++ if (url.pathname.startsWith('/analytics/')) {+ return proxyToRybbit(request, url.pathname);+ }++ return next();+};++async function proxyToRybbit(request, pathname) {+ try {+ let rybbitPath = pathname.replace('/analytics/', '/api/');++ if (pathname.startsWith('/analytics/site/')) {+ rybbitPath = pathname.replace('/analytics/', '/');+ }++ const rybbitUrl = `${RYBBIT_HOST}${rybbitPath}`;+ const forwardedFor = request.headers.get('x-forwarded-for');+ const clientIp = forwardedFor ? forwardedFor.split(',')[0].trim() : '127.0.0.1';++ const proxyHeaders = new Headers(request.headers);+ proxyHeaders.set('X-Real-IP', clientIp);+ proxyHeaders.set('X-Forwarded-For', clientIp);++ const response = await fetch(rybbitUrl, {+ method: request.method,+ headers: proxyHeaders,+ body: request.method !== 'GET' ? await request.text() : undefined,+ });++ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ });+ } catch (error) {+ console.error('Rybbit proxy error:', error);+ return new Response('Analytics proxy error', { status: 500 });+ }+}+```++### Update Your Layout++Add the tracking script to your layout:++```astro+---+// src/layouts/Layout.astro+const { title } = Astro.props;+---++<!DOCTYPE html>+<html lang="en">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width" />+ <title>{title}</title>++ <!-- Rybbit Analytics -->+ <script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+ </head>+ <body>+ <slot />+ </body>+</html>+```++### Start Development Server++```bash+npm run dev+```++### Verify the Setup++1. **Open your site** in a browser with Developer Tools+2. **Check Network tab**: Requests should go to `/analytics/*`+3. **Verify in Rybbit dashboard**: Data should appear++</Steps>++## How It Works++Astro middleware intercepts requests before they're processed:++1. Request to `/analytics/script.js` enters middleware+2. Middleware proxies to `https://app.rybbit.io/api/script.js`+3. Client IP headers are preserved+4. Response is returned to browser++## Advanced Configuration++### Caching with Astro++Add caching for scripts:++```typescript+// src/middleware.ts+const cache = new Map<string, { response: Response; timestamp: number }>();+const CACHE_TTL = 3600000; // 1 hour in milliseconds++async function proxyToRybbit(request: Request, pathname: string): Promise<Response> {+ // Cache GET requests for scripts+ if (request.method === 'GET' && pathname.endsWith('.js')) {+ const cached = cache.get(pathname);++ if (cached && Date.now() - cached.timestamp < CACHE_TTL) {+ return cached.response.clone();+ }+ }++ // ... proxy logic++ // Cache the response+ if (request.method === 'GET' && pathname.endsWith('.js')) {+ cache.set(pathname, {+ response: response.clone(),+ timestamp: Date.now(),+ });+ }++ return response;+}+```++### Conditional Proxying++Only proxy in production:++```typescript+export const onRequest: MiddlewareHandler = async (context, next) => {+ const { request } = context;+ const url = new URL(request.url);++ // Only proxy in production+ if (import.meta.env.PROD && url.pathname.startsWith('/analytics/')) {+ return proxyToRybbit(request, url.pathname);+ }++ return next();+};+```++### Error Logging++Add detailed error logging:++```typescript+async function proxyToRybbit(request: Request, pathname: string): Promise<Response> {+ try {+ // ... proxy logic+ } catch (error) {+ const errorDetails = {+ message: error instanceof Error ? error.message : 'Unknown error',+ pathname,+ method: request.method,+ timestamp: new Date().toISOString(),+ };++ console.error('Rybbit proxy error:', errorDetails);++ // Return error response+ return new Response(JSON.stringify({ error: 'Analytics proxy error' }), {+ status: 500,+ headers: { 'Content-Type': 'application/json' },+ });+ }+}+```++## Troubleshooting++### Middleware not running++**Problem**: Requests bypass middleware.++**Solution**:+1. Ensure SSR or hybrid mode is enabled in `astro.config.mjs`+2. Verify middleware file is in `src/middleware.ts` (not in subdirectory)+3. Check adapter is installed: `npm install @astrojs/node`++### Static build issues++**Problem**: Build fails or proxy doesn't work in production.++**Solution**:+Middleware requires server-side rendering. Ensure:+```javascript+// astro.config.mjs+export default defineConfig({+ output: 'server', // Required for middleware+ adapter: node({+ mode: 'standalone',+ }),+});+```++### Environment variables not loading++**Problem**: `RYBBIT_HOST` is undefined.++**Solution**:+1. Check `.env` file is in project root+2. Use `import.meta.env.RYBBIT_HOST` (not `process.env`)+3. For production, set environment variables in your hosting platform++## Deployment++### Vercel++Deploy with Vercel adapter:++```bash+npm install @astrojs/vercel+```++```javascript+// astro.config.mjs+import { defineConfig } from 'astro/config';+import vercel from '@astrojs/vercel/serverless';++export default defineConfig({+ output: 'server',+ adapter: vercel(),+});+```++### Netlify++Deploy with Netlify adapter:++```bash+npm install @astrojs/netlify+```++```javascript+// astro.config.mjs+import { defineConfig } from 'astro/config';+import netlify from '@astrojs/netlify/functions';++export default defineConfig({+ output: 'server',+ adapter: netlify(),+});+```++### Node.js Server++For self-hosting:++```bash+npm run build+node ./dist/server/entry.mjs+```++## Related Resources++- [Astro Integration Guide](/docs/guides/astro) - General Astro integration+- [Tracking Script Documentation](/docs/script) - Script configuration+- [Astro Middleware](https://docs.astro.build/en/guides/middleware/) - Official Astro docsdiff --git a/docs/content/docs/proxy-guide/caddy.mdx b/docs/content/docs/proxy-guide/caddy.mdxnew file mode 100644index 000000000..4cd72b5f7--- /dev/null+++ b/docs/content/docs/proxy-guide/caddy.mdx@@ -0,0 +1,482 @@+---+title: Caddy Proxy Setup+description: Configure Caddy reverse proxy to serve Rybbit tracking with automatic HTTPS+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Caddy is a powerful web server with automatic HTTPS that makes reverse proxying simple and secure. This guide shows how to configure Caddy to proxy Rybbit tracking through your own domain.++## Overview++Caddy's `reverse_proxy` directive makes it incredibly easy to proxy requests. Combined with automatic HTTPS via Let's Encrypt, Caddy provides a secure, low-configuration solution for proxying analytics.++**What you'll achieve:**+- Automatic HTTPS with Let's Encrypt+- Simple reverse proxy configuration+- Header forwarding for accurate tracking+- Support all Rybbit features++## Prerequisites++- Caddy installed (version 2.0 or later)+- Domain pointing to your server+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID (found in your dashboard)++<Callout type="info">+Caddy automatically obtains and renews SSL certificates from Let's Encrypt. No manual SSL configuration needed!+</Callout>++## Implementation++<Steps>++### Configure Caddyfile++Add or update your Caddyfile with the analytics proxy configuration:++<Tabs>+<Tab value="full-proxy-recommended" title="Full Proxy (Recommended)">++```txt+# /etc/caddy/Caddyfile++yourdomain.com {+ # Your main site configuration+ # ...++ # Rybbit Analytics Proxy+ # Main tracking script+ handle /analytics/script.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ header_up X-Forwarded-Proto {scheme}+ }+ rewrite * /api/script.js+ }++ # Unminified script+ handle /analytics/script-full.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/script-full.js+ }++ # Session replay script+ handle /analytics/replay.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/replay.js+ }++ # Web Vitals metrics script+ handle /analytics/metrics.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/metrics.js+ }++ # Event tracking endpoint+ handle /analytics/track {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ header_up Content-Type {header.Content-Type}+ }+ rewrite * /api/track+ }++ # User identification endpoint+ handle /analytics/identify {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ header_up Content-Type {header.Content-Type}+ }+ rewrite * /api/identify+ }++ # Session replay recording+ handle /analytics/session-replay/record/* {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ header_up Content-Type {header.Content-Type}+ }+ rewrite * /api/session-replay/record{path}+ }++ # Site configuration+ handle /analytics/site/tracking-config/* {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /site/tracking-config{path}+ }+}+```++<Callout type="info">+Replace `app.rybbit.io` with your self-hosted Rybbit instance URL if you're not using the cloud version.+</Callout>++</Tab>+<Tab value="minimal-proxy" title="Minimal Proxy">++```txt+# /etc/caddy/Caddyfile++yourdomain.com {+ # Main tracking script+ handle /analytics/script.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/script.js+ }++ # Event tracking+ handle /analytics/track {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/track+ }+}+```++</Tab>+<Tab value="simplified-with-handle-path" title="Simplified with Handle Path">++Caddy 2.4+ supports a cleaner syntax with `handle_path`:++```txt+# /etc/caddy/Caddyfile++yourdomain.com {+ handle_path /analytics/* {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api{uri}+ }+}+```++This proxies all `/analytics/*` requests to `https://app.rybbit.io/api/*`.++</Tab>+</Tabs>++### Validate Caddyfile++Test your configuration for syntax errors:++```bash+caddy validate --config /etc/caddy/Caddyfile+```++You should see:+```+Valid configuration+```++### Reload Caddy++Apply the changes by reloading Caddy:++```bash+sudo caddy reload --config /etc/caddy/Caddyfile+```++Or if using systemd:++```bash+sudo systemctl reload caddy+```++<Callout type="info">+Caddy will automatically obtain an SSL certificate from Let's Encrypt on first request if one doesn't exist.+</Callout>++### Update Your Tracking Script++Update your HTML to load the script from your proxied domain:++```html+<!DOCTYPE html>+<html>+<head>+ <!-- ... other head elements -->+ <script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+</head>+<body>+ <!-- Your content -->+</body>+</html>+```++Replace `YOUR_SITE_ID` with your actual site ID from the Rybbit dashboard.++### Verify the Setup++Test your configuration:++1. **Check Caddy is running**:+ ```bash+ sudo systemctl status caddy+ ```++2. **Test script loading**:+ ```bash+ curl -I https://yourdomain.com/analytics/script.js+ ```++ You should see `HTTP/2 200` with `content-type: application/javascript`.++3. **Open your website** in a browser with Developer Tools and verify:+ - Script loads from `/analytics/script.js`+ - Tracking requests go to `/analytics/track`+ - Data appears in Rybbit dashboard++</Steps>++## How It Works++Caddy's `reverse_proxy` directive forwards requests to Rybbit's servers:++1. Browser requests `https://yourdomain.com/analytics/script.js`+2. Caddy matches the handle block+3. Rewrites the path to `/api/script.js`+4. Forwards to `https://app.rybbit.io/api/script.js` with proper headers+5. Returns response to browser++The Rybbit script auto-detects it's being served from your domain and sends all tracking to your domain's endpoints.++## Advanced Configuration++### Caching with Cache-Control++Add caching headers for better performance:++```txt+yourdomain.com {+ # Scripts - cache for 1 hour+ handle /analytics/script.js {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/script.js+ header Cache-Control "public, max-age=3600"+ }++ # Config - cache for 5 minutes+ handle /analytics/site/tracking-config/* {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /site/tracking-config{path}+ header Cache-Control "public, max-age=300"+ }++ # Tracking - no cache+ handle /analytics/track {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/track+ header Cache-Control "no-store"+ }+}+```++### Subdomain Proxy++Use a dedicated subdomain for analytics:++```txt+# /etc/caddy/Caddyfile++analytics.yourdomain.com {+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api{uri}+}+```++Then use:+```html+<script src="https://analytics.yourdomain.com/script.js" data-site-id="123"></script>+```++### Request Size Limits++For session replay, increase max body size:++```txt+yourdomain.com {+ # Increase request body limit for session replay+ handle /analytics/session-replay/record/* {+ request_body {+ max_size 10MB+ }+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/session-replay/record{path}+ }+}+```++### Environment-Based Configuration++Use Caddy's environment variable support:++```txt+# /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}+ }+}+```++Then set environment variables:+```bash+export DOMAIN=yourdomain.com+export RYBBIT_HOST=https://app.rybbit.io+caddy run+```++### Rate Limiting++Protect your proxy with rate limiting using the `rate_limit` plugin:++```txt+yourdomain.com {+ handle /analytics/track {+ rate_limit {+ zone analytics {+ key {remote_host}+ events 100+ window 1m+ }+ }+ reverse_proxy https://app.rybbit.io {+ header_up Host app.rybbit.io+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+ }+ rewrite * /api/track+ }+}+```++<Callout type="warn">+The `rate_limit` directive requires the [caddy-ratelimit plugin](https://github.com/mholt/caddy-ratelimit). Install with: `xcaddy build --with github.com/mholt/caddy-ratelimit`+</Callout>++## Troubleshooting++### Certificate errors++**Problem**: Caddy fails to obtain SSL certificate.++**Solution**:+1. Verify domain points to your server (DNS)+2. Check ports 80 and 443 are open+3. Ensure no other process is using port 443+4. Check Caddy logs: `journalctl -u caddy -f`++### Incorrect geolocation++**Problem**: All visitors show same location.++**Solution**:+Ensure you're forwarding client IP:+```txt+reverse_proxy https://app.rybbit.io {+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+}+```++### 502 Bad Gateway++**Problem**: Caddy returns 502 when accessing analytics endpoints.++**Solution**:+1. Verify Rybbit backend is accessible:+ ```bash+ curl -I https://app.rybbit.io/api/script.js+ ```+2. Check Caddy logs for errors:+ ```bash+ journalctl -u caddy -n 50+ ```++### Path rewriting not working++**Problem**: Requests go to wrong Rybbit endpoints.++**Solution**:+Use the `rewrite` directive correctly:+```txt+handle /analytics/script.js {+ rewrite * /api/script.js # Rewrite before reverse_proxy+ reverse_proxy https://app.rybbit.io {+ # ... headers+ }+}+```++## Related Resources++- [Tracking Script Documentation](/docs/script) - Script configuration options+- [Generic Proxy Guide](/docs/proxy-guide/get-started) - Framework-agnostic concepts+- [Caddy Documentation](https://caddyserver.com/docs/) - Official Caddy docs+- [Caddy reverse_proxy](https://caddyserver.com/docs/caddyfile/directives/reverse_proxy) - Reverse proxy directive docsdiff --git a/docs/content/docs/proxy-guide/cloudflare-workers.mdx b/docs/content/docs/proxy-guide/cloudflare-workers.mdxnew file mode 100644index 000000000..0fb80dc07--- /dev/null+++ b/docs/content/docs/proxy-guide/cloudflare-workers.mdx@@ -0,0 +1,457 @@+---+title: Cloudflare Workers Proxy Setup+description: Use Cloudflare Workers to proxy Rybbit tracking at the edge+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Cloudflare Workers provide a serverless way to proxy Rybbit tracking at the edge, close to your users worldwide. This delivers excellent performance with minimal configuration.++## Overview++Cloudflare Workers run on Cloudflare's global network, intercepting and proxying requests before they reach your origin server. This makes them perfect for analytics proxying with built-in caching and ultra-low latency.++**What you'll achieve:**+- Edge-based proxying in 300+ cities worldwide+- Automatic caching with Cloudflare's Cache API+- Sub-10ms latency for most requests+- Zero server infrastructure needed++## Prerequisites++- Cloudflare account with your domain+- Workers enabled on your account (free tier available)+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID++## Implementation++<Steps>++### Create Worker++Log in to Cloudflare Dashboard and create a new Worker:++1. Go to **Workers & Pages** β **Create application** β **Create Worker**+2. Name it `rybbit-proxy` (or your preferred name)+3. Click **Deploy** to create the worker++### Update Worker Code++Replace the default code with the proxy implementation:++<Tabs>+<Tab value="full-proxy-recommended" title="Full Proxy (Recommended)">++```javascript+// Cloudflare Worker for Rybbit Analytics Proxy++const RYBBIT_HOST = 'https://app.rybbit.io';++addEventListener('fetch', event => {+ event.respondWith(handleRequest(event.request));+});++async function handleRequest(request) {+ const url = new URL(request.url);++ // Only proxy /analytics/* paths+ if (!url.pathname.startsWith('/analytics/')) {+ // Pass through to origin+ return fetch(request);+ }++ try {+ return await proxyToRybbit(request, url);+ } catch (error) {+ console.error('Proxy error:', error);+ return new Response('Analytics proxy error', { status: 500 });+ }+}++async function proxyToRybbit(request, url) {+ // Map paths: /analytics/* β /api/*+ let rybbitPath = url.pathname.replace('/analytics/', '/api/');++ // Special case for site config+ if (url.pathname.startsWith('/analytics/site/')) {+ rybbitPath = url.pathname.replace('/analytics/', '/');+ }++ // Build Rybbit URL+ const rybbitUrl = new URL(rybbitPath, RYBBIT_HOST);+ rybbitUrl.search = url.search; // Preserve query params++ // Get client IP+ const clientIp = request.headers.get('CF-Connecting-IP') ||+ request.headers.get('X-Forwarded-For') ||+ '0.0.0.0';++ // Build request headers+ const proxyHeaders = new Headers(request.headers);+ proxyHeaders.set('X-Real-IP', clientIp);+ proxyHeaders.set('X-Forwarded-For', clientIp);+ proxyHeaders.delete('CF-Connecting-IP'); // Remove Cloudflare internal header++ // Build proxy request+ const proxyRequest = new Request(rybbitUrl, {+ method: request.method,+ headers: proxyHeaders,+ body: request.method !== 'GET' && request.method !== 'HEAD' ? request.body : undefined,+ });++ // Check cache for GET requests+ if (request.method === 'GET') {+ const cache = caches.default;+ let response = await cache.match(proxyRequest);++ if (response) {+ // Return cached response+ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: {+ ...Object.fromEntries(response.headers),+ 'X-Cache-Status': 'HIT',+ },+ });+ }+ }++ // Fetch from Rybbit+ const response = await fetch(proxyRequest);++ // Cache scripts for 1 hour+ if (request.method === 'GET' && url.pathname.match(/\.(js)$/)) {+ const cacheResponse = new Response(response.body, response);+ cacheResponse.headers.set('Cache-Control', 'public, max-age=3600');+ cacheResponse.headers.set('X-Cache-Status', 'MISS');++ // Clone and cache+ const cache = caches.default;+ await cache.put(proxyRequest, cacheResponse.clone());++ return cacheResponse;+ }++ // Return non-cacheable response+ return new Response(response.body, {+ status: response.status,+ statusText: response.statusText,+ headers: response.headers,+ });+}+```++</Tab>+<Tab value="minimal-proxy" title="Minimal Proxy">++```javascript+// Minimal Cloudflare Worker for Rybbit++const RYBBIT_HOST = 'https://app.rybbit.io';++addEventListener('fetch', event => {+ event.respondWith(handleRequest(event.request));+});++async function handleRequest(request) {+ const url = new URL(request.url);++ // Only proxy /analytics/script.js and /analytics/track+ if (url.pathname === '/analytics/script.js' || url.pathname === '/analytics/track') {+ const rybbitPath = url.pathname.replace('/analytics/', '/api/');+ const rybbitUrl = `${RYBBIT_HOST}${rybbitPath}`;++ const clientIp = request.headers.get('CF-Connecting-IP') || '0.0.0.0';++ const proxyHeaders = new Headers(request.headers);+ proxyHeaders.set('X-Real-IP', clientIp);+ proxyHeaders.set('X-Forwarded-For', clientIp);++ return fetch(rybbitUrl, {+ method: request.method,+ headers: proxyHeaders,+ body: request.method === 'POST' ? request.body : undefined,+ });+ }++ // Pass through to origin+ return fetch(request);+}+```++</Tab>+<Tab value="with-environment-variables" title="With Environment Variables">++Using Workers secrets for configuration:++```javascript+addEventListener('fetch', event => {+ event.respondWith(handleRequest(event.request, event.env));+});++async function handleRequest(request, env) {+ const RYBBIT_HOST = env.RYBBIT_HOST || 'https://app.rybbit.io';+ const url = new URL(request.url);++ if (!url.pathname.startsWith('/analytics/')) {+ return fetch(request);+ }++ let rybbitPath = url.pathname.replace('/analytics/', '/api/');++ if (url.pathname.startsWith('/analytics/site/')) {+ rybbitPath = url.pathname.replace('/analytics/', '/');+ }++ const rybbitUrl = new URL(rybbitPath, RYBBIT_HOST);+ const clientIp = request.headers.get('CF-Connecting-IP') || '0.0.0.0';++ const proxyHeaders = new Headers(request.headers);+ proxyHeaders.set('X-Real-IP', clientIp);+ proxyHeaders.set('X-Forwarded-For', clientIp);++ return fetch(rybbitUrl.toString(), {+ method: request.method,+ headers: proxyHeaders,+ body: request.method !== 'GET' ? request.body : undefined,+ });+}+```++Set environment variable in Cloudflare Dashboard:+**Workers & Pages** β Your Worker β **Settings** β **Variables** β Add `RYBBIT_HOST`++</Tab>+</Tabs>++### Deploy Worker++Click **Save and Deploy** to publish your worker.++### Configure Worker Route++Set up a route to trigger the worker:++1. Go to **Workers & Pages** β Your Worker β **Triggers**+2. Click **Add route**+3. Configure:+ - **Route**: `yourdomain.com/analytics/*`+ - **Zone**: Select your domain+4. Click **Save**++<Callout type="info">+The route pattern `yourdomain.com/analytics/*` ensures the worker only runs for analytics requests, not your entire site.+</Callout>++### Update Your Tracking Script++Add the script to your website:++```html+<script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++### Verify the Setup++1. **Visit your site** with Developer Tools open+2. **Check Network tab**:+ - Script loads from `/analytics/script.js`+ - Check response headers for `CF-Cache-Status` (HIT/MISS)+3. **Verify in Rybbit dashboard**: Data should appear++</Steps>++## How It Works++Cloudflare Workers intercept requests at the edge:++1. Request to `yourdomain.com/analytics/script.js` hits Cloudflare edge+2. Worker checks cache for GET requests+3. If not cached, proxies to `app.rybbit.io/api/script.js`+4. Response is cached at the edge location+5. Subsequent requests serve from edge cache (ultra-fast)++All tracking data flows through Cloudflare's network while preserving client IP information.++## Performance Benefits++### Global Edge Network++- **300+ locations worldwide**: Workers run in Cloudflare data centers globally+- **Sub-10ms cold start**: Faster than traditional serverless+- **Automatic scaling**: Handles traffic spikes without configuration++### Built-in Caching++- **Cache API**: Leverages Cloudflare's massive edge cache+- **Intelligent caching**: Scripts cached at edge, tracking requests passed through+- **Instant cache purge**: Clear cache via Cloudflare API if needed++### Zero Infrastructure++- **No servers to manage**: Fully serverless+- **Pay-per-request**: Free tier includes 100,000 requests/day+- **Automatic HTTPS**: Cloudflare handles SSL++## Advanced Configuration++### Cache Control++Customize caching behavior:++```javascript+// Cache scripts for different durations+if (url.pathname === '/analytics/script.js') {+ cacheResponse.headers.set('Cache-Control', 'public, max-age=3600'); // 1 hour+} else if (url.pathname === '/analytics/replay.js') {+ cacheResponse.headers.set('Cache-Control', 'public, max-age=7200'); // 2 hours+}+```++### Rate Limiting++Add basic rate limiting:++```javascript+// Simple in-memory rate limiting (per edge location)+const rateLimitMap = new Map();++async function checkRateLimit(ip) {+ const key = `ratelimit:${ip}`;+ const current = rateLimitMap.get(key) || { count: 0, resetAt: Date.now() + 60000 };++ if (Date.now() > current.resetAt) {+ current.count = 0;+ current.resetAt = Date.now() + 60000;+ }++ current.count++;+ rateLimitMap.set(key, current);++ return current.count > 100; // 100 requests per minute+}+```++### Logging and Analytics++Log proxy usage:++```javascript+async function handleRequest(request) {+ const startTime = Date.now();++ try {+ const response = await proxyToRybbit(request, url);+ const duration = Date.now() - startTime;++ // Log to Cloudflare Analytics Engine (if enabled)+ console.log({+ path: url.pathname,+ status: response.status,+ duration,+ cached: response.headers.get('X-Cache-Status') === 'HIT',+ });++ return response;+ } catch (error) {+ console.error('Proxy error:', error);+ return new Response('Error', { status: 500 });+ }+}+```++## Cost Considerations++Cloudflare Workers pricing (as of 2024):++- **Free tier**: 100,000 requests/day+- **Paid plan**: $5/month for 10 million requests + $0.50 per million after++For typical traffic:+- 100,000 sessions/month β 200,000-500,000 requests (well within free tier)+- Even with session replay: Usually under 1 million requests/month++<Callout type="info">+Most sites stay within the free tier. Bandwidth is unlimited on all Cloudflare plans.+</Callout>++## Troubleshooting++### Worker not triggering++**Problem**: Requests bypass worker.++**Solution**:+1. Verify route is configured: `yourdomain.com/analytics/*`+2. Check zone matches your domain+3. Ensure orange-cloud (proxy) is enabled on DNS record++### Cache not working++**Problem**: `X-Cache-Status` always shows MISS.++**Solution**:+1. Verify cache key includes important parts:+ ```javascript+ const cacheKey = new Request(rybbitUrl, request);+ ```+2. Ensure `Cache-Control` headers are set+3. Check method is GET (POST requests aren't cached)++### Incorrect geolocation++**Problem**: All visitors show Cloudflare IPs.++**Solution**:+Use `CF-Connecting-IP` header:+```javascript+const clientIp = request.headers.get('CF-Connecting-IP');+proxyHeaders.set('X-Real-IP', clientIp);+```++### Deployment errors++**Problem**: Worker fails to deploy.++**Solution**:+1. Check syntax in editor (no console.log in production)+2. Verify all async functions use await+3. Test locally with Wrangler:+ ```bash+ npm install -g wrangler+ wrangler dev+ ```++## Local Development++Use Wrangler for local testing:++```bash+# Install Wrangler+npm install -g wrangler++# Login to Cloudflare+wrangler login++# Create worker+wrangler init rybbit-proxy++# Dev server+wrangler dev++# Deploy+wrangler deploy+```++## Related Resources++- [Tracking Script Documentation](/docs/script) - Script configuration+- [Generic Proxy Guide](/docs/proxy-guide/get-started) - Core concepts+- [Cloudflare Workers Docs](https://developers.cloudflare.com/workers/) - Official docs+- [Workers Cache API](https://developers.cloudflare.com/workers/runtime-apis/cache/) - Caching documentationdiff --git a/docs/content/docs/proxy-guide/express.mdx b/docs/content/docs/proxy-guide/express.mdxnew file mode 100644index 000000000..edbd4302a--- /dev/null+++ b/docs/content/docs/proxy-guide/express.mdx@@ -0,0 +1,428 @@+---+title: Express.js Proxy Setup+description: Configure Express.js middleware to proxy Rybbit tracking requests+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Express.js makes it easy to proxy Rybbit tracking using middleware. This guide shows how to set up a reverse proxy using `http-proxy-middleware`.++## Overview++The `http-proxy-middleware` package provides a simple way to proxy requests in Express applications, making it perfect for routing analytics requests to Rybbit servers.++**What you'll achieve:**+- Proxy all Rybbit endpoints through your Express app+- Forward necessary headers for accurate tracking+- Optional caching for better performance+- Support all Rybbit features++## Prerequisites++- Node.js and Express.js application+- npm or yarn package manager+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID++## Implementation++<Steps>++### Install http-proxy-middleware++Install the proxy middleware package:++```bash+npm install http-proxy-middleware+```++Or with yarn:++```bash+yarn add http-proxy-middleware+```++### Configure Environment Variables++Create or update your `.env` file:++```bash+# .env+RYBBIT_HOST=https://app.rybbit.io+# For self-hosted: RYBBIT_HOST=https://analytics.yourcompany.com+```++<Callout type="info">+Install `dotenv` if not already: `npm install dotenv`+</Callout>++### Add Proxy Middleware to Express++<Tabs>+<Tab value="full-proxy-recommended" title="Full Proxy (Recommended)">++Add to your Express server file (e.g., `server.js` or `app.js`):++```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}`);+});+```++</Tab>+<Tab value="minimal-proxy" title="Minimal Proxy">++Minimal setup with basic tracking:++```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';++// Proxy script and track endpoints only+app.use(['/analytics/script.js', '/analytics/track'], createProxyMiddleware({+ 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);+ proxyReq.setHeader('X-Real-IP', clientIp);+ },+}));++const PORT = process.env.PORT || 3000;+app.listen(PORT, () => {+ console.log(`Server running on port ${PORT}`);+});+```++</Tab>+<Tab value="typescript" title="TypeScript">++For TypeScript projects:++```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}`);+});+```++</Tab>+</Tabs>++### Update Your Tracking Script++In your HTML or template files:++```html+<script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++### Start Your Server++```bash+node server.js+```++Or with nodemon for development:++```bash+npm install -D nodemon+npx nodemon server.js+```++### Verify the Setup++1. **Test script endpoint**:+ ```bash+ curl -I http://localhost:3000/analytics/script.js+ ```++2. **Open your app** in a browser with Developer Tools+3. **Check Network tab**: Requests should go to `/analytics/*`+4. **Verify in Rybbit dashboard**: Data should appear++</Steps>++## How It Works++The `http-proxy-middleware` intercepts requests matching the specified paths and forwards them to Rybbit:++1. Request to `/analytics/script.js` is intercepted+2. Path is rewritten to `/api/script.js`+3. Request is forwarded to `https://app.rybbit.io/api/script.js`+4. Client IP headers are added for accurate tracking+5. Response is sent back to the browser++## Advanced Configuration++### Caching Responses++Add caching for better performance:++```javascript+const NodeCache = require('node-cache');+const cache = new NodeCache({ stdTTL: 3600 }); // 1 hour default++// Install: npm install node-cache++// Caching middleware for scripts+const cacheMiddleware = (req, res, next) => {+ const key = req.originalUrl;+ const cachedResponse = cache.get(key);++ if (cachedResponse) {+ res.set('X-Cache-Status', 'HIT');+ return res.send(cachedResponse);+ }++ // Store original send+ const originalSend = res.send.bind(res);+ res.send = (body) => {+ cache.set(key, body);+ res.set('X-Cache-Status', 'MISS');+ return originalSend(body);+ };+ next();+};++// Apply caching only to script files+app.use('/analytics/script.js', cacheMiddleware);+app.use('/analytics/script.js', createProxyMiddleware({+ // ... proxy config+}));+```++### Request Size Limits++For session replay uploads, increase body size limit:++```javascript+const express = require('express');+const app = express();++// Increase limit for session replay endpoints+app.use('/analytics/session-replay', express.json({ limit: '10mb' }));+app.use('/analytics/session-replay', createProxyMiddleware({+ target: RYBBIT_HOST,+ changeOrigin: true,+ pathRewrite: {+ '^/analytics': '/api',+ },+}));+```++### Rate Limiting++Protect your proxy with rate limiting:++```javascript+const rateLimit = require('express-rate-limit');++// Install: npm install express-rate-limit++const analyticsLimiter = rateLimit({+ windowMs: 60 * 1000, // 1 minute+ max: 100, // Limit each IP to 100 requests per minute+ message: 'Too many requests from this IP',+ standardHeaders: true,+ legacyHeaders: false,+});++// Apply to tracking endpoints+app.use('/analytics/track', analyticsLimiter);+app.use('/analytics/track', createProxyMiddleware({+ // ... proxy config+}));+```++### Error Handling++Add error handling for proxy failures:++```javascript+app.use('/analytics', createProxyMiddleware({+ target: RYBBIT_HOST,+ changeOrigin: true,+ pathRewrite: {+ '^/analytics': '/api',+ },+ onError: (err, req, res) => {+ console.error('Proxy error:', err);+ res.status(500).json({ error: 'Analytics proxy error' });+ },+ 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);+ },+}));+```++### CORS Configuration++If serving API endpoints to other domains:++```javascript+const cors = require('cors');++// Install: npm install cors++app.use('/analytics', cors({+ origin: ['https://yourdomain.com', 'https://www.yourdomain.com'],+ credentials: true,+}));++app.use('/analytics', createProxyMiddleware({+ // ... proxy config+}));+```++## Troubleshooting++### Requests timing out++**Problem**: Proxy requests hang or timeout.++**Solution**:+Increase timeout limits:+```javascript+app.use('/analytics', createProxyMiddleware({+ target: RYBBIT_HOST,+ changeOrigin: true,+ timeout: 30000, // 30 seconds+ proxyTimeout: 30000,+ pathRewrite: {+ '^/analytics': '/api',+ },+}));+```++### Incorrect geolocation++**Problem**: All visitors show server's location.++**Solution**:+Ensure IP forwarding is configured:+```javascript+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);+}+```++### Path rewriting issues++**Problem**: 404 errors on Rybbit endpoints.++**Solution**:+Check path rewriting is correct:+```javascript+pathRewrite: {+ '^/analytics': '/api', // /analytics/script.js β /api/script.js+}+```++Debug by logging:+```javascript+onProxyReq: (proxyReq, req, res) => {+ console.log('Proxying:', req.method, req.path, 'β', proxyReq.path);+}+```++## Related Resources++- [Tracking Script Documentation](/docs/script) - Script configuration+- [Generic Proxy Guide](/docs/proxy-guide/get-started) - Core concepts+- [http-proxy-middleware docs](https://github.com/chimurai/http-proxy-middleware) - Middleware documentationdiff --git a/docs/content/docs/proxy-guide/get-started.mdx b/docs/content/docs/proxy-guide/get-started.mdxnew file mode 100644index 000000000..c58e8445d--- /dev/null+++ b/docs/content/docs/proxy-guide/get-started.mdx@@ -0,0 +1,311 @@+---+title: Generic Proxy Setup+description: Framework-agnostic guide to proxy Rybbit tracking through your own domain+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++This guide covers the core concepts for setting up a Rybbit proxy with any reverse proxy or server framework. If your specific framework has a dedicated guide, we recommend following that instead for optimized instructions.++## Prerequisites++Before setting up the proxy, ensure you have:++- **A domain or subdomain** where you'll serve the proxied scripts (e.g., `yourdomain.com` or `analytics.yourdomain.com`)+- **SSL/TLS certificate** for HTTPS (required for modern browsers)+- **Server or platform** with reverse proxy capabilities+- **Your Rybbit instance URL**:+ - Cloud: `https://app.rybbit.io`+ - Self-hosted: Your Rybbit instance URL (e.g., `https://analytics.yourcompany.com`)+- **Your Rybbit site ID** (found in your Rybbit dashboard)++## Understanding the Endpoints++Rybbit uses several endpoints for tracking. You can choose between a minimal setup or full proxy:++<Tabs>+<Tab value="minimal" title="Minimal Setup">++**Required endpoints for basic tracking:**++| Endpoint | Method | Purpose | Cache |+|----------|--------|---------|-------|+| `/api/script.js` | GET | Main tracking script | 1 hour |+| `/api/track` | POST | Event tracking endpoint | No cache |++This minimal setup enables basic pageview and event tracking, but won't support session replay or some advanced features.++</Tab>+<Tab value="full-setup-recommended" title="Full Setup (Recommended)">++**All endpoints for complete functionality:**++| Endpoint | Method | Purpose | Cache |+|----------|--------|---------|-------|+| `/api/script.js` | GET | Main tracking script (minified) | 1 hour |+| `/api/script-full.js` | GET | Unminified script for debugging | 1 hour |+| `/api/replay.js` | GET | Session replay recording script | 1 hour |+| `/api/metrics.js` | GET | Web Vitals metrics script | 1 hour |+| `/api/track` | POST | Event tracking endpoint | No cache |+| `/api/identify` | POST | User identification endpoint | No cache |+| `/api/session-replay/record/:siteId` | POST | Session replay data upload | No cache |+| `/site/tracking-config/:siteId` | GET | Site configuration | 5 minutes |++This setup supports all Rybbit features including session replay, Web Vitals, and custom events.++</Tab>+</Tabs>++<Callout type="info">+The session replay and metrics scripts (`/api/replay.js` and `/api/metrics.js`) are loaded dynamically by the main script when those features are enabled in your site settings. You don't need to include them in your HTML.+</Callout>++## Implementation Steps++<Steps>++### Configure Your Proxy Rules++Set up your reverse proxy to forward requests from your chosen path (e.g., `/analytics/*`) to the Rybbit server.++**Generic proxy configuration pattern:**++```+Your domain path β Rybbit backend+----------------- ---------------+/analytics/script.js β https://app.rybbit.io/api/script.js+/analytics/track β https://app.rybbit.io/api/track+/analytics/replay.js β https://app.rybbit.io/api/replay.js+... and so on+```++**Key requirements:**+- Preserve the HTTP method (GET or POST)+- Forward necessary headers (User-Agent, X-Forwarded-For, Referer)+- Maintain request/response body for POST requests+- Set appropriate Content-Type headers++### Configure Caching (Optional but Recommended)++Implement caching to reduce load on Rybbit servers and improve performance:++**Recommended cache durations:**+- **Scripts** (`.js` files): 1 hour (3600 seconds)+ - These change infrequently but may be updated for bug fixes+- **Site configuration** (`/site/tracking-config/*`): 5 minutes (300 seconds)+ - Updated when you change settings in the dashboard+- **Tracking endpoints** (POST requests): Never cache+ - Each request contains unique event data++**Example cache headers to set:**+```+Cache-Control: public, max-age=3600 # For scripts+Cache-Control: public, max-age=300 # For config+Cache-Control: no-store # For tracking POSTs+```++### Update Your Tracking Script++Change your script tag to load from your proxied domain instead of directly from Rybbit:++**Before (direct loading):**+```html+<script src="https://app.rybbit.io/api/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++**After (proxied):**+```html+<script src="https://yourdomain.com/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++<Callout type="info">+**How Auto-Discovery Works**: The Rybbit script automatically extracts the analytics host from its own `src` attribute by splitting on `/script.js`. This means when it loads from `https://yourdomain.com/analytics/script.js`, it automatically sends all tracking data to `https://yourdomain.com/analytics/*` endpoints.+</Callout>++### Verify the Setup++Test your proxy configuration to ensure everything works correctly:++1. **Open your website** in a browser with Developer Tools open+2. **Go to the Network tab** and filter by "script" or your proxy path+3. **Verify the script loads**:+ - You should see a request to `yourdomain.com/analytics/script.js`+ - Status should be `200 OK`+ - Content-Type should be `application/javascript`+4. **Verify tracking works**:+ - Navigate to another page or trigger an event+ - You should see POST requests to `yourdomain.com/analytics/track`+ - Check the response is successful (200 OK)+5. **Check your Rybbit dashboard**:+ - Wait 1-2 minutes for data to process+ - Verify your session appears in real-time dashboard++### Configure Security Headers (Optional)++Add security headers to protect your proxy:++**Recommended headers:**+```+X-Content-Type-Options: nosniff+X-Frame-Options: DENY+Referrer-Policy: strict-origin-when-cross-origin+```++**CORS headers** (should be preserved from Rybbit):+```+Access-Control-Allow-Origin: *+Access-Control-Allow-Methods: GET, POST, OPTIONS+Access-Control-Allow-Headers: Content-Type+```++</Steps>++## Request Header Forwarding++For accurate tracking, ensure these headers are forwarded to the Rybbit backend:++| Header | Purpose | Required |+|--------|---------|----------|+| `User-Agent` | Device and browser detection | Yes |+| `X-Forwarded-For` or `X-Real-IP` | IP address for geolocation | Yes |+| `Referer` | Referrer tracking | Recommended |+| `Accept-Language` | Language detection | Optional |++<Callout type="warn">+**IP Forwarding**: Rybbit uses IP addresses for geolocation (country/city) and creating anonymous user identifiers (hashed IP + User Agent). If you don't forward the `X-Forwarded-For` or `X-Real-IP` header, all traffic will appear to come from your proxy server's IP.+</Callout>++## Bandwidth Considerations++Proxying adds bandwidth usage to your infrastructure. Here's what to expect:++**Typical bandwidth per session:**+- Initial script load: ~18 KB (one-time per session)+- Pageview tracking: ~0.5-2 KB per pageview+- Custom events: ~0.5-3 KB per event+- Session replay: 50-500 KB per session (if enabled, varies by session length)+- Web Vitals: ~1-2 KB per page++**Estimated monthly bandwidth** for a site with 100,000 monthly sessions:+- Without session replay: ~5-10 GB/month+- With session replay: ~30-80 GB/month++Most modern hosting plans can handle this easily, but verify your bandwidth limits if you have high traffic or session replay enabled.++## Performance Optimization++### Use a CDN++If your server has CDN capabilities (like Cloudflare, Fastly, or AWS CloudFront), configure it to cache the static scripts:++- Cache scripts at edge locations worldwide+- Reduce latency for global users+- Offload bandwidth from your origin server++### Enable Compression++Ensure your proxy enables gzip or brotli compression:++```+Content-Encoding: gzip+```++This can reduce script size by 60-70%, improving load times and reducing bandwidth.++### Connection Reuse++Configure your proxy to maintain persistent connections to Rybbit's backend to reduce latency on repeated requests.++## Common Proxy Patterns++<Tabs>+<Tab value="subdomain-proxy" title="Subdomain Proxy">++Use a dedicated subdomain for analytics:++```+https://analytics.yourdomain.com/script.js β https://app.rybbit.io/api/script.js+https://analytics.yourdomain.com/track β https://app.rybbit.io/api/track+```++**Pros:**+- Clean separation of concerns+- Easy to manage SSL certificate+- Can use separate CDN configuration++**Cons:**+- Additional DNS lookup (minor performance impact)+- Need to manage subdomain DNS++</Tab>+<Tab value="path-based-proxy" title="Path-Based Proxy">++Use a path on your main domain:++```+https://yourdomain.com/analytics/script.js β https://app.rybbit.io/api/script.js+https://yourdomain.com/analytics/track β https://app.rybbit.io/api/track+```++**Pros:**+- No additional DNS lookup+- Single SSL certificate+- Truly first-party from browser perspective++**Cons:**+- Must ensure proxy path doesn't conflict with your app routes++</Tab>+</Tabs>++## Security Considerations++### Rate Limiting++Consider adding rate limiting to prevent abuse:++- Limit POST requests to tracking endpoints (e.g., 100 requests per minute per IP)+- Whitelist your Rybbit backend IP if possible+- Monitor for unusual traffic patterns++### Request Size Limits++Set appropriate request body size limits:++- `/api/track`, `/api/identify`: 1 MB max+- `/api/session-replay/record/*`: 10 MB max (session replay can send large payloads)++### HTTPS Only++Always serve your proxy over HTTPS:++- Modern browsers require HTTPS for many features+- Protects user data in transit+- Required for accurate tracking in secure contexts++## Troubleshooting++If something isn't working, check:++1. **Script loads but no events tracked**: Verify all tracking endpoints (`/api/track`, etc.) are proxied+2. **CORS errors**: Ensure CORS headers are preserved from Rybbit backend+3. **404 errors**: Check that URL paths exactly match expected format+4. **Incorrect geolocation**: Verify `X-Forwarded-For` header is forwarded+5. **Session replay not working**: Add `/api/replay.js` and `/api/session-replay/record/:siteId` endpoints++For more detailed troubleshooting, see our [troubleshooting guide](/docs/proxy-guide/troubleshooting).++## Next Steps++Now that you understand the generic concepts, choose your specific framework or platform for detailed implementation instructions:++- [Next.js](/docs/proxy-guide/next-js)+- [Nginx](/docs/proxy-guide/nginx)+- [Caddy](/docs/proxy-guide/caddy)+- [Vercel](/docs/proxy-guide/vercel)+- [Express.js](/docs/proxy-guide/express)+- [Laravel](/docs/proxy-guide/laravel)+- [Astro](/docs/proxy-guide/astro)+- [Cloudflare Workers](/docs/proxy-guide/cloudflare-workers)diff --git a/docs/content/docs/proxy-guide/index.mdx b/docs/content/docs/proxy-guide/index.mdxnew file mode 100644index 000000000..c68a27aed--- /dev/null+++ b/docs/content/docs/proxy-guide/index.mdx@@ -0,0 +1,121 @@+---+title: Proxy Setup Guide+description: Bypass ad blockers and improve tracking accuracy by proxying Rybbit through your own domain+---++import { Cards, Card } from 'fumadocs-ui/components/card';+import { Callout } from 'fumadocs-ui/components/callout';++Proxying Rybbit's tracking script through your own domain helps bypass ad blockers and improves tracking accuracy by making all analytics requests appear as first-party traffic.++## What is Proxy Setup?++When you add Rybbit's tracking script directly to your website using the default installation:++```html+<script src="https://app.rybbit.io/api/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++The browser loads the script from `app.rybbit.io`, which ad blockers can identify and block as third-party analytics. Even though Rybbit is privacy-focused and doesn't use cookies, some ad blockers use aggressive blocking rules that target any analytics domains.++**Proxying solves this** by serving the tracking script and handling tracking requests through your own domain (e.g., `yourdomain.com/analytics/script.js`), making all tracking appear as first-party traffic.++<Callout type="info">+Rybbit is fully compliant with GDPR, CCPA, and other privacy regulations. It uses cookieless tracking based on IP + User Agent hashing with optional daily rotating salts. Proxying is about improving data accuracy, not circumventing privacy laws.+</Callout>++## Why Proxy Rybbit?++### Improve Tracking Accuracy++Ad blockers are becoming increasingly aggressive and may block analytics scripts regardless of their privacy practices. By proxying through your own domain:++- **Bypass ad blocker detection**: Requests appear as first-party traffic to your own domain+- **Increase data completeness**: Typical improvement of 10-30% in tracked sessions+- **Maintain accurate metrics**: Get a true picture of your website's performance++### Stay Privacy-Compliant++Proxying doesn't compromise user privacy:++- No cookies are used (Rybbit remains cookieless)+- User data is still processed according to your privacy policy+- GDPR, CCPA, and other privacy regulations remain fully satisfied+- Users can still opt out through browser settings or Do Not Track++### Better Performance (Optional)++With proper caching configuration, proxying can also improve performance:++- Serve scripts from your CDN or edge network+- Reduce DNS lookups (one less domain to resolve)+- Cache static scripts closer to your users++## How It Works++Here's the flow when you proxy Rybbit:++1. **User visits your website**: Your HTML includes the tracking script from your domain+ ```html+ <script src="https://yourdomain.com/analytics/script.js" data-site-id="123"></script>+ ```++2. **Script loads from your domain**: Your server proxies the request to Rybbit's servers+ - Request: `yourdomain.com/analytics/script.js` β proxied to β `app.rybbit.io/api/script.js`++3. **Script auto-discovers analytics host**: The Rybbit script automatically detects the domain it was loaded from+ ```typescript+ // The script extracts the host from its own src attribute+ const analyticsHost = src.split("/script.js")[0];+ // Result: "https://yourdomain.com/analytics"+ ```++4. **Tracking data sent through your domain**: All analytics events are sent to your domain and proxied to Rybbit+ - Event tracking: `yourdomain.com/analytics/track` β proxied to β `app.rybbit.io/api/track`+ - Session replay: `yourdomain.com/analytics/session-replay/record/{siteId}` β proxied+ - Configuration: `yourdomain.com/analytics/site/tracking-config/{siteId}` β proxied++5. **Data appears in your Rybbit dashboard**: No changes needed in the Rybbit interface++<Callout type="warn">+**Bandwidth Consideration**: All tracking requests will flow through your server infrastructure, which will increase bandwidth usage. For most sites this is minimal (typically 10-50KB per session), but consider this when evaluating hosting costs.+</Callout>++## Choose Your Framework++Select the framework or platform that matches your setup:++<Cards>+ <Card title="Next.js" href="/docs/proxy-guide/next-js">+ Configure Next.js rewrites for seamless proxying+ </Card>+ <Card title="Nginx" href="/docs/proxy-guide/nginx">+ Set up Nginx reverse proxy with caching+ </Card>+ <Card title="Caddy" href="/docs/proxy-guide/caddy">+ Use Caddy's reverse proxy with automatic HTTPS+ </Card>+ <Card title="Vercel" href="/docs/proxy-guide/vercel">+ Deploy proxy configuration on Vercel+ </Card>+ <Card title="Express.js" href="/docs/proxy-guide/express">+ Proxy through Express middleware+ </Card>+ <Card title="Laravel" href="/docs/proxy-guide/laravel">+ Implement proxy in Laravel PHP application+ </Card>+ <Card title="Astro" href="/docs/proxy-guide/astro">+ Configure Astro middleware for proxying+ </Card>+ <Card title="Cloudflare Workers" href="/docs/proxy-guide/cloudflare-workers">+ Use Cloudflare Workers for edge proxying+ </Card>+</Cards>++## Generic Implementation++If your framework isn't listed above, check out our [generic implementation guide](/docs/proxy-guide/get-started) that covers the core concepts applicable to any reverse proxy or server setup.++## Need Help?++If you encounter issues during setup, check our [troubleshooting guide](/docs/proxy-guide/troubleshooting) for common problems and solutions.diff --git a/docs/content/docs/proxy-guide/laravel.mdx b/docs/content/docs/proxy-guide/laravel.mdxnew file mode 100644index 000000000..e5a441cc8--- /dev/null+++ b/docs/content/docs/proxy-guide/laravel.mdx@@ -0,0 +1,485 @@+---+title: Laravel Proxy Setup+description: Configure Laravel routes and middleware to proxy Rybbit tracking+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Laravel makes it straightforward to proxy Rybbit tracking using routes and the HTTP client. This guide shows how to set up proxy endpoints in your Laravel application.++## Overview++Laravel's HTTP client (built on Guzzle) provides an elegant way to proxy requests to Rybbit servers while maintaining full control over headers, caching, and error handling.++**What you'll achieve:**+- Proxy all Rybbit endpoints through your Laravel app+- Forward necessary headers for accurate tracking+- Optional caching with Laravel Cache+- Support all Rybbit features++## Prerequisites++- Laravel 8 or later+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID++## Implementation++<Steps>++### Configure Environment Variables++Add your Rybbit host to `.env`:++```bash+# .env+RYBBIT_HOST=https://app.rybbit.io+# For self-hosted: RYBBIT_HOST=https://analytics.yourcompany.com+```++### Create Analytics Controller++Generate a controller for handling analytics proxying:++```bash+php artisan make:controller AnalyticsProxyController+```++Then implement the proxy logic:++```php+<?php+// app/Http/Controllers/AnalyticsProxyController.php++namespace App\Http\Controllers;++use Illuminate\Http\Request;+use Illuminate\Support\Facades\Http;+use Illuminate\Support\Facades\Cache;++class AnalyticsProxyController extends Controller+{+ private string $rybbitHost;++ public function __construct()+ {+ $this->rybbitHost = config('services.rybbit.host', 'https://app.rybbit.io');+ }++ /**+ * Proxy script requests (GET)+ */+ public function proxyScript(Request $request, string $script)+ {+ // Cache scripts for 1 hour+ $cacheKey = "rybbit_script_{$script}";++ return Cache::remember($cacheKey, 3600, function () use ($script, $request) {+ return $this->forwardRequest("api/{$script}", 'GET', $request);+ });+ }++ /**+ * Proxy tracking requests (POST)+ */+ public function proxyTrack(Request $request)+ {+ return $this->forwardRequest('api/track', 'POST', $request);+ }++ /**+ * Proxy identify requests (POST)+ */+ public function proxyIdentify(Request $request)+ {+ return $this->forwardRequest('api/identify', 'POST', $request);+ }++ /**+ * Proxy session replay recording (POST)+ */+ public function proxySessionReplay(Request $request, string $siteId)+ {+ return $this->forwardRequest("api/session-replay/record/{$siteId}", 'POST', $request);+ }++ /**+ * Proxy site configuration (GET)+ */+ public function proxySiteConfig(Request $request, string $siteId)+ {+ // Cache config for 5 minutes+ $cacheKey = "rybbit_config_{$siteId}";++ return Cache::remember($cacheKey, 300, function () use ($siteId, $request) {+ return $this->forwardRequest("site/tracking-config/{$siteId}", 'GET', $request);+ });+ }++ /**+ * Forward request to Rybbit backend+ */+ private function forwardRequest(string $path, string $method, Request $request)+ {+ $url = "{$this->rybbitHost}/{$path}";++ // Get client IP+ $clientIp = $request->header('X-Forwarded-For', $request->ip());++ // Build HTTP request+ $httpRequest = Http::timeout(30)+ ->withHeaders([+ 'X-Real-IP' => $clientIp,+ 'X-Forwarded-For' => $clientIp,+ 'User-Agent' => $request->header('User-Agent'),+ 'Referer' => $request->header('Referer', ''),+ ]);++ try {+ if ($method === 'POST') {+ $response = $httpRequest->post($url, $request->all());+ } else {+ $response = $httpRequest->get($url);+ }++ return response($response->body(), $response->status())+ ->header('Content-Type', $response->header('Content-Type'));+ } catch (\Exception $e) {+ \Log::error('Rybbit proxy error', [+ 'url' => $url,+ 'error' => $e->getMessage(),+ ]);++ return response()->json(['error' => 'Analytics proxy error'], 500);+ }+ }+}+```++### Add Routes++Add routes for the analytics proxy in `routes/web.php`:++```php+<?php+// routes/web.php++use App\Http\Controllers\AnalyticsProxyController;++// Analytics proxy routes+Route::prefix('analytics')->group(function () {+ // Scripts (GET)+ Route::get('/{script}', [AnalyticsProxyController::class, 'proxyScript'])+ ->where('script', '(script|script-full|replay|metrics)\.js');++ // Tracking endpoints (POST)+ Route::post('/track', [AnalyticsProxyController::class, 'proxyTrack']);+ Route::post('/identify', [AnalyticsProxyController::class, 'proxyIdentify']);+ Route::post('/session-replay/record/{siteId}', [AnalyticsProxyController::class, 'proxySessionReplay']);++ // Configuration (GET)+ Route::get('/site/tracking-config/{siteId}', [AnalyticsProxyController::class, 'proxySiteConfig']);+});+```++### Add Service Configuration (Optional)++Add Rybbit configuration to `config/services.php`:++```php+<?php+// config/services.php++return [+ // ... other services++ 'rybbit' => [+ 'host' => env('RYBBIT_HOST', 'https://app.rybbit.io'),+ ],+];+```++### Update Your Blade Templates++Add the tracking script to your layout:++```blade+{{-- resources/views/layouts/app.blade.php --}}+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <title>{{ config('app.name') }}</title>++ {{-- Rybbit Analytics --}}+ <script src="{{ url('/analytics/script.js') }}" async data-site-id="YOUR_SITE_ID"></script>+</head>+<body>+ @yield('content')+</body>+</html>+```++### Verify the Setup++1. **Clear route cache** (if caching enabled):+ ```bash+ php artisan route:clear+ ```++2. **Visit your application** with Developer Tools open+3. **Check Network tab**: Requests should go to `/analytics/*`+4. **Verify in Rybbit dashboard**: Data should appear++</Steps>++## How It Works++Laravel routes intercept requests to `/analytics/*` and forward them to Rybbit:++1. Request to `/analytics/script.js` hits Laravel route+2. Controller forwards to `https://app.rybbit.io/api/script.js`+3. Response is cached (for cacheable endpoints)+4. Client IP and headers are preserved for accurate tracking++## Advanced Configuration++### Middleware for Rate Limiting++Create rate limiting middleware:++```bash+php artisan make:middleware RateLimitAnalytics+```++```php+<?php+// app/Http/Middleware/RateLimitAnalytics.php++namespace App\Http\Middleware;++use Closure;+use Illuminate\Cache\RateLimiter;++class RateLimitAnalytics+{+ protected $limiter;++ public function __construct(RateLimiter $limiter)+ {+ $this->limiter = $limiter;+ }++ public function handle($request, Closure $next)+ {+ $key = 'analytics:' . $request->ip();++ if ($this->limiter->tooManyAttempts($key, 100)) {+ return response('Too Many Requests', 429);+ }++ $this->limiter->hit($key, 60); // 100 requests per minute++ return $next($request);+ }+}+```++Register in `app/Http/Kernel.php`:++```php+protected $routeMiddleware = [+ // ... other middleware+ 'rate.limit.analytics' => \App\Http\Middleware\RateLimitAnalytics::class,+];+```++Apply to routes:++```php+Route::prefix('analytics')->middleware('rate.limit.analytics')->group(function () {+ // ... routes+});+```++### Custom Cache Configuration++Use different cache drivers for analytics:++```php+private function forwardRequest(string $path, string $method, Request $request)+{+ // Use Redis for analytics caching+ $cache = Cache::store('redis');++ // Or use file cache+ // $cache = Cache::store('file');++ // ... rest of the method+}+```++### Queue Large Requests++For large session replay uploads, use queues:++```bash+php artisan make:job ForwardAnalyticsData+```++```php+<?php+// app/Jobs/ForwardAnalyticsData.php++namespace App\Jobs;++use Illuminate\Bus\Queueable;+use Illuminate\Contracts\Queue\ShouldQueue;+use Illuminate\Support\Facades\Http;++class ForwardAnalyticsData implements ShouldQueue+{+ use Queueable;++ protected $url;+ protected $data;+ protected $headers;++ public function __construct(string $url, array $data, array $headers)+ {+ $this->url = $url;+ $this->data = $data;+ $this->headers = $headers;+ }++ public function handle()+ {+ Http::withHeaders($this->headers)+ ->post($this->url, $this->data);+ }+}+```++Use in controller for session replay:++```php+public function proxySessionReplay(Request $request, string $siteId)+{+ // Dispatch job for async processing+ ForwardAnalyticsData::dispatch(+ "{$this->rybbitHost}/api/session-replay/record/{$siteId}",+ $request->all(),+ [+ 'X-Real-IP' => $request->ip(),+ 'User-Agent' => $request->header('User-Agent'),+ ]+ );++ return response()->json(['status' => 'queued']);+}+```++### CORS Configuration++If serving from a different domain:++```php+<?php+// config/cors.php++return [+ 'paths' => ['analytics/*'],+ 'allowed_methods' => ['GET', 'POST'],+ 'allowed_origins' => ['https://yourdomain.com'],+ 'allowed_headers' => ['Content-Type', 'X-Requested-With'],+];+```++## Troubleshooting++### 404 Not Found++**Problem**: Routes return 404.++**Solution**:+1. Clear route cache: `php artisan route:clear`+2. List routes to verify: `php artisan route:list --path=analytics`+3. Check route order (more specific routes first)++### Session errors with POST requests++**Problem**: CSRF token errors on tracking endpoints.++**Solution**:+Exclude analytics routes from CSRF protection in `app/Http/Middleware/VerifyCsrfToken.php`:++```php+protected $except = [+ 'analytics/*',+];+```++### Incorrect geolocation++**Problem**: All visitors show server's location.++**Solution**:+Ensure IP forwarding in controller:+```php+$clientIp = $request->header('X-Forwarded-For', $request->ip());+```++And add to HTTP request:+```php+'X-Real-IP' => $clientIp,+'X-Forwarded-For' => $clientIp,+```++### Cache not clearing++**Problem**: Old script cached after Rybbit update.++**Solution**:+Clear specific cache key:+```bash+php artisan cache:forget rybbit_script_script.js+```++Or clear all cache:+```bash+php artisan cache:clear+```++## Performance Optimization++### Cache Optimization++```php+// Configure cache tags for easy clearing+Cache::tags(['rybbit', 'scripts'])->remember($cacheKey, 3600, function () {+ // ... fetch script+});++// Clear all Rybbit cache+Cache::tags(['rybbit'])->flush();+```++### HTTP Client Optimization++```php+// Use connection pooling+Http::pool(fn (Pool $pool) => [+ $pool->get("{$this->rybbitHost}/api/script.js"),+ $pool->get("{$this->rybbitHost}/api/replay.js"),+]);+```++## Related Resources++- [Laravel Integration Guide](/docs/guides/laravel) - General Laravel integration+- [Tracking Script Documentation](/docs/script) - Script configuration+- [Laravel HTTP Client](https://laravel.com/docs/http-client) - Official Laravel docsdiff --git a/docs/content/docs/proxy-guide/meta.json b/docs/content/docs/proxy-guide/meta.jsonnew file mode 100644index 000000000..1c065ca86--- /dev/null+++ b/docs/content/docs/proxy-guide/meta.json@@ -0,0 +1,18 @@+{+ "title": "Proxy Guide",+ "pages": [+ "index",+ "get-started",+ "---Frameworks---",+ "next-js",+ "nginx",+ "caddy",+ "vercel",+ "express",+ "laravel",+ "astro",+ "cloudflare-workers",+ "---Help---",+ "troubleshooting"+ ]+}diff --git a/docs/content/docs/proxy-guide/next-js.mdx b/docs/content/docs/proxy-guide/next-js.mdxnew file mode 100644index 000000000..e5da548d5--- /dev/null+++ b/docs/content/docs/proxy-guide/next-js.mdx@@ -0,0 +1,516 @@+---+title: Next.js Proxy Setup+description: Configure Next.js rewrites to proxy Rybbit tracking and bypass ad blockers+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Next.js provides a powerful [rewrites](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites) feature that makes it easy to proxy Rybbit tracking through your own domain. This guide works with both the App Router (Next.js 13+) and Pages Router.++## Overview++Next.js rewrites allow you to map incoming request paths to different destination URLs transparently. This is perfect for proxying analytics since the browser sees requests to your domain while Next.js forwards them to Rybbit's servers behind the scenes.++**What you'll achieve:**+- Serve Rybbit scripts from your domain (e.g., `/analytics/script.js`)+- Proxy all tracking requests through your Next.js application+- Bypass ad blocker detection with first-party requests+- Support all Rybbit features (session replay, Web Vitals, custom events)++## Prerequisites++- Next.js 12 or later (rewrites are supported in all modern versions)+- Your Rybbit site ID (found in your dashboard)+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL (e.g., `https://analytics.yourcompany.com`)++## Implementation++<Steps>++### Configure Environment Variables++Create or update your `.env` or `.env.local` file with your Rybbit instance URL:++<Tabs>+<Tab value="cloud-hosted" title="Cloud Hosted">++```bash+# .env.local+NEXT_PUBLIC_RYBBIT_HOST=https://app.rybbit.io+```++</Tab>+<Tab value="self-hosted" title="Self-Hosted">++```bash+# .env.local+NEXT_PUBLIC_RYBBIT_HOST=https://analytics.yourcompany.com+```++Replace `analytics.yourcompany.com` with your actual Rybbit instance domain.++</Tab>+</Tabs>++<Callout type="info">+The `NEXT_PUBLIC_` prefix makes this environment variable available in both server and client environments, though it's primarily used during build time for the rewrites configuration.+</Callout>++### Set Up Rewrites in next.config.js++Add or update the `rewrites` function in your `next.config.js` (or `next.config.mjs` for ESM):++<Tabs>+<Tab value="full-proxy-recommended" title="Full Proxy (Recommended)">++This configuration proxies all Rybbit endpoints including session replay and Web Vitals:++```javascript+// next.config.js+/** @type {import('next').NextConfig} */+const nextConfig = {+ async rewrites() {+ const rybbitHost = process.env.NEXT_PUBLIC_RYBBIT_HOST;++ if (!rybbitHost) {+ console.warn('NEXT_PUBLIC_RYBBIT_HOST is not set. Rybbit proxy will not work.');+ return [];+ }++ return [+ // Tracking scripts+ {+ source: '/analytics/script.js',+ destination: `${rybbitHost}/api/script.js`,+ },+ {+ source: '/analytics/script-full.js',+ destination: `${rybbitHost}/api/script-full.js`,+ },+ {+ source: '/analytics/replay.js',+ destination: `${rybbitHost}/api/replay.js`,+ },+ {+ source: '/analytics/metrics.js',+ destination: `${rybbitHost}/api/metrics.js`,+ },+ // Tracking endpoints+ {+ source: '/analytics/track',+ destination: `${rybbitHost}/api/track`,+ },+ {+ source: '/analytics/identify',+ destination: `${rybbitHost}/api/identify`,+ },+ {+ source: '/analytics/session-replay/record/:siteId',+ destination: `${rybbitHost}/api/session-replay/record/:siteId`,+ },+ {+ source: '/analytics/site/tracking-config/:siteId',+ destination: `${rybbitHost}/site/tracking-config/:siteId`,+ },+ ];+ },+};++module.exports = nextConfig;+```++</Tab>+<Tab value="minimal-proxy" title="Minimal Proxy">++Minimal setup with just script loading and basic event tracking:++```javascript+// next.config.js+/** @type {import('next').NextConfig} */+const nextConfig = {+ async rewrites() {+ const rybbitHost = process.env.NEXT_PUBLIC_RYBBIT_HOST;++ if (!rybbitHost) {+ console.warn('NEXT_PUBLIC_RYBBIT_HOST is not set. Rybbit proxy will not work.');+ return [];+ }++ return [+ {+ source: '/analytics/script.js',+ destination: `${rybbitHost}/api/script.js`,+ },+ {+ source: '/analytics/track',+ destination: `${rybbitHost}/api/track`,+ },+ ];+ },+};++module.exports = nextConfig;+```++<Callout type="warn">+This minimal setup won't support session replay or Web Vitals. Use the full proxy configuration if you need these features.+</Callout>++</Tab>+<Tab value="esm-nextconfigmjs" title="ESM (next.config.mjs)">++If you're using ES modules:++```javascript+// next.config.mjs+/** @type {import('next').NextConfig} */+const nextConfig = {+ async rewrites() {+ const rybbitHost = process.env.NEXT_PUBLIC_RYBBIT_HOST;++ if (!rybbitHost) {+ console.warn('NEXT_PUBLIC_RYBBIT_HOST is not set. Rybbit proxy will not work.');+ return [];+ }++ return [+ {+ source: '/analytics/script.js',+ destination: `${rybbitHost}/api/script.js`,+ },+ {+ source: '/analytics/track',+ destination: `${rybbitHost}/api/track`,+ },+ {+ source: '/analytics/replay.js',+ destination: `${rybbitHost}/api/replay.js`,+ },+ {+ source: '/analytics/metrics.js',+ destination: `${rybbitHost}/api/metrics.js`,+ },+ {+ source: '/analytics/identify',+ destination: `${rybbitHost}/api/identify`,+ },+ {+ source: '/analytics/session-replay/record/:siteId',+ destination: `${rybbitHost}/api/session-replay/record/:siteId`,+ },+ {+ source: '/analytics/site/tracking-config/:siteId',+ destination: `${rybbitHost}/site/tracking-config/:siteId`,+ },+ ];+ },+};++export default nextConfig;+```++</Tab>+</Tabs>++<Callout type="info">+**Custom Path**: You can change `/analytics` to any path you prefer (e.g., `/tracking`, `/stats`, `/rybbit`). Just ensure you use the same path consistently in both your rewrites and script tag.+</Callout>++### Update Your Tracking Script++Update your script tag to load from the proxied path instead of directly from Rybbit:++<Tabs>+<Tab value="app-router-nextjs-13" title="App Router (Next.js 13+)">++Update your root layout file:++```tsx+// app/layout.tsx+import Script from 'next/script';++export default function RootLayout({+ children,+}: {+ children: React.ReactNode;+}) {+ return (+ <html lang="en">+ <body>+ {children}+ <Script+ src="/analytics/script.js"+ data-site-id="YOUR_SITE_ID"+ strategy="afterInteractive"+ />+ </body>+ </html>+ );+}+```++Replace `YOUR_SITE_ID` with your actual site ID from the Rybbit dashboard.++</Tab>+<Tab value="pages-router" title="Pages Router">++Update your `_app.tsx` or `_app.jsx` file:++```tsx+// pages/_app.tsx+import Script from 'next/script';+import type { AppProps } from 'next/app';++function MyApp({ Component, pageProps }: AppProps) {+ return (+ <>+ <Component {...pageProps} />+ <Script+ src="/analytics/script.js"+ data-site-id="YOUR_SITE_ID"+ strategy="afterInteractive"+ />+ </>+ );+}++export default MyApp;+```++Replace `YOUR_SITE_ID` with your actual site ID from the Rybbit dashboard.++</Tab>+<Tab value="javascript-no-typescript" title="JavaScript (No TypeScript)">++```jsx+// app/layout.js or pages/_app.js+import Script from 'next/script';++export default function RootLayout({ children }) {+ return (+ <html lang="en">+ <body>+ {children}+ <Script+ src="/analytics/script.js"+ data-site-id="YOUR_SITE_ID"+ strategy="afterInteractive"+ />+ </body>+ </html>+ );+}+```++</Tab>+</Tabs>++### Restart Your Development Server++After updating `next.config.js`, restart your Next.js development server for the changes to take effect:++```bash+# Stop the server (Ctrl+C) and restart+npm run dev+# or+yarn dev+# or+pnpm dev+```++### Verify the Setup++Open your website in a browser with Developer Tools:++1. **Open the Network tab** and filter by "analytics" or "script"+2. **Verify the script loads**:+ - You should see a request to `/analytics/script.js` (not `app.rybbit.io`)+ - Status should be `200 OK`+ - The domain should be your own domain+3. **Verify tracking works**:+ - Navigate to another page or trigger an event+ - You should see POST requests to `/analytics/track`+ - All requests should show your domain, not `app.rybbit.io`+4. **Check the Rybbit dashboard**:+ - Wait 1-2 minutes for data processing+ - Verify your session appears in the real-time dashboard++</Steps>++## How It Works++The Rybbit tracking script has a built-in auto-discovery mechanism. When it loads from:++```html+<script src="/analytics/script.js" data-site-id="123"></script>+```++It automatically extracts the analytics host from its own `src` attribute:++```typescript+// Inside Rybbit's script+const scriptElement = document.currentScript;+const src = scriptElement.getAttribute('src');+const analyticsHost = src.split('/script.js')[0];+// Result: "" (empty string means same domain)+```++This means all tracking requests automatically go to `/analytics/track`, `/analytics/identify`, etc., which Next.js then rewrites to forward to Rybbit's servers.++## Performance Considerations++### Bandwidth Usage++All tracking requests now flow through your Next.js server, which will increase bandwidth usage:++<Callout type="warn">+**Bandwidth Impact**: Each session typically uses 10-50 KB without session replay, or 50-500 KB with session replay enabled. For a site with 100,000 monthly sessions, expect 5-10 GB/month additional bandwidth without replay, or 30-80 GB/month with replay.+</Callout>++Most Vercel, Netlify, or other hosting plans can handle this, but check your plan's bandwidth limits if you have high traffic.++### Caching++Next.js automatically caches responses when possible, but you can optimize further:++**Using Vercel Edge Network:**+If deployed on Vercel, your rewrites benefit from the global Edge Network, which caches static scripts close to users worldwide.++**Custom caching headers:**+The Rybbit server sets appropriate cache headers, which Next.js respects:+- Scripts (`.js` files): Cached for 1 hour+- Configuration: Cached for 5 minutes+- Tracking POSTs: Not cached++### Server Load++Rewrites are handled at the edge on Vercel, so there's minimal impact on your serverless functions. For self-hosted Next.js, consider:++- Using a CDN (Cloudflare, CloudFront, etc.) in front of Next.js+- Scaling your server if you have very high traffic+- Monitoring server response times++## Troubleshooting++### Script loads but events aren't tracked++**Problem**: You see the script load successfully, but no tracking data appears in the dashboard.++**Solution**:+1. Check that `/analytics/track` is included in your rewrites+2. Verify POST requests to `/analytics/track` return `200 OK` in Network tab+3. Check for CORS errors in the browser console+4. Ensure your Rybbit instance URL is correct in `.env.local`++### 404 errors on tracking endpoints++**Problem**: Script loads fine, but tracking requests return 404.++**Solution**:+1. Verify all tracking endpoints are in your `rewrites()` configuration+2. Restart your dev server after changing `next.config.js`+3. Clear your browser cache+4. Check that the endpoint paths exactly match (case-sensitive)++### Session replay not working++**Problem**: Basic tracking works but session replay doesn't record.++**Solution**:+Add the session replay endpoints to your rewrites:++```javascript+{+ source: '/analytics/replay.js',+ destination: `${rybbitHost}/api/replay.js`,+},+{+ source: '/analytics/session-replay/record/:siteId',+ destination: `${rybbitHost}/api/session-replay/record/:siteId`,+},+```++### Environment variable not loading++**Problem**: Rewrites don't work, console shows warning about missing `NEXT_PUBLIC_RYBBIT_HOST`.++**Solution**:+1. Ensure you created `.env.local` in your project root+2. Restart your dev server after creating `.env.local`+3. For production, ensure environment variables are set in your hosting platform (Vercel, Netlify, etc.)++## Deployment Considerations++### Vercel++When deploying to Vercel:+1. Add `NEXT_PUBLIC_RYBBIT_HOST` environment variable in your Vercel project settings+2. Rewrites automatically work at the edge with zero configuration+3. Bandwidth is generous on all Vercel plans++### Self-Hosted++When self-hosting Next.js:+1. Ensure environment variables are available to the Next.js process+2. Consider adding a CDN layer for better caching and reduced bandwidth+3. Monitor server load if you have high traffic++### Other Platforms (Netlify, AWS, etc.)++1. Set environment variables in your platform's settings+2. Verify rewrites are supported (most platforms support Next.js rewrites)+3. Check bandwidth limits for your plan++## Advanced Configuration++### Different paths for different environments++You can customize the proxy path based on the environment:++```javascript+// next.config.js+const nextConfig = {+ async rewrites() {+ const rybbitHost = process.env.NEXT_PUBLIC_RYBBIT_HOST;+ const analyticsPath = process.env.NODE_ENV === 'development'+ ? '/dev-analytics'+ : '/analytics';++ return [+ {+ source: `${analyticsPath}/script.js`,+ destination: `${rybbitHost}/api/script.js`,+ },+ // ... other rewrites+ ];+ },+};+```++### Conditional proxy (development only)++If you only want proxying in production:++```javascript+// next.config.js+const nextConfig = {+ async rewrites() {+ if (process.env.NODE_ENV === 'development') {+ return []; // No proxy in development+ }++ // ... production rewrites+ },+};+```++## Related Resources++- [Next.js Integration Guide](/docs/guides/react/next-js) - General Next.js integration+- [Tracking Script Documentation](/docs/script) - Script configuration options+- [Custom Events](/docs/track-events) - Track custom events+- [Next.js Rewrites Documentation](https://nextjs.org/docs/app/api-reference/next-config-js/rewrites) - Official Next.js docsdiff --git a/docs/content/docs/proxy-guide/nginx.mdx b/docs/content/docs/proxy-guide/nginx.mdxnew file mode 100644index 000000000..5dbf3f631--- /dev/null+++ b/docs/content/docs/proxy-guide/nginx.mdx@@ -0,0 +1,592 @@+---+title: Nginx Proxy Setup+description: Configure Nginx reverse proxy to serve Rybbit tracking and bypass ad blockers+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';+import { Tabs, Tab } from 'fumadocs-ui/components/tabs';++Nginx is a powerful web server and reverse proxy that makes it easy to proxy Rybbit tracking through your own domain. This guide shows how to configure Nginx to forward tracking requests to Rybbit servers while caching static scripts for better performance.++## Overview++Nginx's `proxy_pass` directive lets you forward requests from your domain to Rybbit's servers. Combined with caching, this provides excellent performance and reliability for proxying analytics.++**What you'll achieve:**+- Proxy all Rybbit endpoints through your domain+- Cache static scripts for better performance+- Forward necessary headers for accurate tracking+- Support all Rybbit features (session replay, Web Vitals, custom events)++## Prerequisites++- Nginx installed (version 1.18 or later recommended)+- SSL/TLS certificate configured (Let's Encrypt recommended)+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID (found in your dashboard)++## Implementation++<Steps>++### Configure Nginx Proxy++Add a new location block (or update existing configuration) in your Nginx site configuration:++<Tabs>+<Tab value="full-proxy-recommended" title="Full Proxy (Recommended)">++```nginx+# /etc/nginx/sites-available/yourdomain.com+server {+ listen 443 ssl http2;+ server_name yourdomain.com;++ # Your SSL configuration+ ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;+ ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;++ # Your main site configuration+ location / {+ # Your regular site config...+ }++ # Rybbit Analytics Proxy+ # Main tracking script (cached)+ location = /analytics/script.js {+ proxy_pass https://app.rybbit.io/api/script.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_ssl_server_name on;++ # Cache for 1 hour+ proxy_cache_valid 200 1h;+ proxy_cache_bypass $http_cache_control;+ add_header X-Cache-Status $upstream_cache_status;+ }++ # Unminified script for debugging (cached)+ location = /analytics/script-full.js {+ proxy_pass https://app.rybbit.io/api/script-full.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_ssl_server_name on;++ proxy_cache_valid 200 1h;+ }++ # Session replay script (cached)+ location = /analytics/replay.js {+ proxy_pass https://app.rybbit.io/api/replay.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_ssl_server_name on;++ proxy_cache_valid 200 1h;+ }++ # Web Vitals metrics script (cached)+ location = /analytics/metrics.js {+ proxy_pass https://app.rybbit.io/api/metrics.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_ssl_server_name on;++ proxy_cache_valid 200 1h;+ }++ # Event tracking endpoint (not cached)+ location = /analytics/track {+ proxy_pass https://app.rybbit.io/api/track;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header Content-Type application/json;+ proxy_ssl_server_name on;+ }++ # User identification endpoint (not cached)+ location = /analytics/identify {+ proxy_pass https://app.rybbit.io/api/identify;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header Content-Type application/json;+ proxy_ssl_server_name on;+ }++ # Session replay recording endpoint (not cached)+ location ~ ^/analytics/session-replay/record/(.*)$ {+ proxy_pass https://app.rybbit.io/api/session-replay/record/$1;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_set_header Content-Type application/json;+ proxy_ssl_server_name on;++ # Allow larger uploads for session replay+ client_max_body_size 10M;+ }++ # Site configuration endpoint (cached briefly)+ location ~ ^/analytics/site/tracking-config/(.*)$ {+ proxy_pass https://app.rybbit.io/site/tracking-config/$1;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_set_header X-Forwarded-Proto $scheme;+ proxy_ssl_server_name on;++ # Cache for 5 minutes+ proxy_cache_valid 200 5m;+ }+}+```++<Callout type="info">+Replace `app.rybbit.io` with your self-hosted Rybbit instance URL if you're not using the cloud version.+</Callout>++</Tab>+<Tab value="minimal-proxy" title="Minimal Proxy">++Minimal configuration for basic tracking:++```nginx+# /etc/nginx/sites-available/yourdomain.com+server {+ listen 443 ssl http2;+ server_name yourdomain.com;++ # SSL configuration+ ssl_certificate /etc/letsencrypt/live/yourdomain.com/fullchain.pem;+ ssl_certificate_key /etc/letsencrypt/live/yourdomain.com/privkey.pem;++ # Main tracking script+ location = /analytics/script.js {+ proxy_pass https://app.rybbit.io/api/script.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_ssl_server_name on;++ proxy_cache_valid 200 1h;+ }++ # Event tracking+ location = /analytics/track {+ proxy_pass https://app.rybbit.io/api/track;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_ssl_server_name on;+ }+}+```++</Tab>+<Tab value="with-cache-zone" title="With Cache Zone">++For better performance with caching, define a cache zone:++```nginx+# /etc/nginx/nginx.conf (http block)+http {+ # Define cache zone for Rybbit+ proxy_cache_path /var/cache/nginx/rybbit+ levels=1:2+ keys_zone=rybbit_cache:10m+ max_size=100m+ inactive=60m+ use_temp_path=off;++ # ... rest of http config+}+```++Then in your site config:++```nginx+# /etc/nginx/sites-available/yourdomain.com+server {+ # ... server config++ location = /analytics/script.js {+ proxy_pass https://app.rybbit.io/api/script.js;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_ssl_server_name on;++ # Use the cache zone+ proxy_cache rybbit_cache;+ proxy_cache_valid 200 1h;+ proxy_cache_key "$scheme$request_method$host$request_uri";+ add_header X-Cache-Status $upstream_cache_status;+ }++ # ... other locations+}+```++</Tab>+</Tabs>++<Callout type="warn">+**Important**: The `proxy_set_header X-Real-IP` and `X-Forwarded-For` headers are critical for accurate geolocation and user identification. Without these, all traffic will appear to come from your Nginx server's IP.+</Callout>++### Create Cache Directory (Optional)++If using a cache zone, create the cache directory:++```bash+sudo mkdir -p /var/cache/nginx/rybbit+sudo chown www-data:www-data /var/cache/nginx/rybbit+```++### Test Nginx Configuration++Before reloading Nginx, test the configuration for syntax errors:++```bash+sudo nginx -t+```++You should see:+```+nginx: configuration file /etc/nginx/nginx.conf test is successful+```++### Reload Nginx++Apply the changes by reloading Nginx:++```bash+sudo systemctl reload nginx+```++Or if you prefer:++```bash+sudo nginx -s reload+```++### Update Your Tracking Script++Update your HTML to load the script from your proxied domain:++```html+<!DOCTYPE html>+<html>+<head>+ <!-- ... other head elements -->+ <script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+</head>+<body>+ <!-- Your content -->+</body>+</html>+```++Replace `YOUR_SITE_ID` with your actual site ID from the Rybbit dashboard.++### Verify the Setup++Test your configuration:++1. **Check Nginx is running**:+ ```bash+ sudo systemctl status nginx+ ```++2. **Test script loading**:+ ```bash+ curl -I https://yourdomain.com/analytics/script.js+ ```++ You should see:+ ```+ HTTP/2 200+ content-type: application/javascript+ x-cache-status: MISS # First request+ ```++3. **Test again to verify caching**:+ ```bash+ curl -I https://yourdomain.com/analytics/script.js+ ```++ You should see:+ ```+ HTTP/2 200+ x-cache-status: HIT # Cached!+ ```++4. **Open your website** in a browser with Developer Tools and verify:+ - Script loads from `/analytics/script.js` (your domain)+ - Tracking requests go to `/analytics/track` (your domain)+ - Data appears in your Rybbit dashboard after 1-2 minutes++</Steps>++## How It Works++Nginx's `proxy_pass` directive transparently forwards requests to Rybbit's servers:++1. Browser requests `https://yourdomain.com/analytics/script.js`+2. Nginx matches the location block and forwards to `https://app.rybbit.io/api/script.js`+3. Nginx sets necessary headers (`X-Real-IP`, `X-Forwarded-For`) for accurate tracking+4. Response is cached (if configured) and sent back to browser+5. All subsequent tracking requests follow the same pattern++The Rybbit script auto-detects it's being served from your domain and sends all tracking data to your domain's `/analytics/*` endpoints.++## Performance Optimization++### Caching Strategy++Configure different cache durations based on content type:++```nginx+# Scripts - cache for 1 hour+location ~ ^/analytics/(script|replay|metrics)\.js$ {+ proxy_pass https://app.rybbit.io/api/$1.js;+ # ... proxy headers+ proxy_cache_valid 200 1h;+ proxy_cache_valid 404 1m; # Cache 404s briefly+}++# Config - cache for 5 minutes (changes when you update dashboard settings)+location ~ ^/analytics/site/tracking-config/ {+ proxy_pass https://app.rybbit.io/site/tracking-config/;+ # ... proxy headers+ proxy_cache_valid 200 5m;+}++# Tracking - never cache (each request is unique)+location ~ ^/analytics/(track|identify)$ {+ proxy_pass https://app.rybbit.io/api/$1;+ # ... proxy headers+ # No caching directives+}+```++### Gzip Compression++Enable compression for JavaScript files:++```nginx+# In http or server block+gzip on;+gzip_vary on;+gzip_types application/javascript text/javascript;+gzip_min_length 1000;+```++### Connection Pooling++Keep connections to Rybbit backend alive for better performance:++```nginx+upstream rybbit_backend {+ server app.rybbit.io:443;+ keepalive 32;+}++location /analytics/ {+ proxy_pass https://rybbit_backend/api/;+ proxy_http_version 1.1;+ proxy_set_header Connection "";+ # ... other proxy headers+}+```++### Proxy Buffering++For better performance with larger session replay uploads:++```nginx+location ~ ^/analytics/session-replay/record/ {+ proxy_pass https://app.rybbit.io/api/session-replay/record/;+ # ... proxy headers++ proxy_buffering on;+ proxy_buffer_size 4k;+ proxy_buffers 8 4k;+ proxy_busy_buffers_size 8k;+ client_max_body_size 10M;+}+```++## Security Considerations++### Rate Limiting++Protect your proxy from abuse with rate limiting:++```nginx+# In http block+http {+ limit_req_zone $binary_remote_addr zone=analytics_limit:10m rate=10r/s;++ # ... rest of config+}++# In server block+location = /analytics/track {+ limit_req zone=analytics_limit burst=20 nodelay;+ proxy_pass https://app.rybbit.io/api/track;+ # ... proxy headers+}+```++This limits to 10 requests per second per IP, with bursts up to 20.++### Request Size Limits++Set appropriate limits for different endpoints:++```nginx+# Default for most endpoints+client_max_body_size 1M;++# Larger limit for session replay+location ~ ^/analytics/session-replay/record/ {+ client_max_body_size 10M;+ # ... proxy config+}+```++### Security Headers++Add security headers to your responses:++```nginx+add_header X-Content-Type-Options nosniff;+add_header X-Frame-Options DENY;+add_header Referrer-Policy strict-origin-when-cross-origin;+```++## Troubleshooting++### 502 Bad Gateway++**Problem**: Nginx returns 502 error when accessing analytics endpoints.++**Solution**:+1. Check Rybbit backend is accessible:+ ```bash+ curl -I https://app.rybbit.io/api/script.js+ ```+2. Verify `proxy_ssl_server_name on` is set+3. Check Nginx error logs:+ ```bash+ sudo tail -f /var/log/nginx/error.log+ ```++### Cache not working++**Problem**: `X-Cache-Status` always shows `MISS`.++**Solution**:+1. Verify cache directory exists and is writable+2. Check `proxy_cache_path` is defined in http block+3. Ensure `proxy_cache` directive uses correct zone name+4. Check cache key is consistent:+ ```nginx+ proxy_cache_key "$scheme$request_method$host$request_uri";+ ```++### Incorrect geolocation in Rybbit++**Problem**: All visitors show same location (your server's location).++**Solution**:+Ensure you're forwarding client IP headers:+```nginx+proxy_set_header X-Real-IP $remote_addr;+proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+```++### SSL errors in Nginx logs++**Problem**: Logs show SSL verification errors when connecting to Rybbit.++**Solution**:+Add `proxy_ssl_server_name on` to enable SNI:+```nginx+location /analytics/ {+ proxy_pass https://app.rybbit.io/api/;+ proxy_ssl_server_name on; # Enable SNI+ # ... other config+}+```++## Advanced Configuration++### Subdomain Proxy++Use a dedicated subdomain for analytics:++```nginx+# /etc/nginx/sites-available/analytics.yourdomain.com+server {+ listen 443 ssl http2;+ server_name analytics.yourdomain.com;++ ssl_certificate /etc/letsencrypt/live/analytics.yourdomain.com/fullchain.pem;+ ssl_certificate_key /etc/letsencrypt/live/analytics.yourdomain.com/privkey.pem;++ # Proxy all requests to Rybbit+ location / {+ proxy_pass https://app.rybbit.io/api/;+ proxy_set_header Host app.rybbit.io;+ proxy_set_header X-Real-IP $remote_addr;+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+ proxy_ssl_server_name on;+ }+}+```++Then use:+```html+<script src="https://analytics.yourdomain.com/script.js" data-site-id="123"></script>+```++### Multiple Rybbit Instances++If you need to proxy multiple Rybbit instances:++```nginx+location /analytics-prod/ {+ proxy_pass https://prod.rybbit.io/api/;+ # ... proxy config+}++location /analytics-staging/ {+ proxy_pass https://staging.rybbit.io/api/;+ # ... proxy config+}+```++## Related Resources++- [Nginx Custom Configuration Guide](/docs/self-hosting-guides/custom-nginx) - Self-hosting Rybbit with Nginx+- [Tracking Script Documentation](/docs/script) - Script configuration options+- [Generic Proxy Guide](/docs/proxy-guide/get-started) - Framework-agnostic concepts+- [Nginx Proxy Module](http://nginx.org/en/docs/http/ngx_http_proxy_module.html) - Official Nginx documentationdiff --git a/docs/content/docs/proxy-guide/troubleshooting.mdx b/docs/content/docs/proxy-guide/troubleshooting.mdxnew file mode 100644index 000000000..daa46a928--- /dev/null+++ b/docs/content/docs/proxy-guide/troubleshooting.mdx@@ -0,0 +1,611 @@+---+title: Troubleshooting Proxy Setup+description: Common issues and solutions for Rybbit proxy configurations+---++import { Callout } from 'fumadocs-ui/components/callout';+import { Steps } from 'fumadocs-ui/components/steps';++This guide covers common issues you might encounter when setting up a Rybbit proxy and how to resolve them.++## Script Loading Issues++### Script Fails to Load (404 Error)++**Symptoms:**+- Network tab shows 404 for `/analytics/script.js`+- Console errors about failed script loading+- No tracking data in dashboard++**Solutions:**++<Steps>++### Verify Proxy Configuration++Check your proxy rules are correctly configured:++- **Next.js**: Ensure rewrites are in `next.config.js` and server is restarted+- **Nginx**: Verify location blocks are active and Nginx is reloaded+- **Caddy**: Check Caddyfile syntax with `caddy validate`+- **Workers**: Verify route is configured in Cloudflare dashboard++### Check Path Mapping++Ensure paths are correctly mapped:++```+Your domain β Rybbit backend+----------------- ---------------+/analytics/script.js β /api/script.js+```++Common mistakes:+- Wrong source path (`/tracking` instead of `/analytics`)+- Incorrect destination (missing `/api` prefix)+- Typos in configuration++### Test Direct Backend Access++Verify Rybbit backend is accessible:++```bash+curl -I https://app.rybbit.io/api/script.js+```++Should return `HTTP/2 200` with `content-type: application/javascript`.++</Steps>++---++### Script Loads but Returns HTML++**Symptoms:**+- Script loads with 200 status+- Content-Type is `text/html` instead of `application/javascript`+- Console errors about unexpected token `<`++**Cause:** Proxy is serving your application's 404 page instead of proxying.++**Solutions:**++1. **Ensure proxy runs before app routing**:+ - Next.js: Rewrites run automatically before pages+ - Express: Define proxy routes BEFORE catch-all routes+ - Laravel: Place proxy routes at the top of `web.php`++2. **Check route specificity**:+```javascript+// β Wrong order - catch-all comes first+app.get('*', (req, res) => res.sendFile('index.html'));+app.use('/analytics', proxyMiddleware);++// β Correct order - proxy comes first+app.use('/analytics', proxyMiddleware);+app.get('*', (req, res) => res.sendFile('index.html'));+```++---++## Tracking Issues++### Script Loads but No Events Tracked++**Symptoms:**+- Script loads successfully+- No errors in console+- No tracking data appears in Rybbit dashboard+- POST requests to `/analytics/track` fail or return errors++**Solutions:**++<Steps>++### Verify All Endpoints Are Proxied++Ensure tracking endpoints are configured:++- `/analytics/track` (required)+- `/analytics/identify` (for user identification)+- `/analytics/session-replay/record/:siteId` (for session replay)+- `/analytics/site/tracking-config/:siteId` (for configuration)++**Check Network tab**: Look for failed POST requests to `/analytics/track`.++### Check CORS Headers++Tracking endpoints need proper CORS headers. Rybbit sets these automatically, but ensure your proxy preserves them:++```nginx+# Nginx - preserve CORS headers+proxy_pass_header Access-Control-Allow-Origin;+proxy_pass_header Access-Control-Allow-Methods;+```++```javascript+// Express - don't override CORS+// β Wrong - blocks CORS+app.use('/analytics', cors({ origin: 'https://yourdomain.com' }));++// β Correct - allow all origins (or use Rybbit's headers)+app.use('/analytics', cors({ origin: true }));+```++### Verify Content-Type for POST Requests++Tracking POSTs send JSON data. Ensure Content-Type is preserved:++```nginx+# Nginx+proxy_set_header Content-Type $content_type;+```++```javascript+// Express+onProxyReq: (proxyReq, req) => {+ if (req.headers['content-type']) {+ proxyReq.setHeader('Content-Type', req.headers['content-type']);+ }+}+```++### Check Request Method Preservation++Ensure POST requests remain POST:++```nginx+# Nginx - correct+proxy_method $request_method;++# Or let it default (preserves method)+proxy_pass https://app.rybbit.io;+```++</Steps>++---++### Events Tracked but Dashboard Shows Wrong Data++**Symptoms:**+- Events appear in dashboard+- But geolocation is wrong (all same location)+- Or user agents are incorrect++**Cause:** Client IP or headers not forwarded properly.++**Solutions:**++<Callout type="warn">+**Critical**: The `X-Forwarded-For` and `X-Real-IP` headers must contain the original client IP for accurate geolocation and user identification.+</Callout>++**Nginx:**+```nginx+proxy_set_header X-Real-IP $remote_addr;+proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;+proxy_set_header User-Agent $http_user_agent;+```++**Caddy:**+```txt+reverse_proxy https://app.rybbit.io {+ header_up X-Real-IP {remote_host}+ header_up X-Forwarded-For {remote_host}+}+```++**Express:**+```javascript+onProxyReq: (proxyReq, req) => {+ const clientIp = req.headers['x-forwarded-for'] || req.socket.remoteAddress;+ proxyReq.setHeader('X-Real-IP', clientIp);+ proxyReq.setHeader('X-Forwarded-For', clientIp);+ proxyReq.setHeader('User-Agent', req.headers['user-agent']);+}+```++**Cloudflare Workers:**+```javascript+const clientIp = request.headers.get('CF-Connecting-IP') || '0.0.0.0';+proxyHeaders.set('X-Real-IP', clientIp);+```++---++## Session Replay Issues++### Session Replay Not Working++**Symptoms:**+- Basic tracking works fine+- Session replays don't appear in dashboard+- Console shows errors loading `/analytics/replay.js`++**Solutions:**++1. **Add replay script endpoint**:+```javascript+// Next.js+{+ source: '/analytics/replay.js',+ destination: `${process.env.NEXT_PUBLIC_RYBBIT_HOST}/api/replay.js`,+}+```++2. **Add replay recording endpoint**:+```javascript+{+ source: '/analytics/session-replay/record/:siteId',+ destination: `${process.env.NEXT_PUBLIC_RYBBIT_HOST}/api/session-replay/record/:siteId`,+}+```++3. **Increase request size limits**:++Session replay can send large payloads (up to 10MB). Ensure your proxy allows this:++```nginx+# Nginx+location ~ ^/analytics/session-replay/record/ {+ client_max_body_size 10M;+ proxy_pass https://app.rybbit.io;+}+```++```javascript+// Express+app.use('/analytics/session-replay', express.json({ limit: '10mb' }));+```++```javascript+// Next.js - add to next.config.js+module.exports = {+ api: {+ bodyParser: {+ sizeLimit: '10mb',+ },+ },+};+```++---++## Configuration and Caching Issues++### Stale Configuration (Settings Changes Not Applied)++**Symptoms:**+- Changed settings in Rybbit dashboard+- But tracking script still uses old settings+- Takes a long time for changes to appear++**Cause:** Configuration endpoint is cached too aggressively.++**Solutions:**++1. **Check cache duration** for config endpoint:++```nginx+# Nginx - cache for 5 minutes max+location ~ ^/analytics/site/tracking-config/ {+ proxy_cache_valid 200 5m; # Not longer!+ proxy_pass https://app.rybbit.io;+}+```++2. **Clear cache manually**:++```bash+# Nginx+sudo nginx -s reload++# Or clear cache directory+sudo rm -rf /var/cache/nginx/rybbit/*+```++```javascript+// Node.js/Express with node-cache+cache.del(`rybbit_config_${siteId}`);++// Or flush all+cache.flushAll();+```++3. **Don't cache config endpoint at all** (if issues persist):++```nginx+# Nginx - no caching+location ~ ^/analytics/site/tracking-config/ {+ proxy_cache off;+ proxy_pass https://app.rybbit.io;+}+```++---++### Script Updates Not Appearing++**Symptoms:**+- Rybbit released an update+- Your site still loads old script version+- Missing new features or bug fixes++**Cause:** Script cached too long.++**Solutions:**++1. **Recommended cache duration**: 1 hour maximum++```nginx+# Nginx+proxy_cache_valid 200 1h; # Not longer!+```++2. **Clear script cache**:++```bash+# Nginx - purge cache+sudo rm -rf /var/cache/nginx/rybbit/+sudo nginx -s reload+```++```bash+# Vercel - clear via dashboard+# Deployments β Your deployment β Clear cache+```++```javascript+// Cloudflare Workers - purge via dashboard+// Caching β Configuration β Purge Everything+```++3. **Add cache busting** (advanced):++```javascript+// Next.js - revalidate on each deployment+{+ source: '/analytics/script.js',+ destination: `${rybbitHost}/api/script.js`,+ headers: [+ {+ key: 'Cache-Control',+ value: 'public, max-age=3600, must-revalidate',+ },+ ],+}+```++---++## Performance Issues++### High Bandwidth Usage++**Symptoms:**+- Bandwidth costs increasing significantly+- Server struggling with traffic+- Slow response times++**Solutions:**++<Steps>++### Implement Caching++Cache static scripts to reduce backend requests:++```nginx+# Nginx with caching+proxy_cache_path /var/cache/nginx/rybbit levels=1:2 keys_zone=rybbit:10m;++location = /analytics/script.js {+ proxy_cache rybbit;+ proxy_cache_valid 200 1h;+ proxy_cache_key "$scheme$request_method$host$request_uri";+ add_header X-Cache-Status $upstream_cache_status;+ proxy_pass https://app.rybbit.io/api/script.js;+}+```++### Use CDN++Put a CDN in front of your proxy:++- Cloudflare (recommended)+- AWS CloudFront+- Fastly++### Monitor and Limit++Add monitoring and rate limiting:++```javascript+// Express with rate limiting+const rateLimit = require('express-rate-limit');++app.use('/analytics/track', rateLimit({+ windowMs: 60 * 1000,+ max: 100, // 100 requests per minute per IP+}));+```++</Steps>++---++### Slow Response Times++**Symptoms:**+- Tracking requests take multiple seconds+- Script loading is slow+- Poor user experience++**Solutions:**++1. **Enable compression**:++```nginx+# Nginx+gzip on;+gzip_types application/javascript;+```++2. **Use connection keepalive**:++```nginx+# Nginx+proxy_http_version 1.1;+proxy_set_header Connection "";++upstream rybbit {+ server app.rybbit.io:443;+ keepalive 32;+}+```++3. **Check backend connectivity**:++```bash+# Test latency to Rybbit+curl -w "@curl-format.txt" -o /dev/null -s https://app.rybbit.io/api/script.js++# Create curl-format.txt:+# time_namelookup: %{time_namelookup}s+# time_connect: %{time_connect}s+# time_starttransfer: %{time_starttransfer}s+# time_total: %{time_total}s+```++If backend is slow, consider:+- Self-hosting Rybbit closer to your users+- Using a CDN proxy+- Caching more aggressively++---++## Platform-Specific Issues++### Next.js: Rewrites Not Working++**Problem:** Added rewrites to `next.config.js` but they don't work.++**Solutions:**++1. **Restart dev server**:+```bash+# Stop server (Ctrl+C)+npm run dev+```++2. **Check async rewrites** function:+```javascript+// β Wrong - not async+rewrites() {+ return [...];+}++// β Correct - async+async rewrites() {+ return [...];+}+```++3. **Verify environment variable** is loaded:+```javascript+async rewrites() {+ console.log('RYBBIT_HOST:', process.env.NEXT_PUBLIC_RYBBIT_HOST);+ // Should log the URL+ return [...];+}+```++---++### Nginx: 502 Bad Gateway++**Problem:** Nginx returns 502 error for analytics endpoints.++**Solutions:**++1. **Enable SNI** for SSL:+```nginx+proxy_ssl_server_name on;+```++2. **Check DNS resolution**:+```bash+nslookup app.rybbit.io+```++3. **Check logs**:+```bash+sudo tail -f /var/log/nginx/error.log+```++4. **Test backend directly**:+```bash+curl -v https://app.rybbit.io/api/script.js+```++---++### Vercel: 404 After Deployment++**Problem:** Works locally but 404 in production.++**Solutions:**++1. **Ensure `vercel.json` is committed**:+```bash+git add vercel.json+git commit -m "Add Rybbit proxy config"+git push+```++2. **Check build logs** in Vercel dashboard for errors++3. **Verify environment variables** are set in Vercel project settings++---++## Debugging Checklist++When troubleshooting, work through this checklist:++- [ ] Script loads successfully (200 status, correct Content-Type)+- [ ] Tracking endpoint is proxied (`/analytics/track`)+- [ ] POST requests preserve method and body+- [ ] Client IP is forwarded (`X-Forwarded-For`, `X-Real-IP`)+- [ ] User-Agent header is preserved+- [ ] CORS headers are preserved (check response headers)+- [ ] Request size limits allow tracking data (1MB minimum)+- [ ] Session replay endpoints are proxied (if using replay)+- [ ] Cache duration is appropriate (1 hour for scripts, 5 min for config)+- [ ] No CSRF protection blocking POST requests+- [ ] Environment variables are set correctly+- [ ] Configuration changes have been deployed++## Getting Help++If you've tried everything and still have issues:++1. **Check browser console** for JavaScript errors+2. **Check Network tab** for failed requests (note status codes)+3. **Check server logs** for proxy errors+4. **Test with curl** to isolate browser vs server issues+5. **Verify directly** against `https://app.rybbit.io/api/script.js`++**Gather this information before asking for help:**+- Framework/platform you're using+- Proxy configuration code+- Network tab screenshot showing the issue+- Any error messages from logs or console+- Whether it worked before (what changed?)++## Related Resources++- [Generic Proxy Guide](/docs/proxy-guide/get-started) - Core concepts+- [Tracking Script Documentation](/docs/script) - Script configuration+- Framework-specific guides for detailed setupdiff --git a/docs/content/docs/proxy-guide/vercel.mdx b/docs/content/docs/proxy-guide/vercel.mdxnew file mode 100644index 000000000..2a4dca691--- /dev/null+++ b/docs/content/docs/proxy-guide/vercel.mdx@@ -0,0 +1,283 @@+---+title: Vercel Proxy Setup+description: Deploy Rybbit proxy on Vercel with Edge Network caching+---++import { Steps } from 'fumadocs-ui/components/steps';+import { Callout } from 'fumadocs-ui/components/callout';++Vercel makes it easy to proxy Rybbit tracking through their Edge Network. If you're using Next.js, follow the [Next.js proxy guide](/docs/proxy-guide/next-js) instead, which is optimized for Next.js applications.++This guide is for static sites or other frameworks deployed on Vercel.++## Overview++Vercel supports rewrites in `vercel.json`, allowing you to proxy requests through their global Edge Network. This provides excellent performance with automatic caching at edge locations worldwide.++**What you'll achieve:**+- Proxy Rybbit through Vercel's Edge Network+- Automatic global caching and CDN distribution+- Simple JSON configuration+- Support all Rybbit features++## Prerequisites++- Site deployed on Vercel+- Your Rybbit instance URL:+ - **Cloud hosted**: `https://app.rybbit.io`+ - **Self-hosted**: Your instance URL+- Your Rybbit site ID++## Implementation++<Steps>++### Create or Update vercel.json++Add rewrites to your `vercel.json` file in the project root:++```json+{+ "rewrites": [+ {+ "source": "/analytics/script.js",+ "destination": "https://app.rybbit.io/api/script.js"+ },+ {+ "source": "/analytics/script-full.js",+ "destination": "https://app.rybbit.io/api/script-full.js"+ },+ {+ "source": "/analytics/replay.js",+ "destination": "https://app.rybbit.io/api/replay.js"+ },+ {+ "source": "/analytics/metrics.js",+ "destination": "https://app.rybbit.io/api/metrics.js"+ },+ {+ "source": "/analytics/track",+ "destination": "https://app.rybbit.io/api/track"+ },+ {+ "source": "/analytics/identify",+ "destination": "https://app.rybbit.io/api/identify"+ },+ {+ "source": "/analytics/session-replay/record/:siteId",+ "destination": "https://app.rybbit.io/api/session-replay/record/:siteId"+ },+ {+ "source": "/analytics/site/tracking-config/:siteId",+ "destination": "https://app.rybbit.io/site/tracking-config/:siteId"+ }+ ]+}+```++<Callout type="info">+Replace `app.rybbit.io` with your self-hosted Rybbit instance URL if you're not using the cloud version.+</Callout>++### Update Your Tracking Script++Update your HTML to use the proxied path:++```html+<script src="/analytics/script.js" async data-site-id="YOUR_SITE_ID"></script>+```++### Deploy to Vercel++Commit your changes and deploy:++```bash+git add vercel.json+git commit -m "Add Rybbit proxy configuration"+git push+```++Vercel will automatically detect the changes and deploy with the new rewrites.++### Verify the Setup++1. **Visit your deployed site** with Developer Tools open+2. **Check Network tab**:+ - Script should load from `/analytics/script.js`+ - Tracking requests should go to `/analytics/track`+ - All requests should show your Vercel domain+3. **Verify in Rybbit dashboard**: Data should appear after 1-2 minutes++</Steps>++## How It Works++Vercel's Edge Network handles rewrites at the edge, close to your users:++1. Request hits Vercel's edge location nearest to the user+2. Edge server rewrites and proxies to Rybbit+3. Response is cached at the edge (for cacheable requests)+4. Subsequent requests serve from edge cache++This provides excellent performance with minimal configuration.++## Performance Benefits++### Edge Network Caching++Vercel automatically caches responses at edge locations:++- **Scripts**: Cached globally, served from nearest edge+- **Configuration**: Cached with appropriate TTL+- **Tracking requests**: Not cached (unique per request)++### Global Distribution++Your analytics proxy benefits from Vercel's global CDN:++- 70+ edge locations worldwide+- Sub-100ms latency for most users+- Automatic failover and redundancy++## Bandwidth Considerations++<Callout type="warn">+Vercel rewrites count toward your bandwidth quota. For a site with 100,000 monthly sessions:+- Without session replay: ~5-10 GB/month+- With session replay: ~30-80 GB/month++Check your Vercel plan limits. Pro plan includes 1 TB bandwidth/month.+</Callout>++## Troubleshooting++### Rewrites not working++**Problem**: Requests still go to `app.rybbit.io` directly.++**Solution**:+1. Ensure `vercel.json` is in your project root+2. Redeploy after adding `vercel.json`+3. Clear browser cache and test in incognito mode++### 404 on tracking endpoints++**Problem**: Script loads but tracking returns 404.++**Solution**:+Verify all endpoints are in `vercel.json` rewrites, including:+- `/analytics/track`+- `/analytics/identify`+- `/analytics/session-replay/record/:siteId`++### Session replay not working++**Problem**: Basic tracking works but replay doesn't record.++**Solution**:+Add replay endpoints to rewrites:+```json+{+ "source": "/analytics/replay.js",+ "destination": "https://app.rybbit.io/api/replay.js"+},+{+ "source": "/analytics/session-replay/record/:siteId",+ "destination": "https://app.rybbit.io/api/session-replay/record/:siteId"+}+```++## Environment-Specific Configuration++### Using Environment Variables++While Vercel's `vercel.json` doesn't support environment variables directly, you can use different config files:++```json+// vercel.json (production)+{+ "rewrites": [+ {+ "source": "/analytics/script.js",+ "destination": "https://app.rybbit.io/api/script.js"+ }+ ]+}+```++```json+// vercel.staging.json (staging)+{+ "rewrites": [+ {+ "source": "/analytics/script.js",+ "destination": "https://staging.rybbit.io/api/script.js"+ }+ ]+}+```++Then specify config in build settings or use Vercel CLI:+```bash+vercel --prod --local-config vercel.json+```++## Advanced Configuration++### Headers++Add custom headers to responses:++```json+{+ "rewrites": [+ {+ "source": "/analytics/script.js",+ "destination": "https://app.rybbit.io/api/script.js"+ }+ ],+ "headers": [+ {+ "source": "/analytics/(.*)",+ "headers": [+ {+ "key": "Cache-Control",+ "value": "public, max-age=3600"+ }+ ]+ }+ ]+}+```++### Redirects vs Rewrites++Don't use redirects for proxying (they're visible to the user):++```json+// β Wrong - uses redirects (user sees app.rybbit.io)+{+ "redirects": [+ {+ "source": "/analytics/script.js",+ "destination": "https://app.rybbit.io/api/script.js"+ }+ ]+}++// β Correct - uses rewrites (transparent proxy)+{+ "rewrites": [+ {+ "source": "/analytics/script.js",+ "destination": "https://app.rybbit.io/api/script.js"+ }+ ]+}+```++## Related Resources++- [Next.js Proxy Guide](/docs/proxy-guide/next-js) - If using Next.js+- [Tracking Script Documentation](/docs/script) - Script configuration+- [Vercel Rewrites Documentation](https://vercel.com/docs/projects/project-configuration#rewrites) - Official Vercel docsdiff --git a/docs/content/docs/script.mdx b/docs/content/docs/script.mdxindex d5f729c62..a51501068 100644--- a/docs/content/docs/script.mdx+++ b/docs/content/docs/script.mdx@@ -3,6 +3,7 @@ title: Tracking scriptdescription: How to install and configure the Rybbit tracking script---+import { Callout } from 'fumadocs-ui/components/callout';To start tracking user activity on your website, add the Rybbit tracking script to your site's HTML.@@ -14,6 +15,10 @@ The webpage should give you this script tag like this when you first add a websi```If you are self-hosting Rybbit `app.rybbit.io` will be domain of your Rybbit instance.+<Callout type="info">+ **Bypass Ad Blockers**: Some ad blockers may block analytics scripts regardless of privacy compliance. To improve tracking accuracy, you can proxy the tracking script through your own domain. See our [Proxy Guide](/docs/proxy-guide) for setup instructions for Next.js, Nginx, Caddy, and more.+</Callout>+## Configuration### Site Settings Configuration