### Run Next.js Development Server (Bash) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/apps/demo/README.md Commands to start the Next.js development server using different package managers. Ensure you have Node.js installed. These commands will launch a local server for development. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Install Better Analytics SDK Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Installs the Better Analytics SDK using different package managers. This is the first step to integrate the SDK into your project. ```bash npm install @better-analytics/sdk # or yarn add @better-analytics/sdk # or bun add @better-analytics/sdk ``` -------------------------------- ### Install and Set Up Better Analytics SDK (Bash) Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This snippet provides commands for installing the Better Analytics SDK using different package managers (npm, yarn, bun). It also outlines the typical project structure and includes commands for running the application locally, pushing database schema changes, and opening the Drizzle Studio. Finally, it shows commands for building the project for production and running it with Docker. ```bash # Install the SDK npm install @better-analytics/sdk # Or using other package managers yarn add @better-analytics/sdk bun add @better-analytics/sdk # Project structure better-analytics/ ├── apps/ │ ├── api/ # Elysia REST API │ ├── web/ # Next.js dashboard │ └── demo/ # Demo application ├── packages/ │ ├── sdk/ # TypeScript SDK (client + server) │ ├── db/ # Database schemas (Drizzle ORM) │ ├── auth/ # Authentication utilities │ ├── ui/ # Shared UI components │ └── env/ # Environment configuration └── tooling/ # Build and dev tools # Run locally bun install bun dev # Start all apps in dev mode bun db:push # Push database schema bun db:studio # Open Drizzle Studio # Build for production bun build docker-compose up # Run with Docker ``` -------------------------------- ### Basic Better Analytics SDK Setup (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Initializes the Better Analytics SDK with essential configuration. It automatically detects the environment and debug mode, and enables auto-capture for unhandled errors. ```typescript // lib/analytics.ts import { init } from "@better-analytics/sdk"; export const analytics = init({ apiUrl: "https://api.analytics.customhack.dev", clientId: "your-client-id-here", accessToken: "your-access-token-here", // Optional but recommended }); ``` -------------------------------- ### Install @better-analytics/sdk Source: https://github.com/databuddy-analytics/better-analytics/blob/main/README.md Install the Better Analytics SDK using npm. This package is required to integrate error tracking and logging into your web application. ```bash npm install @better-analytics/sdk ``` -------------------------------- ### Better Analytics SDK Setup with Environment Variables (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Configures the Better Analytics SDK using environment variables for sensitive information like API URLs and client IDs. This is a recommended practice for managing credentials. ```typescript // lib/analytics.ts import { init } from "@better-analytics/sdk"; export const analytics = init({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", }); ``` -------------------------------- ### Better Analytics API: Localization (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Shows how to use the Better Analytics SDK for localization. It includes examples for translating a single string to a specified language and translating an entire object, providing a way to internationalize application content. ```typescript // Translate a single string // const translated = await analytics.localize("Hello world", "es"); // Returns: "Hola mundo" // Translate an entire object // const content = { // greeting: "Hello", // farewell: "Goodbye", // message: "Welcome to our platform", // }; // const translated = await analytics.localizeObject(content, "es"); // Returns: { greeting: "Hola", farewell: "Adiós", message: "Bienvenido a nuestra plataforma" } ``` -------------------------------- ### Advanced Error Tracking with Better Analytics SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt TypeScript example demonstrating advanced error tracking features using the Better Analytics SDK. Includes initializing the tracker, setting user context, adding global tags, tracking errors with context, capturing exceptions, and tracking 404 pages. ```typescript import { createErrorTracker } from "@better-analytics/sdk"; const analytics = createErrorTracker({ apiUrl: "https://api.analytics.customhack.dev", clientId: "client_abc123", accessToken: "token_xyz", autoCapture: true, environment: "production", userId: "user_123" }); // Set user context dynamically analytics.setUser("user_456"); // Add global tags that apply to all subsequent errors analytics.addTags(["premium-user", "mobile-app"]); // Track errors with rich context analytics.track("Checkout failed", { orderId: "order_789", cartValue: 149.99, paymentMethod: "credit_card", errorCode: "CARD_DECLINED" }); // Capture exceptions with detailed context try { await fetchUserProfile(userId); } catch (error) { analytics.captureException(error as Error, { context: "profile-fetch", userId: userId, retryCount: 3, endpoint: "/api/user/profile" }); } // Track 404 pages analytics.track404( window.location.href, document.referrer ); ``` -------------------------------- ### API Route Example with Server-Side Logging (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/README.md Example of an API route in Next.js that utilizes the Better Analytics logger to record information about user creation success or failure. ```typescript // app/api/users/route.ts import { logger } from "@/lib/logger"; export async function POST(request: Request) { try { const user = await createUser(data); logger.info("User created", { userId: user.id }); return Response.json(user); } catch (error) { logger.error("User creation failed", { error, data }); return Response.json({ error: "Failed" }, { status: 500 }); } } ``` -------------------------------- ### Initialize Client-Side Error Tracker (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/README.md Initialize the client-side error tracker for React/Next.js applications. This setup requires API credentials and can be configured to auto-capture unhandled errors. ```typescript // lib/analytics.ts import { createErrorTracker } from "@better-analytics/sdk"; export const analytics = createErrorTracker({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", autoCapture: true, // Auto-capture unhandled errors }); ``` -------------------------------- ### Better Analytics API: Error Tracking (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Provides examples for using the Better Analytics SDK to track custom events, capture exceptions, set user context, and add global tags. This is essential for monitoring application errors and user activity. ```typescript // Track a custom error // await analytics.track("User authentication failed", { // userId: "user123", // action: "login", // customData: { loginMethod: "email" } // }); // Capture an exception // try { // // Your code here // } catch (error) { // await analytics.captureException(error, { // context: "payment-processing", // userId: "user123" // }); // } // Set user context // analytics.setUser("user123"); // Add global tags // analytics.addTags(["production", "checkout-flow"]); ``` -------------------------------- ### Configure Environment Variables for Better Analytics SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This section lists essential environment variables for configuring the Better Analytics SDK and related services. It categorizes variables for client-side (Next.js), server-side, third-party integrations (like Lingo, IPInfo), database connections (ClickHouse), and authentication providers (Supabase). ```bash # Client-side (Next.js) NEXT_PUBLIC_API_URL=https://api.analytics.customhack.dev NEXT_PUBLIC_CLIENT_ID=client_abc123 NEXT_PUBLIC_ACCESS_TOKEN=token_xyz789 # Server-side API_URL=https://api.analytics.customhack.dev CLIENT_ID=client_abc123 ACCESS_TOKEN=token_xyz789 PORT=4000 # Third-party services LINGODOTDEV_API_KEY=lingo_key_123 IPINFO_TOKEN=ipinfo_token_456 # Database (ClickHouse) CLICKHOUSE_HOST=https://clickhouse.example.com CLICKHOUSE_USER=default CLICKHOUSE_PASSWORD=secure_password CLICKHOUSE_DATABASE=analytics # Authentication (Supabase) SUPABASE_URL=https://project.supabase.co SUPABASE_ANON_KEY=supabase_anon_key SUPABASE_SERVICE_ROLE_KEY=supabase_service_key ``` -------------------------------- ### Server Logger Configuration Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Configure server-side logging with environment-specific settings and minimum log levels. Demonstrates manual configuration and simple initialization with auto-detection. ```APIDOC ## Server Logger Configuration Configure server-side logging with environment-specific settings and minimum log levels. ### Description This section details how to set up and use the server-side logger provided by the Better Analytics SDK. It covers manual configuration with various options and a simplified initialization process that attempts to auto-detect necessary settings. ### Methods - `createLogger(options)`: Manually configures and creates a logger instance. - `initLogger(options)`: Initializes the logger with auto-detected settings. - `setRequestId(id)`: Sets the request ID for contextual logging. - `setUser(id)`: Sets the user ID for contextual logging. - `addTags(tags)`: Adds tags for categorizing log entries. - `info(message, context)`: Logs an informational message. - `warn(message, context)`: Logs a warning message. - `error(error, context)`: Logs an error message. ### Parameters for `createLogger` and `initLogger` #### Request Body (Options Object) - **apiUrl** (string) - Required - The endpoint URL for sending analytics data. - **clientId** (string) - Required - The client identifier for your application. - **accessToken** (string) - Optional but recommended - An access token for authentication. - **environment** (string) - Optional - Specifies the deployment environment (e.g., 'production', 'staging'). - **serviceName** (string) - Optional - The name of the service sending logs. - **serviceVersion** (string) - Optional - The version of the service sending logs. - **minLevel** (string) - Optional - The minimum log level to record (e.g., 'info', 'warn', 'error'). Defaults to 'info'. - **debug** (boolean) - Optional - Enables debug mode for more verbose logging. ### Request Example (Manual Configuration) ```typescript import { createLogger } from "@better-analytics/sdk"; const logger = createLogger({ apiUrl: "https://api.analytics.customhack.dev", clientId: "client_abc123", accessToken: "token_xyz", environment: "production", serviceName: "payment-service", serviceVersion: "2.1.0", minLevel: "warn", debug: false }); logger.setRequestId("req_abc123"); logger.setUser("user_456"); logger.addTags(["payment", "stripe", "webhook"]); logger.info("Payment processed", { amount: 99.99, currency: "USD", customerId: "cus_123", processingTime: 245 }); logger.error("Payment webhook failed", { webhookId: "whk_789", statusCode: 500, retries: 3, error: "Connection timeout" }); try { await processWebhook(payload); } catch (error) { logger.error(error as Error, { webhookType: "payment.succeeded", payload: payload }); } ``` ### Response Logs are sent asynchronously to the configured `apiUrl`. There is no direct response object for log operations, but errors during sending might be visible in debug mode or returned via error handling mechanisms of the SDK. ``` -------------------------------- ### Capture Exceptions with Context (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Demonstrates how to capture an exception with additional context, such as the component, user ID, current step, and metadata. This aids in debugging and understanding error origins. ```typescript analytics.captureException(error, { component: "CheckoutForm", userId: user.id, step: "payment-processing", metadata: { orderId: "12345" } }); ``` -------------------------------- ### Configure Server-Side Logging with Better Analytics SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This snippet demonstrates how to configure the server-side logger using the Better Analytics SDK. It shows manual configuration with specific API details and environment settings, as well as simple initialization with environment variable auto-detection. It also illustrates how to set request context, add tags, and log messages with rich context, including Error objects. ```typescript import { createLogger, initLogger } from "@better-analytics/sdk"; // Manual configuration const logger = createLogger({ apiUrl: "https://api.analytics.customhack.dev", clientId: "client_abc123", accessToken: "token_xyz", environment: "production", serviceName: "payment-service", serviceVersion: "2.1.0", minLevel: "warn", // Only log warn and error debug: false }); // Simple initialization with auto-detection const autoLogger = initLogger({ apiUrl: process.env.API_URL || "", clientId: process.env.CLIENT_ID || "", accessToken: process.env.ACCESS_TOKEN || "", serviceName: "api-gateway" }); // Set request context logger.setRequestId("req_abc123"); logger.setUser("user_456"); // Add tags for categorization logger.addTags(["payment", "stripe", "webhook"]); // Log with rich context logger.info("Payment processed", { amount: 99.99, currency: "USD", customerId: "cus_123", processingTime: 245 }); logger.error("Payment webhook failed", { webhookId: "whk_789", statusCode: 500, retries: 3, error: "Connection timeout" }); // Log Error objects directly try { await processWebhook(payload); } catch (error) { logger.error(error as Error, { webhookType: "payment.succeeded", payload: payload }); } ``` -------------------------------- ### Manage Feature Quotas with Autumn Integration (TypeScript) Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This snippet demonstrates how to check feature quotas using Autumn integration in TypeScript. It shows example responses for quota exceeded errors and provides an async function `trackError` that implements retry logic for when the API returns a 429 status code, indicating that a quota has been exceeded. The function handles network errors and returns success or failure status along with a reason. ```typescript // Quota features tracked: // - "error": Error ingestion // - "log": Log ingestion // - "404_page_tracking": 404 page tracking // Example quota check response { "status": "error", "message": "Quota exceeded for error ingestion." } // HTTP Status: 429 Too Many Requests // Implement retry logic in SDK async function trackError(errorData) { try { const response = await fetch("/ingest", { method: "POST", body: JSON.stringify(errorData) }); if (response.status === 429) { console.warn("Quota exceeded, will retry later"); // Queue for later or drop based on priority return { success: false, reason: "quota_exceeded" }; } return await response.json(); } catch (error) { console.error("Failed to track error:", error); return { success: false, reason: "network_error" }; } } ``` -------------------------------- ### Advanced Better Analytics SDK Configuration (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Sets up the Better Analytics SDK with advanced options, allowing explicit control over environment, debug mode, and automatic error capture. This is useful for specific use cases or testing. ```typescript // lib/analytics.ts import { createErrorTracker } from "@better-analytics/sdk"; export const analytics = createErrorTracker({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", environment: "production", // Force specific environment debug: false, // Force disable debug mode autoCapture: false, // Disable automatic error capture }); ``` -------------------------------- ### Configuration Options Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Defines the configuration interface for the Error Tracker. ```APIDOC ## Configuration Options ### ErrorTrackerConfig Interface #### Description Defines the structure for configuring the Better Analytics Error Tracker. #### Fields - **apiUrl** (string) - Required - Better Analytics API URL. - **clientId** (string) - Required - Your project's client ID. - **accessToken** (string) - Optional - Your access token (recommended). - **environment** (string) - Optional - Environment (e.g., `development`, `production`). - **debug** (boolean) - Optional - Enable debug logging. - **autoCapture** (boolean) - Optional - Auto-capture unhandled errors. - **userId** (string) - Optional - Set initial user ID. ``` -------------------------------- ### Advanced Better Analytics Logger Configuration (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Demonstrates advanced configuration for the Better Analytics logger using `createLogger`. This allows explicit control over API URL, client ID, access token, environment, service name, service version, debug mode, and minimum log level. ```typescript import { createLogger } from "@better-analytics/sdk"; export const logger = createLogger({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", environment: "production", serviceName: "my-service", serviceVersion: "2.1.0", debug: false, minLevel: "warn", // Only log warnings and errors }); ``` -------------------------------- ### Configure Environment-Specific Analytics (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Initializes the error tracker with environment-specific settings like API URL, client ID, access token, and debug mode. It utilizes environment variables for configuration. ```typescript const analytics = createErrorTracker({ apiUrl: process.env.NEXT_PUBLIC_API_URL, clientId: process.env.NEXT_PUBLIC_CLIENT_ID, accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN, environment: process.env.NODE_ENV, debug: process.env.NODE_ENV === "development", autoCapture: true, }); ``` -------------------------------- ### Environment Variables Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Environment variables for configuring the SDK and connecting to third-party services like databases and authentication providers. ```APIDOC ## Environment Variables Configure the SDK and API with environment-specific settings. ### Description This section lists the essential environment variables required for setting up the Better Analytics SDK and integrating with various services. These variables cover API endpoints, client identification, authentication tokens, and database/service connection details. ### Variables #### Client-side (Next.js) - **NEXT_PUBLIC_API_URL** (string) - The public API URL for the analytics service. - **NEXT_PUBLIC_CLIENT_ID** (string) - The public client ID. - **NEXT_PUBLIC_ACCESS_TOKEN** (string) - The public access token. #### Server-side - **API_URL** (string) - The API URL for the analytics service. - **CLIENT_ID** (string) - The client identifier. - **ACCESS_TOKEN** (string) - The access token for server-side requests. - **PORT** (number) - The port the server should listen on. #### Third-party Services - **LINGODOTDEV_API_KEY** (string) - API key for the LingodotDev service. - **IPINFO_TOKEN** (string) - Token for the IPInfo service. #### Database (ClickHouse) - **CLICKHOUSE_HOST** (string) - Hostname or URL for the ClickHouse database. - **CLICKHOUSE_USER** (string) - Username for ClickHouse authentication. - **CLICKHOUSE_PASSWORD** (string) - Password for ClickHouse authentication. - **CLICKHOUSE_DATABASE** (string) - The name of the ClickHouse database. #### Authentication (Supabase) - **SUPABASE_URL** (string) - URL for the Supabase project. - **SUPABASE_ANON_KEY** (string) - Anonymous key for Supabase client access. - **SUPABASE_SERVICE_ROLE_KEY** (string) - Service role key for administrative Supabase access. ### Usage Example (Bash) ```bash export NEXT_PUBLIC_API_URL="https://api.analytics.customhack.dev" export CLIENT_ID="client_abc123" export ACCESS_TOKEN="token_xyz789" export PORT=4000 ``` ``` -------------------------------- ### Server-Side Logging Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Utilize the `initLogger` function for structured logging on your server-side applications. It automatically configures log levels and debug modes based on the environment. ```APIDOC ## Server-Side Logging ### Description Initializes a logger instance for structured logging in server-side applications. Automatically detects environment, debug mode, and log level. ### Method `initLogger(config: LoggerConfig): Logger` ### Parameters #### Request Body (LoggerConfig) - **apiUrl** (string) - Required - The Better Analytics API URL. - **clientId** (string) - Required - Your project's client ID. - **accessToken** (string) - Optional - Your access token. - **serviceName** (string) - Required - The name of your service. ### Usage ```typescript // lib/logger.ts import { initLogger } from "@better-analytics/sdk"; export const logger = initLogger({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", serviceName: "my-app-backend", }); // Usage examples: await logger.info("User logged in", { userId: "123" }); await logger.error("Payment failed", { orderId: "456", amount: 100 }); ``` ### Advanced Configuration Allows for more granular control over logger settings. ### Method `createLogger(config: AdvancedLoggerConfig): Logger` ### Parameters #### Request Body (AdvancedLoggerConfig) - **apiUrl** (string) - Required - The Better Analytics API URL. - **clientId** (string) - Required - Your project's client ID. - **accessToken** (string) - Optional - Your access token. - **environment** (string) - Optional - Explicitly set the environment (e.g., `"production"`). - **serviceName** (string) - Required - The name of your service. - **serviceVersion** (string) - Optional - The version of your service. - **debug** (boolean) - Optional - Enable or disable debug logging. - **minLevel** (string) - Optional - Minimum log level to record (e.g., `"warn"`, `"info"`). ### Example ```typescript import { createLogger } from "@better-analytics/sdk"; export const logger = createLogger({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", environment: "production", serviceName: "my-service", serviceVersion: "2.1.0", debug: false, minLevel: "warn", // Only log warnings and errors }); ``` ``` -------------------------------- ### Identify Users and Add Tags (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Shows how to set the current user's ID and add relevant tags (like plan and region) to the analytics context. This helps in segmenting errors by user attributes. ```typescript // When user logs in analytics.setUser(user.id); // Add relevant tags analytics.addTags([user.plan, user.region]); ``` -------------------------------- ### Initialize Better Analytics Logger (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Initializes the Better Analytics logger for server-side applications. It automatically configures environment detection, debug mode, log level, and service version based on environment variables. The logger supports various methods like 'info' and 'error'. ```typescript // lib/logger.ts import { initLogger } from "@better-analytics/sdk"; export const logger = initLogger({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", serviceName: "my-app-backend", }); // Usage // await logger.info("User logged in", { userId: "123" }); // await logger.error("Payment failed", { orderId: "456", amount: 100 }); ``` -------------------------------- ### Subscribe to Real-Time Events with Supabase Channels Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This TypeScript snippet demonstrates how to subscribe to real-time error and log events using Supabase channels for live dashboard updates. It shows how to create a Supabase client, subscribe to user-specific and client-specific broadcast events, and handle incoming payloads for errors and logs. It also includes cleanup logic for unsubscribing from channels. ```typescript import { createClient } from "@supabase/supabase-js"; const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL || "", process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "" ); // Subscribe to user-specific events const channel = supabase.channel(`user:${userId}`); channel .on("broadcast", { event: "error_ingested" }, (payload) => { console.log("New error:", payload); // payload includes: id, message, severity, error_type, source, etc. updateDashboard(payload); }) .on("broadcast", { event: "log_ingested" }, (payload) => { console.log("New log:", payload); // payload includes: id, message, level, source, context, etc. updateLogViewer(payload); }) .subscribe(); // Subscribe to client-specific events const clientChannel = supabase.channel(`user:${clientId}`); clientChannel .on("broadcast", { event: "new-log" }, (payload) => { console.log("New log for client:", payload); }) .on("broadcast", { event: "new-404" }, (payload) => { console.log("New 404 tracked:", payload); }) .subscribe(); // Clean up on unmount return () => { channel.unsubscribe(); clientChannel.unsubscribe(); }; ``` -------------------------------- ### Real-Time Event Streaming Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Instructions on subscribing to real-time error and log events using Supabase channels for live dashboard updates. ```APIDOC ## Real-Time Event Streaming Subscribe to real-time error and log events using Supabase channels for live dashboard updates. ### Description This section details how to leverage Supabase's real-time capabilities to stream error and log events directly from the Better Analytics backend. This enables live updates on dashboards and monitoring tools. ### Subscription Methods 1. **User-Specific Events**: Subscribe to events related to a specific user ID. 2. **Client-Specific Events**: Subscribe to events related to a specific client ID. ### Supabase Setup - Ensure your Supabase project is configured and you have the necessary URL and Anon Key. - Environment variables `NEXT_PUBLIC_SUPABASE_URL` and `NEXT_PUBLIC_SUPABASE_ANON_KEY` should be set. ### Code Example (TypeScript) ```typescript import { createClient } from "@supabase/supabase-js"; // Assuming userId and clientId are available in your scope const userId = "user_abc"; const clientId = "client_xyz"; const supabase = createClient( process.env.NEXT_PUBLIC_SUPABASE_URL || "", process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY || "" ); // Subscribe to user-specific events const userChannel = supabase.channel(`user:${userId}`); userChannel .on("broadcast", { event: "error_ingested" }, (payload) => { console.log("New user error:", payload); // payload includes: id, message, severity, error_type, source, etc. updateDashboard(payload); // Example function to update UI }) .on("broadcast", { event: "log_ingested" }, (payload) => { console.log("New user log:", payload); // payload includes: id, message, level, source, context, etc. updateLogViewer(payload); // Example function to update UI }) .subscribe(); // Subscribe to client-specific events const clientChannel = supabase.channel(`client:${clientId}`); clientChannel .on("broadcast", { event: "new-log" }, (payload) => { console.log("New client log:", payload); }) .on("broadcast", { event: "new-404" }, (payload) => { console.log("New 404 tracked:", payload); }) .subscribe(); // Clean up subscriptions on component unmount or when no longer needed // This is crucial to prevent memory leaks const cleanupSubscriptions = () => { userChannel.unsubscribe(); clientChannel.unsubscribe(); }; // Example of calling cleanup // cleanupSubscriptions(); ``` ### Event Payloads - **`error_ingested`**: Contains details about an ingested error, including `id`, `message`, `severity`, `error_type`, `source`, etc. - **`log_ingested`**: Contains details about an ingested log, including `id`, `message`, `level`, `source`, `context`, etc. - **`new-log`**: General log events for a client. - **`new-404`**: Specific events for tracking 404 errors. ``` -------------------------------- ### Ingest Application Logs using cURL Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to ingest application logs with contextual information and custom metadata. Requires client ID, log level, message, source, environment, and optional user ID, session ID, tags, and context. Available log levels include debug, info, warn, and error. ```bash curl -X POST https://api.analytics.customhack.dev/log \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-access-token" \ -d '{ "client_id": "client_abc123", "level": "error", "message": "Database connection timeout after 30s", "source": "api-server", "environment": "production", "user_id": "user_123", "session_id": "session_xyz789", "tags": ["database", "timeout"], "context": "{\"host\":\"db.example.com\",\"port\":5432,\"timeout\":30000}" }' ``` -------------------------------- ### Localization API Source: https://github.com/databuddy-analytics/better-analytics/blob/main/packages/sdk/README.md Methods for translating individual strings or entire objects to specified languages. ```APIDOC ## Localization ### Translate String #### Description Translates a single string to a target language. #### Method `analytics.localize(text: string, language: string): Promise` #### Example ```typescript // Translate a single string const translated = await analytics.localize("Hello world", "es"); // Returns: "Hola mundo" ``` ### Translate Object #### Description Translates all string values within an object to a target language. #### Method `analytics.localizeObject(obj: object, language: string): Promise` #### Example ```typescript const content = { greeting: "Hello", farewell: "Goodbye", message: "Welcome to our platform", }; const translated = await analytics.localizeObject(content, "es"); // Returns: { greeting: "Hola", farewell: "Adiós", message: "Bienvenido a nuestra plataforma" } ``` ``` -------------------------------- ### Server-Side Logging with TypeScript SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Set up a logger instance for backend services using the @better-analytics/sdk. This allows tracking application logs with multiple severity levels (debug, info, warn, error). It supports request ID association, error context logging, and adding tags or user context. ```typescript import { createLogger } from "@better-analytics/sdk"; export const logger = createLogger({ apiUrl: process.env.API_URL || "https://api.analytics.customhack.dev", clientId: process.env.CLIENT_ID || "", accessToken: process.env.ACCESS_TOKEN || "", environment: "production", serviceName: "api-server", serviceVersion: "1.2.3", minLevel: "info", debug: false }); // Use in API routes export async function POST(request: Request) { logger.setRequestId(crypto.randomUUID()); try { const user = await createUser(data); logger.info("User created successfully", { userId: user.id, email: user.email, timestamp: Date.now() }); return Response.json(user); } catch (error) { logger.error("User creation failed", { error: (error as Error).message, stack: (error as Error).stack, data: data }); return Response.json({ error: "Failed" }, { status: 500 }); } } // Different log levels logger.debug("Cache hit", { key: "user_123", ttl: 3600 }); logger.info("User logged in", { userId: "123", ip: "1.2.3.4" }); logger.warn("Rate limit approached", { ip: "1.2.3.4", requests: 95 }); logger.error(new Error("Database connection failed"), { host: "db.example.com" }); // Add tags and user context logger.addTags(["payment", "critical"]); logger.setUser("user_123"); ``` -------------------------------- ### Text Localization API Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to translate single text strings with automatic caching for 5 minutes. ```APIDOC ## POST /localization ### Description Translate single text strings with automatic caching for 5 minutes. ### Method POST ### Endpoint https://api.analytics.customhack.dev/localization ### Parameters #### Request Body - **key** (string) - Required - The text string to translate. - **language** (string) - Optional - The target language code (e.g., 'es', 'fr'). If not provided, the browser's language will be auto-detected. ### Request Example ```json { "key": "An error occurred while processing your request", "language": "es" } ``` ### Response #### Success Response (200) - **result** (string) - The translated text string. #### Response Example ```json { "result": "Se produjo un error al procesar su solicitud" } ``` ``` -------------------------------- ### Object Localization API Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to translate entire objects with multiple string properties. ```APIDOC ## POST /localization/object ### Description Translate entire objects with multiple string properties. ### Method POST ### Endpoint https://api.analytics.customhack.dev/localization/object ### Parameters #### Request Body - **content** (object) - Required - The object containing string properties to translate. - **sourceLocale** (string) - Required - The source language code (e.g., 'en'). - **targetLocale** (string) - Required - The target language code (e.g., 'de'). ### Request Example ```json { "content": { "title": "Payment Error", "message": "Your payment could not be processed", "action": "Try again" }, "sourceLocale": "en", "targetLocale": "de" } ``` ### Response #### Success Response (200) - **result** (object) - The translated object with properties localized. #### Response Example ```json { "result": { "title": "Zahlungsfehler", "message": "Ihre Zahlung konnte nicht verarbeitet werden", "action": "Erneut versuchen" } } ``` ``` -------------------------------- ### Authenticate API Requests with Better Analytics SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt This snippet shows how to authenticate API requests for secure data ingestion using Bearer tokens. It includes initializing the SDK with an access token and making authenticated POST requests to the ingest and log endpoints. An alternative method demonstrates passing the token directly in the request body. ```typescript // Initialize SDK with access token const analytics = createErrorTracker({ apiUrl: "https://api.analytics.customhack.dev", clientId: "client_abc123", accessToken: "your-access-token-here", // Optional but recommended autoCapture: true }); // Making authenticated requests fetch("https://api.analytics.customhack.dev/ingest", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer your-access-token-here" }, body: JSON.stringify({ client_id: "client_abc123", message: "Error message", // ... other fields }) }); // Alternative: Pass token in request body fetch("https://api.analytics.customhack.dev/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: "client_abc123", accessToken: "your-access-token-here", level: "error", message: "Log message", // ... other fields }) }); ``` -------------------------------- ### Client-Side Error Tracking with TypeScript SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Initialize the error tracker using the @better-analytics/sdk for client-side applications. This SDK automatically captures unhandled errors and promise rejections. It requires configuration for API URL, client ID, access token, and environment. Custom exceptions and events can also be tracked. ```typescript import { createErrorTracker } from "@better-analytics/sdk"; export const analytics = createErrorTracker({ apiUrl: process.env.NEXT_PUBLIC_API_URL || "https://api.analytics.customhack.dev", clientId: process.env.NEXT_PUBLIC_CLIENT_ID || "", accessToken: process.env.NEXT_PUBLIC_ACCESS_TOKEN || "", autoCapture: true, environment: "production", debug: false, userId: "user_123" }); // Use in error boundary export default function Error({ error }: { error: Error }) { useEffect(() => { analytics.captureException(error); }, [error]); return
Something went wrong!
; } // Track custom errors try { await processPayment(amount); } catch (error) { analytics.captureException(error as Error, { context: "checkout", userId: "user_123", amount: amount }); } // Track custom events analytics.track("Payment failed", { userId: "123", errorCode: "INSUFFICIENT_FUNDS" }); ``` -------------------------------- ### Translate Object Properties using cURL and SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to translate entire objects with multiple string properties. Requires the content object, source locale, and target locale. The SDK provides a convenient method for object localization. ```bash curl -X POST https://api.analytics.customhack.dev/localization/object \ -H "Content-Type: application/json" \ -d '{ "content": { "title": "Payment Error", "message": "Your payment could not be processed", "action": "Try again" }, "sourceLocale": "en", "targetLocale": "de" }' ``` ```javascript const content = { title: "Error", message: "Something went wrong", buttonText: "Retry" }; const translated = await analytics.localizeObject(content, "ja"); console.log(translated.title); // "エラー" ``` -------------------------------- ### Track 404 Page Not Found using cURL Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to track 404 Not Found pages with user agent and geolocation data. Requires client ID, the URL of the missing page, referrer, source, environment, and optional user ID, session ID, and tags. ```bash curl -X POST https://api.analytics.customhack.dev/track-404 \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your-access-token" \ -d '{ "client_id": "client_abc123", "url": "https://example.com/missing-page", "referrer": "https://google.com/search", "source": "website", "environment": "production", "user_id": "user_123", "session_id": "session_xyz789", "tags": ["404", "broken-link"] }' ``` -------------------------------- ### Server-Side Log Levels (TypeScript) Source: https://github.com/databuddy-analytics/better-analytics/blob/main/README.md Demonstrates the usage of different log levels (info, warn, error) provided by the Better Analytics server-side logger to categorize and record events. ```typescript logger.info("User logged in", { userId: "123" }); logger.warn("Rate limit approached", { ip: "1.2.3.4" }); logger.error("Database connection failed", { error }); ``` -------------------------------- ### Authentication and Authorization Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt Details on how the API endpoints handle authentication using Bearer tokens and optional access tokens for secure data ingestion. ```APIDOC ## Authentication and Authorization API endpoints use Bearer token authentication with optional access tokens for secure data ingestion. ### Description This section explains the authentication mechanisms employed by the Better Analytics API. It covers the use of Bearer tokens in the `Authorization` header and how access tokens can be included either in the header or directly within the request body for specific endpoints. ### Authentication Methods 1. **Bearer Token in Header**: The recommended method for authenticating requests. - Include the `Authorization` header with the value `Bearer YOUR_ACCESS_TOKEN`. 2. **Access Token in Request Body**: An alternative method where the access token is provided within the JSON payload. ### Request Example (Bearer Token) ```typescript // Initialize SDK with access token (optional but recommended) const analytics = createErrorTracker({ apiUrl: "https://api.analytics.customhack.dev", clientId: "client_abc123", accessToken: "your-access-token-here", autoCapture: true }); // Making authenticated requests using Fetch API fetch("https://api.analytics.customhack.dev/ingest", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": "Bearer your-access-token-here" }, body: JSON.stringify({ client_id: "client_abc123", message: "Error message", // ... other fields }) }); ``` ### Request Example (Access Token in Body) ```typescript fetch("https://api.analytics.customhack.dev/log", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ client_id: "client_abc123", accessToken: "your-access-token-here", level: "error", message: "Log message", // ... other fields }) }); ``` ### Parameters #### Request Body (for POST /ingest or /log) - **client_id** (string) - Required - Your application's client ID. - **accessToken** (string) - Optional (if using Bearer token header) - Your access token. - **message** (string) - Required - The log message or error description. - **level** (string) - Optional - The severity level of the log (e.g., 'info', 'warn', 'error'). #### Headers - **Content-Type**: `application/json` - **Authorization**: `Bearer YOUR_ACCESS_TOKEN` (Required for Bearer token method) ``` -------------------------------- ### Log Ingestion API Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to ingest application logs with contextual information and custom metadata. ```APIDOC ## POST /log ### Description Ingest application logs with contextual information and custom metadata. ### Method POST ### Endpoint https://api.analytics.customhack.dev/log ### Parameters #### Request Body - **client_id** (string) - Required - Client identifier. - **level** (string) - Required - Log level (e.g., debug, info, warn, error). - **message** (string) - Required - The log message. - **source** (string) - Required - The source of the log (e.g., api-server, website). - **environment** (string) - Required - The environment (e.g., production, staging). - **user_id** (string) - Optional - The user identifier. - **session_id** (string) - Optional - The session identifier. - **tags** (array of strings) - Optional - List of tags associated with the log. - **context** (string) - Optional - JSON string containing additional context. ### Request Example ```json { "client_id": "client_abc123", "level": "error", "message": "Database connection timeout after 30s", "source": "api-server", "environment": "production", "user_id": "user_123", "session_id": "session_xyz789", "tags": ["database", "timeout"], "context": "{\"host\":\"db.example.com\",\"port\":5432,\"timeout\":30000}" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success or failure. - **id** (string) - The unique identifier for the ingested log. #### Response Example ```json { "status": "success", "id": "660f9511-f39c-52e5-b827-557766551111" } ``` ``` -------------------------------- ### Translate Text String using cURL and SDK Source: https://context7.com/databuddy-analytics/better-analytics/llms.txt POST endpoint to translate single text strings with automatic caching for 5 minutes. Requires a key (text to translate) and target language. The SDK also supports auto-detection of the browser's language. ```bash curl -X POST https://api.analytics.customhack.dev/localization \ -H "Content-Type: application/json" \ -d '{ "key": "An error occurred while processing your request", "language": "es" }' ``` ```javascript const translated = await analytics.localize( "Error occurred", "fr" ); console.log(translated); // "Une erreur s'est produite" // Auto-detect browser language const autoTranslated = await analytics.localize("Error occurred"); ```