### Installation Source: https://preview.databuddy.cc/docs/sdk/node Instructions on how to install the Databuddy Node SDK using Bun. ```APIDOC ## Installation {`bun add @databuddy/sdk`} ``` -------------------------------- ### Manual Installation Tracking Script - Framer Source: https://preview.databuddy.cc/docs/Integrations/framer Use this script in the 'Start of tag' section of your Framer site's custom code for manual installation. Ensure you replace 'YOUR_CLIENT_ID' with your actual client ID. ```html ``` -------------------------------- ### Install Databuddy SDK Source: https://preview.databuddy.cc/docs/sdk/react Install the Databuddy SDK package using bun. ```bash bun add @databuddy/sdk ``` -------------------------------- ### Install Databuddy SDK Source: https://preview.databuddy.cc/docs/Integrations/nextjs Install the Databuddy SDK using your preferred package manager. ```bash bun add @databuddy/sdk ``` ```bash npm install @databuddy/sdk ``` ```bash yarn add @databuddy/sdk ``` -------------------------------- ### Install Databuddy SDK Source: https://preview.databuddy.cc/docs/Integrations/react Install the Databuddy SDK using npm or yarn. ```bash npm install @databuddy/sdk ``` ```bash yarn add @databuddy/sdk ``` -------------------------------- ### TL;DR Example Source: https://preview.databuddy.cc/docs/sdk/node A quick example demonstrating the basic usage of the Node SDK for tracking server-side events. ```APIDOC ## TL;DR The Node SDK is perfect for tracking server-side events like API calls, background jobs, webhooks, and more. It supports batching and explicit flushes for serverless environments. {`import { Databuddy } from '@databuddy/sdk/node'; const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY!, enableBatching: true }); await client.track({ name: 'api_call', properties: { endpoint: '/api/users', method: 'GET' } }); await client.flush(); // Important in serverless!`} ``` -------------------------------- ### Vue Quick Start with Flags Plugin Source: https://preview.databuddy.cc/docs/sdk/feature-flags Set up the feature flags plugin for your Vue application. This example shows how to import the plugin and configure it with your client ID, API URL, and user information. Ensure 'currentUser' is correctly sourced from your app's authentication store. ```ts import { createApp } from 'vue'; import { createFlagsPlugin } from '@databuddy/sdk/vue'; import App from './App.vue'; // currentUser should come from your app's auth/session store. createApp(App) .use(createFlagsPlugin({ clientId: import.meta.env.VITE_DATABUDDY_CLIENT_ID, apiUrl: 'https://api.databuddy.cc', user: { userId: currentUser.id, organizationId: currentUser.organizationId, teamId: currentUser.teamId, properties: { role: currentUser.role, workspace_type: currentUser.workspaceType, }, }, })) .mount('#app'); ``` -------------------------------- ### Install Databuddy Node SDK Source: https://preview.databuddy.cc/docs/Integrations/sveltekit Install the Databuddy Node.js SDK for server-side tracking in your SvelteKit project. ```bash # Install the Node SDK npm install @databuddy/sdk ``` -------------------------------- ### Install Databuddy SDK (npm/yarn/bun) Source: https://preview.databuddy.cc/docs/getting-started Install the official Databuddy SDK using your preferred package manager. ```bash # Using bun (recommended) bun add @databuddy/sdk # Using npm npm install @databuddy/sdk # Using yarn yarn add @databuddy/sdk ``` -------------------------------- ### Server-Side Examples Source: https://preview.databuddy.cc/docs/api/events Examples of how to track events using the Basket API from different server-side environments. ```APIDOC ## Server-Side Examples ### Node.js / TypeScript ```typescript async function trackEvent( name: string, properties?: Record ) { const response = await fetch('https://basket.databuddy.cc/track', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer your_api_key' }, body: JSON.stringify({ name, properties, timestamp: Date.now() }) }); return response.json(); } // Usage await trackEvent('purchase', { value: 99.99, currency: 'USD', product_id: 'prod_123' }); ``` ### Python ```python import requests import time def track_event(name: str, properties: dict = None): response = requests.post( "https://basket.databuddy.cc/track", headers={ "Content-Type": "application/json", "Authorization": "Bearer your_api_key" }, json={ "name": name, "properties": properties or {}, "timestamp": int(time.time() * 1000) } ) return response.json() # Usage track_event("purchase", { "value": 99.99, "currency": "USD", "product_id": "prod_123" }) ``` ### cURL ```bash curl -X POST https://basket.databuddy.cc/track \ -H "Content-Type: application/json" \ -H "Authorization: Bearer your_api_key" \ -d '{ "name": "purchase", "properties": { "value": 99.99, "currency": "USD" } }' ``` ``` -------------------------------- ### Complete Website Integration Example Source: https://preview.databuddy.cc/docs/sdk/vanilla-js An example of integrating the Databuddy script into an HTML file, including custom event tracking and redirection with attribution. It enables performance and error tracking, along with batching. ```html My Website

Welcome

``` -------------------------------- ### Environment Variable Setup Source: https://preview.databuddy.cc/docs/Integrations/nextjs Add your Databuddy Client ID to your .env.local file. ```bash NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id ``` -------------------------------- ### Quick Start: Basic Event Tracking Source: https://preview.databuddy.cc/docs/sdk/node Initialize the Databuddy client and track a basic user signup event with properties. ```tsx import { Databuddy } from '@databuddy/sdk/node'; // Initialize the client const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY! }); // Track an event await client.track({ name: 'user_signup', properties: { plan: 'pro', source: 'api' } }); ``` -------------------------------- ### Quick Setup with CDN Source: https://preview.databuddy.cc/docs/sdk/vanilla-js Add this script tag to your HTML before the closing tag to quickly set up Databuddy. The script initializes automatically. ```html ``` -------------------------------- ### Install HTTP Client for Server-Side Tracking (Laravel) Source: https://preview.databuddy.cc/docs/Integrations/laravel This comment indicates that no additional package installation is needed for making HTTP requests in Laravel, as Guzzle is included by default. This is a prerequisite for server-side tracking. ```bash # Install HTTP client (Guzzle is included with Laravel) # No additional package needed ``` -------------------------------- ### Full Databuddy Component Example Source: https://preview.databuddy.cc/docs/sdk/vue A comprehensive example of the Databuddy component with various tracking and performance props enabled. It also shows how to conditionally disable tracking in development. ```html ``` -------------------------------- ### Pagination Example Source: https://preview.databuddy.cc/docs/api/query Demonstrates how to paginate through large result sets by specifying the desired page number and the number of items per page. ```json { "parameters": ["pages"], "startDate": "2024-01-01", "endDate": "2024-01-31", "limit": 50, "page": 2 } ``` -------------------------------- ### Error Example: Missing Authentication Source: https://preview.databuddy.cc/docs/api/errors Example of an error response when authentication is required but not provided. ```APIDOC ### Error Examples #### Missing Authentication ```json { "success": false, "error": "Authentication required", "code": "AUTH_REQUIRED" } ``` ``` -------------------------------- ### Install Databuddy DevTools Source: https://preview.databuddy.cc/docs/sdk/devtools Add Databuddy DevTools as a development dependency. ```bash bun add -d @databuddy/devtools ``` -------------------------------- ### Initialize Databuddy SDK for React Source: https://preview.databuddy.cc/docs/security Basic setup for the Databuddy React SDK. No consent banners are needed due to its privacy-first design. ```tsx import { Databuddy } from "@databuddy/sdk/react"; function App() { return ( <> {/* No consent needed - privacy-first by design */} {/* No cookie banner needed! */} ); } ``` -------------------------------- ### Filter Operation Example Source: https://preview.databuddy.cc/docs/api/query Provides an example of how to apply a filter to a query, specifying the field, operator, and value. ```json {"field": "country", "op": "eq", "value": "US"} ``` -------------------------------- ### Subscription Event Example Source: https://preview.databuddy.cc/docs/api/events Send a subscription_started event with plan, billing cycle, and MRR details. Ensure event names are consistent and use snake_case. ```json { "name": "subscription_started", "properties": { "plan": "pro", "billing_cycle": "annual", "mrr": 99 } } ``` -------------------------------- ### Configure Databuddy SDK with Vanilla JavaScript Source: https://preview.databuddy.cc/docs/sdk/configuration Configure the Databuddy SDK using script tag attributes. Attributes are prefixed with `data-`. For example, `clientId` becomes `data-client-id`. This example enables web vitals, error tracking, outgoing link tracking, and sets batching and sampling configurations. ```html ``` -------------------------------- ### Server-Side Aggregation Example Source: https://preview.databuddy.cc/docs/privacy/cookieless-analytics-guide An example of aggregated page statistics, including URL, views, unique sessions, average time, and bounce rate, processed on the server. ```javascript // Server-side aggregation const pageStats = { url: '/products', views: 1247, unique_sessions: 892, avg_time: 145, // seconds bounce_rate: 0.34 }; ``` -------------------------------- ### Environment Setup for Client ID Source: https://preview.databuddy.cc/docs/sdk/react Configure your Databuddy client ID in the .env.local file. The SDK will automatically detect and use this variable. ```bash NEXT_PUBLIC_DATABUDDY_CLIENT_ID=your-client-id-here ``` -------------------------------- ### Full Databuddy Component Example Source: https://preview.databuddy.cc/docs/sdk/react A comprehensive example of the Databuddy component with various tracking and configuration options enabled. This includes performance, errors, outgoing links, batching, sampling, and privacy settings. ```tsx import { Databuddy } from "@databuddy/sdk/react"; export default function RootLayout({ children }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Using API Key with x-api-key Header Source: https://preview.databuddy.cc/docs/api-keys Example of how to use an API key with the 'x-api-key' header for an API request. ```APIDOC ## Use Your Key You can authenticate with either header: ```bash curl -H "x-api-key: YOUR_API_KEY" \ "https://api.databuddy.cc/v1/websites/{website_id}/analytics" ``` ``` -------------------------------- ### Common User Signup Event Source: https://preview.databuddy.cc/docs/api/events Example JSON payload for tracking a user signup event, including signup method, plan, and referrer. ```json { "name": "signup", "properties": { "method": "email", "plan": "free", "referrer": "google" } } ``` -------------------------------- ### Configure Minimal Tracking Setup Source: https://preview.databuddy.cc/docs/security Sets up Databuddy with only essential analytics, disabling performance, Web Vitals, outgoing link, and error tracking. ```tsx // Essential analytics only ``` -------------------------------- ### Product Tracking Example Source: https://preview.databuddy.cc/docs/Integrations/react Track product-related events like 'product_view' and 'add_to_cart' within a product component. This example uses `useEffect` to track views and a button click handler for adding to cart. ```tsx import { useEffect } from 'react'; import { track } from '@databuddy/sdk'; function ProductCard({ product }) { useEffect(() => { track('product_view', { product_id: product.id, product_name: product.name, product_category: product.category, product_price: product.price }); }, [product]); const handleAddToCart = () => { track('add_to_cart', { product_id: product.id, quantity: 1, value: product.price }); }; return (

{product.name}

); } ``` -------------------------------- ### Privacy-Safe Attribution Example Source: https://preview.databuddy.cc/docs/privacy/cookieless-analytics-guide Demonstrates how to track conversion attribution using source, medium, and campaign information without relying on cross-site tracking or cookies. ```javascript // Attribution without cookies const attribution = { source: 'organic_search', medium: 'google', campaign: null, conversion_value: 99.99, time_to_conversion: 3600 // seconds }; ``` -------------------------------- ### Secure Environment Configuration for Databuddy Source: https://preview.databuddy.cc/docs/security This example demonstrates how to configure Databuddy with environment-specific settings, including different client IDs for development and production, and disabling tracking in development. ```tsx // Environment-specific settings const config = { development: { clientId: process.env.NEXT_PUBLIC_DATABUDDY_DEV_ID, disabled: true, // No tracking in development }, production: { clientId: process.env.NEXT_PUBLIC_DATABUDDY_PROD_ID, disabled: false, }, }[process.env.NODE_ENV]; ; ``` -------------------------------- ### App Router Setup Source: https://preview.databuddy.cc/docs/Integrations/nextjs Add the Databuddy React component to your app/layout.tsx for automatic page view and client-side route change tracking. ```tsx import { Databuddy } from "@databuddy/sdk/react"; export default function RootLayout({ children, }: { children: React.ReactNode }) { return ( {children} ); } ``` -------------------------------- ### Example JSON Response Format Source: https://preview.databuddy.cc/docs/api/query Illustrates the structure of a successful JSON response, including query data and metadata. Note that individual parameter success should be checked. ```json { "success": true, "queryId": "my-query-123", "data": [ { "parameter": "summary", "success": true, "data": [ { "date": "2024-01-01", "pageviews": 1250, "visitors": 890, "sessions": 1100 } ] }, { "parameter": "pages", "success": true, "data": [ { "path": "/", "pageviews": 450, "visitors": 320 } ] } ], "meta": { "parameters": ["summary", "pages"], "total_parameters": 2, "page": 1, "limit": 100, "filters_applied": 2 } } ``` -------------------------------- ### Pages Router Setup Source: https://preview.databuddy.cc/docs/Integrations/nextjs Add the Databuddy React component to your pages/_app.tsx for automatic page view and client-side route change tracking. ```tsx import { Databuddy } from "@databuddy/sdk/react"; import type { AppProps } from "next/app"; export default function MyApp({ Component, pageProps }: AppProps) { return ( <> ); } ``` -------------------------------- ### Feature Usage Event JSON Source: https://preview.databuddy.cc/docs/dashboard Example JSON structure for an event indicating feature usage, including feature name and plan details. ```json { "event": "feature_used", "properties": { "feature": "export_data", "plan": "pro", "usage_count": 5 } } ``` -------------------------------- ### TypeScript Support Examples Source: https://preview.databuddy.cc/docs/sdk Leverage the SDK's full TypeScript support by importing types for tracker helpers, React components, and Node.js event inputs. ```tsx import { track, type DatabuddyTracker } from "@databuddy/sdk"; import type { DatabuddyConfig } from "@databuddy/sdk/react"; import type { CustomEventInput } from "@databuddy/sdk/node"; ``` -------------------------------- ### Basic Usage Source: https://preview.databuddy.cc/docs/sdk/node Demonstrates the basic initialization and event tracking with the Databuddy Node SDK. ```APIDOC ### Basic Usage {`import { Databuddy } from '@databuddy/sdk/node'; // Initialize the client const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY! }); // Track an event await client.track({ name: 'user_signup', properties: { plan: 'pro', source: 'api' } });`} ``` -------------------------------- ### Install Databuddy via Theme Code Source: https://preview.databuddy.cc/docs/Integrations/shopify Add this script to your theme.liquid file before the closing tag for direct integration. Ensure you replace 'YOUR_CLIENT_ID' with your actual client ID. ```html ``` -------------------------------- ### Error Example: Rate Limit Exceeded Source: https://preview.databuddy.cc/docs/api/errors Example of an error response when the API rate limit has been exceeded. ```APIDOC #### Rate Limit Exceeded ```json { "success": false, "error": "Rate limit exceeded. Please try again later.", "code": "RATE_LIMIT_EXCEEDED", "limit": 200, "remaining": 0, "reset": "2024-01-01T12:00:10.000Z", "retryAfter": 8 } ``` ``` -------------------------------- ### Error Example: Invalid Query Type Source: https://preview.databuddy.cc/docs/api/errors Example of an error response when an invalid query type is specified. ```APIDOC #### Invalid Query Type ```json { "success": false, "error": "Unknown query type: summry", "code": "INVALID_QUERY_TYPE" } ``` ``` -------------------------------- ### Use Resource Hints for DNS Prefetching Source: https://preview.databuddy.cc/docs/performance/core-web-vitals-guide Implement 'dns-prefetch' resource hints to resolve domain names in advance, reducing latency for subsequent requests to external domains. ```html ``` -------------------------------- ### Error Example: Missing Resource Identifier Source: https://preview.databuddy.cc/docs/api/errors Example of an error response when a required resource identifier is missing from the request. ```APIDOC #### Missing Resource Identifier ```json { "success": false, "error": "Missing resource identifier (website_id, schedule_id, link_id, or organization_id)", "code": "MISSING_PROJECT_ID" } ``` ``` -------------------------------- ### Link Analytics API Example Response Source: https://preview.databuddy.cc/docs/api/links This is an example of a successful response for link analytics queries, including total clicks, daily clicks, and top referrers. ```json { "success": true, "queryId": "", "data": [ { "parameter": "link_total_clicks", "success": true, "data": [{ "total": 1542 }] }, { "parameter": "link_clicks_by_day", "success": true, "data": [ { "date": "2024-01-01", "clicks": 125 }, { "date": "2024-01-02", "clicks": 143 } ] }, { "parameter": "link_top_referrers", "success": true, "data": [ { "name": "twitter.com", "referrer": "twitter.com", "clicks": 523 }, { "name": "Direct", "referrer": "Direct", "clicks": 412 } ] } ], "meta": { "parameters": ["link_total_clicks", "link_clicks_by_day", "link_top_referrers"], "total_parameters": 3, "page": 1, "limit": 10, "filters_applied": 0 } } ``` -------------------------------- ### Prioritize Critical Resources with Preload and Prefetch Source: https://preview.databuddy.cc/docs/performance/core-web-vitals-guide Use `` to fetch critical resources early and `` to fetch resources for future navigation, optimizing resource loading. ```html ``` -------------------------------- ### Get Available Query Types Source: https://preview.databuddy.cc/docs/api/query Retrieve a list of available query types and their configurations. This endpoint is public and does not require authentication. Set `include_meta=true` to get detailed descriptions and field information. ```http GET /v1/query/types?include_meta=true ``` -------------------------------- ### Initialize Databuddy Node SDK Source: https://preview.databuddy.cc/docs/Integrations/sveltekit Set up the Databuddy Node.js SDK with your API key and website ID. This code should be placed in a module that can be imported across your server-side code. ```typescript import { Databuddy } from '@databuddy/sdk/node'; import { DATABUDDY_API_KEY, DATABUDDY_WEBSITE_ID } from '$env/static/private'; export const databuddy = new Databuddy({ apiKey: DATABUDDY_API_KEY, websiteId: DATABUDDY_WEBSITE_ID }); // Track server-side events export async function trackServerEvent(name: string, properties?: Record) { await databuddy.track({ name, properties, anonymousId: 'server-event', // Use an appropriate identifier source: 'server' }); await databuddy.flush(); } ``` -------------------------------- ### Configure Databuddy SDK in Vue Source: https://preview.databuddy.cc/docs/sdk/configuration Configure the Databuddy SDK in Vue using props with kebab-case naming. For example, `clientId` becomes `:client-id` and `trackWebVitals` becomes `:track-web-vitals`. This example shows enabling web vitals tracking, error tracking, and batching. ```html ``` -------------------------------- ### List Websites using API Key Source: https://preview.databuddy.cc/docs/api Use this command to list all websites associated with your API key. Replace `dbdy_your_api_key` with your actual API key. ```bash curl -H "x-api-key: dbdy_your_api_key" \ https://api.databuddy.cc/v1/query/websites ``` -------------------------------- ### Configuration Options Source: https://preview.databuddy.cc/docs/sdk/node Details the various configuration options available when initializing the Databuddy Node SDK client. ```APIDOC ## Configuration {`interface DatabuddyConfig { apiKey: string; // Required: Your API key for authentication websiteId?: string; // Optional: Default Client ID to scope events namespace?: string; // Optional: Default namespace for logical grouping source?: string; // Optional: Default source identifier for events apiUrl?: string; // Default: 'https://basket.databuddy.cc' debug?: boolean; // Enable debug logging logger?: Logger; // Custom logger instance enableBatching?: boolean; // Default: true batchSize?: number; // Default: 10, Max: 100 batchTimeout?: number; // Default: 2000ms maxQueueSize?: number; // Default: 1000 enableDeduplication?: boolean; // Default: true maxDeduplicationCacheSize?: number; // Default: 10000 middleware?: Middleware[]; // Transform or drop events before send }`} {`import { Databuddy } from '@databuddy/sdk/node'; const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY!, enableBatching: true, batchSize: 20, batchTimeout: 5000 });`} ``` -------------------------------- ### Insufficient Permissions Error Source: https://preview.databuddy.cc/docs/api-keys Example of an insufficient permissions error response. ```APIDOC ## Errors Authentication/authorization failures return structured errors: ```json { "success": false, "error": "Insufficient permissions", "code": "FORBIDDEN" } ``` ``` -------------------------------- ### Authentication Required Error Source: https://preview.databuddy.cc/docs/api-keys Example of an authentication required error response. ```APIDOC ## Errors Authentication/authorization failures return structured errors: ```json { "success": false, "error": "Authentication required", "code": "AUTH_REQUIRED" } ``` ``` -------------------------------- ### Node.js SDK Configuration Source: https://preview.databuddy.cc/docs/sdk/configuration Initialize the Databuddy SDK in a Node.js environment with various options for API access, event batching, deduplication, and middleware. ```APIDOC ## Node.js SDK Initialization ### Description Initialize the Databuddy SDK for server-side applications using Node.js. Configure essential parameters like API key, website ID, and options for event batching, deduplication, and middleware. ### Method `new Databuddy(options)` ### Parameters #### Options - **apiKey** (string) - Required - Your API key for authentication. - **websiteId** (string) - Optional - Default Client ID to scope events. - **namespace** (string) - Optional - Default namespace for logical grouping. - **source** (string) - Optional - Default source identifier for events. - **apiUrl** (string) - Optional - API endpoint. Defaults to `https://basket.databuddy.cc`. - **enableBatching** (boolean) - Optional - Enable event batching. Defaults to `true`. - **batchSize** (number) - Optional - Batch size. Defaults to `10`, max is `100`. - **batchTimeout** (number) - Optional - Batch timeout in ms. Defaults to `2000`. - **maxQueueSize** (number) - Optional - Maximum queue size. Defaults to `1000`. - **enableDeduplication** (boolean) - Optional - Deduplicate events by ID. Defaults to `true`. - **maxDeduplicationCacheSize** (number) - Optional - Dedup cache size. Defaults to `10000`. - **middleware** (Middleware[]) - Optional - Event transform functions. - **debug** (boolean) - Optional - Enable debug logging. Defaults to `false`. - **logger** (Logger) - Optional - Custom logger instance. ### Request Example ```typescript import { Databuddy } from "@databuddy/sdk/node"; const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY!, websiteId: process.env.DATABUDDY_WEBSITE_ID, namespace: "api", source: "backend", apiUrl: "https://basket.databuddy.cc", enableBatching: true, batchSize: 10, batchTimeout: 2000, maxQueueSize: 1000, enableDeduplication: true, maxDeduplicationCacheSize: 10_000, middleware: [ (event) => { event.properties = { ...event.properties, server: true }; return event; } ], debug: false, logger: customLogger }); ``` ``` -------------------------------- ### Get Query Types Source: https://preview.databuddy.cc/docs/api/query Retrieves available query types and their configurations, including metadata if requested. ```APIDOC ## GET /v1/query/types ### Description Discover available query types and their configurations. This endpoint is public and doesn't require authentication. ### Method GET ### Endpoint /v1/query/types ### Query Parameters - **include_meta** (boolean) - Optional - Set to `true` to get descriptions, output fields, and visualization hints. ### Response #### Success Response (200) - **success** (boolean) - Indicates if the request was successful. - **types** (array) - A list of available query type names. - **configs** (object) - Configuration details for each query type. - **[type_name]** (object) - Configuration for a specific query type. - **allowedFilters** (array) - List of filters allowed for this type. - **customizable** (boolean) - Whether the type is customizable. - **defaultLimit** (number) - Default limit for results. - **meta** (object) - Metadata about the query type. - **description** (string) - Description of the query type. - **outputFields** (array) - Fields that can be returned by this query type. #### Response Example ```json { "success": true, "types": ["summary", "pages", "traffic", "browser_name", "..."], "configs": { "summary": { "allowedFilters": ["country", "device_type", "browser_name"], "customizable": true, "defaultLimit": 100, "meta": { "description": "Overall website metrics and KPIs", "outputFields": ["pageviews", "visitors", "sessions", "..."] } } } } ``` ``` -------------------------------- ### Configure Batching Options Source: https://preview.databuddy.cc/docs/sdk/node Initialize the Databuddy client with custom batching configurations, including batch size and timeout. ```tsx import { Databuddy } from '@databuddy/sdk/node'; const client = new Databuddy({ apiKey: process.env.DATABUDDY_API_KEY!, enableBatching: true, batchSize: 20, batchTimeout: 5000 }); ``` -------------------------------- ### Troubleshooting: Access Denied Source: https://preview.databuddy.cc/docs/api/errors Guidance for resolving 'Access denied' errors. ```APIDOC ### "Access denied" - Check that your API key has access to this website - Verify the API key has the required scope (`read:data`) - For website-specific keys, ensure the website is in the allowed list ``` -------------------------------- ### Invalid Query Type Error Example Source: https://preview.databuddy.cc/docs/api/errors This response indicates that an unrecognized query type was provided in the request parameters. ```json { "success": false, "error": "Unknown query type: summry", "code": "INVALID_QUERY_TYPE" } ``` -------------------------------- ### Production Setup with Disabled Tracking Source: https://preview.databuddy.cc/docs/Integrations/nextjs Conditionally disable tracking outside of production environments by setting the 'disabled' prop. ```tsx ``` -------------------------------- ### Script Tag Setup Source: https://preview.databuddy.cc/docs/Integrations/nextjs Alternatively, use the script tag in pages/_document.tsx for tracking if you prefer not to use the React component. ```tsx import { Head, Html, Main, NextScript } from "next/document"; export default function Document() { return ( ``` -------------------------------- ### Using API Key with Authorization Header Source: https://preview.databuddy.cc/docs/api-keys Example of how to use an API key with the 'Authorization: Bearer' header for an API request. ```APIDOC ## Use Your Key You can authenticate with either header: ```bash curl -H "Authorization: Bearer YOUR_API_KEY" \ "https://api.databuddy.cc/v1/websites/{website_id}/analytics" ``` ``` -------------------------------- ### Batch Queries Example Source: https://preview.databuddy.cc/docs/api/rate-limits To optimize API usage and avoid exceeding rate limits, combine multiple queries into a single batch request instead of making individual requests. ```json // Instead of 3 separate requests: // POST /v1/query { parameters: ["summary"] } // POST /v1/query { parameters: ["pages"] } // POST /v1/query { parameters: ["traffic"] } // Use one batch request: POST /v1/query { "parameters": ["summary", "pages", "traffic"], "startDate": "2024-01-01", "endDate": "2024-01-31" } ``` -------------------------------- ### getValue Source: https://preview.databuddy.cc/docs/sdk/server-flags Get a typed value from the cache for a given flag key. Provides a default value if the flag is not found or not enabled. ```APIDOC ## getValue(key, defaultValue) Get a typed value from cache: ``` -------------------------------- ### Initialize FlagsProvider with Client ID and API URL Source: https://preview.databuddy.cc/docs/sdk/feature-flags Configure the FlagsProvider with your client ID, API endpoint, and user context. Set `isPending` to defer evaluation until the user session is loaded, and enable debug logging in development. ```tsx ``` -------------------------------- ### Parallel Tracking Implementation HTML Source: https://preview.databuddy.cc/docs/privacy/cookieless-analytics-guide HTML snippet demonstrating how to run both cookieless (Databuddy) and traditional (GA4) tracking systems in parallel during a migration phase. ```html ``` -------------------------------- ### Pagination Source: https://preview.databuddy.cc/docs/api/query Use 'page' and 'limit' parameters to manage pagination for large result sets. Page numbering starts at 1. ```APIDOC ## Pagination Use `page` and `limit` for large result sets: Page numbering starts at 1. ``` -------------------------------- ### Configure Event Sampling Source: https://preview.databuddy.cc/docs/sdk/vanilla-js Reduce event volume by setting a sampling rate with `data-sampling-rate`. For example, `0.5` tracks 50% of events. ```html ``` -------------------------------- ### Optimize Images for LCP Source: https://preview.databuddy.cc/docs/performance/core-web-vitals-guide Implement modern image formats like AVIF and WebP, and use 'loading="eager"' for critical images to improve LCP. ```html Hero image ``` -------------------------------- ### Deploy databuddy.js with Git Source: https://preview.databuddy.cc/docs/Integrations/mintlify Commit and push the databuddy.js file to your repository to deploy the analytics script. Mintlify automatically includes .js files from the content directory on every page. ```bash git add databuddy.js git commit -m "feat(docs): add databuddy analytics" git push ``` -------------------------------- ### Missing Resource Identifier Error Example Source: https://preview.databuddy.cc/docs/api/errors This error occurs when a required identifier for a resource (like website_id or link_id) is missing from the request. ```json { "success": false, "error": "Missing resource identifier (website_id, schedule_id, link_id, or organization_id)", "code": "MISSING_PROJECT_ID" } ``` -------------------------------- ### Get Databuddy Tracking Script Source: https://preview.databuddy.cc/docs/Integrations/hugo Obtain the basic Databuddy tracking script from your dashboard. Replace 'YOUR_CLIENT_ID' with your actual Client ID. ```html ``` -------------------------------- ### Configure Databuddy Environment Variables (.env) Source: https://preview.databuddy.cc/docs/Integrations/laravel Store your Databuddy credentials securely in the .env file. This is the recommended approach for managing sensitive information. ```bash DATABUDDY_CLIENT_ID=your-client-id-here DATABUDDY_API_KEY=your-api-key-here DATABUDDY_WEBSITE_ID=your-client-id-here ``` -------------------------------- ### Automatic Error Tracking Setup Source: https://preview.databuddy.cc/docs/sdk/vanilla-js Enable automatic JavaScript error tracking by including the `data-track-errors` attribute in the Databuddy script tag. ```html ``` -------------------------------- ### Using Shorthand Alias Source: https://preview.databuddy.cc/docs/sdk/vanilla-js For convenience, use the shorter `window.db` alias instead of `window.databuddy` for tracking events and screen views. ```jsx window.db.track('button_click', { button_id: 'cta' }); window.db.screenView({ section: 'dashboard' }); ``` -------------------------------- ### API Key Authentication using x-api-key Header Source: https://preview.databuddy.cc/docs/api/authentication Use this method for server-side integrations. Include your API key in the `x-api-key` header of your request. ```bash curl -H "x-api-key: dbdy_your_api_key_here" \ https://api.databuddy.cc/v1/query/websites ``` -------------------------------- ### Basic Databuddy Script Setup in GTM Source: https://preview.databuddy.cc/docs/Integrations/gtm Use this Custom HTML tag in GTM to load the Databuddy script. Ensure to use `createElement` and `setAttribute` as GTM sanitizes non-standard attributes. ```html ``` -------------------------------- ### Measure LCP with JavaScript PerformanceObserver Source: https://preview.databuddy.cc/docs/performance/core-web-vitals-guide Observe the 'largest-contentful-paint' entry type using PerformanceObserver to log LCP candidates and their start times. ```javascript new PerformanceObserver((entryList) => { for (const entry of entryList.getEntries()) { console.log('LCP candidate:', entry.startTime, entry.element); } }).observe({entryTypes: ['largest-contentful-paint']}); ``` -------------------------------- ### Add Databuddy Script to SvelteKit app.html Source: https://preview.databuddy.cc/docs/Integrations/svelte Alternatively, include the Databuddy script directly in your SvelteKit project's `src/app.html` file within the `` section. Ensure 'YOUR_CLIENT_ID' is replaced with your actual client ID. ```html %sveltekit.head%
%sveltekit.body%
```