SDKs & Libraries
Use official SDKs and libraries to integrate pxlpeak into your applications across multiple programming languages.
Introduction
pxlpeak provides official SDKs for popular programming languages, making it easy to integrate analytics tracking, conversion attribution, and data retrieval into your applications. All SDKs are open-source, fully typed, and designed with developer experience in mind.
Supported Languages
| Language | Package | Status | Version |
|----------|---------|--------|---------|
| JavaScript/TypeScript | @pxlpeak/sdk | Stable | 2.x |
| Python | pxlpeak | Stable | 2.x |
| PHP | pxlpeak/pxlpeak-php | Stable | 1.x |
| Go | github.com/pxlpeak/pxlpeak-go | Beta | 0.9.x |
| Ruby | pxlpeak | Beta | 0.8.x |
JavaScript/TypeScript SDK
The JavaScript SDK is our most feature-complete client, supporting both browser and Node.js environments with full TypeScript support.
Installation
# npm
npm install @pxlpeak/sdk
# yarn
yarn add @pxlpeak/sdk
# pnpm
pnpm add @pxlpeak/sdk
# bun
bun add @pxlpeak/sdkQuick Start
import { PxlPeak } from '@pxlpeak/sdk';
// Initialize the client
const pxlpeak = new PxlPeak({
apiKey: process.env.PXLPEAK_API_KEY!,
siteId: process.env.PXLPEAK_SITE_ID!,
});
// Track an event
await pxlpeak.track({
event: 'button_click',
properties: {
button_id: 'cta-hero',
page: '/landing',
},
});
// Record a conversion
await pxlpeak.conversion({
type: 'purchase',
value: 99.99,
currency: 'USD',
orderId: 'order_123',
});Browser Usage
For client-side tracking, use the lightweight browser bundle:
<script src="https://cdn.pxlpeak.com/sdk/v2/pxlpeak.min.js"></script>
<script>
pxlpeak.init({
siteId: 'your-site-id',
trackPageviews: true,
trackClicks: true,
respectDoNotTrack: true,
});
</script>Or with ES modules:
import { PxlPeakBrowser } from '@pxlpeak/sdk/browser';
const tracker = new PxlPeakBrowser({
siteId: 'your-site-id',
debug: process.env.NODE_ENV === 'development',
});
// Auto-track page views on SPA navigation
tracker.enableAutoPageviews();
// Track custom events
tracker.track('signup_started', {
source: 'homepage',
variant: 'A',
});Server-Side Usage (Node.js)
import { PxlPeakServer } from '@pxlpeak/sdk/server';
const pxlpeak = new PxlPeakServer({
apiKey: process.env.PXLPEAK_API_KEY!,
// Optional: Custom API endpoint for self-hosted
baseUrl: 'https://api.pxlpeak.com',
});
// Fetch analytics data
const analytics = await pxlpeak.analytics.get({
siteId: 'site_123',
metrics: ['pageviews', 'visitors', 'bounce_rate'],
dateRange: {
start: '2026-01-01',
end: '2026-01-12',
},
groupBy: 'day',
});
// Create a segment
const segment = await pxlpeak.segments.create({
siteId: 'site_123',
name: 'High-Value Customers',
rules: [
{ field: 'total_spend', operator: 'gt', value: 500 },
{ field: 'orders_count', operator: 'gte', value: 3 },
],
});Next.js Integration
// app/providers.tsx
'use client';
import { PxlPeakProvider } from '@pxlpeak/sdk/react';
export function Providers({ children }: { children: React.ReactNode }) {
return (
<PxlPeakProvider
siteId={process.env.NEXT_PUBLIC_PXLPEAK_SITE_ID!}
trackPageviews
trackWebVitals
>
{children}
</PxlPeakProvider>
);
}// app/components/checkout-button.tsx
'use client';
import { usePxlPeak } from '@pxlpeak/sdk/react';
export function CheckoutButton({ cartTotal }: { cartTotal: number }) {
const { track, conversion } = usePxlPeak();
const handleCheckout = async () => {
track('checkout_started', { cart_value: cartTotal });
// After successful purchase
conversion({
type: 'purchase',
value: cartTotal,
currency: 'USD',
});
};
return <button onClick={handleCheckout}>Checkout</button>;
}TypeScript Types
The SDK exports all types for full IntelliSense support:
import type {
TrackEvent,
Conversion,
AnalyticsQuery,
AnalyticsResponse,
Segment,
SegmentRule,
Site,
User,
Webhook,
RateLimitInfo,
} from '@pxlpeak/sdk';
// Strongly typed event tracking
const event: TrackEvent = {
event: 'form_submit',
properties: {
form_id: 'contact',
fields_count: 5,
},
timestamp: new Date().toISOString(),
};Error Handling
import {
PxlPeak,
PxlPeakError,
RateLimitError,
AuthenticationError,
ValidationError,
} from '@pxlpeak/sdk';
const pxlpeak = new PxlPeak({ apiKey: 'your-key' });
try {
await pxlpeak.track({ event: 'test' });
} catch (error) {
if (error instanceof RateLimitError) {
console.log(`Rate limited. Retry after ${error.retryAfter}ms`);
} else if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof ValidationError) {
console.error('Invalid request:', error.errors);
} else if (error instanceof PxlPeakError) {
console.error(`API Error: ${error.code} - ${error.message}`);
}
}Configuration Options
const pxlpeak = new PxlPeak({
apiKey: 'pk_live_...',
siteId: 'site_123',
// API configuration
baseUrl: 'https://api.pxlpeak.com', // Custom endpoint
timeout: 30000, // Request timeout in ms
// Retry configuration
retry: {
maxRetries: 3,
backoffFactor: 2,
maxBackoff: 30000,
},
// Batching (for high-volume tracking)
batch: {
enabled: true,
maxSize: 100,
flushInterval: 5000, // ms
},
// Debug mode
debug: process.env.NODE_ENV === 'development',
// Custom headers
headers: {
'X-Custom-Header': 'value',
},
});Python SDK
The Python SDK provides a clean, Pythonic interface for interacting with the pxlpeak API.
Installation
# pip
pip install pxlpeak
# poetry
poetry add pxlpeak
# pipenv
pipenv install pxlpeakQuick Start
from pxlpeak import PxlPeak
# Initialize client
client = PxlPeak(
api_key="pk_live_...",
site_id="site_123"
)
# Track an event
client.track(
event="page_view",
properties={
"page": "/products",
"referrer": "google"
}
)
# Record a conversion
client.conversion(
type="purchase",
value=149.99,
currency="USD",
order_id="order_456"
)Async Support
import asyncio
from pxlpeak import AsyncPxlPeak
async def main():
client = AsyncPxlPeak(api_key="pk_live_...")
# Async tracking
await client.track(
event="signup",
properties={"plan": "pro"}
)
# Fetch analytics data
analytics = await client.analytics.get(
site_id="site_123",
metrics=["pageviews", "visitors"],
date_range={
"start": "2026-01-01",
"end": "2026-01-12"
}
)
print(f"Total pageviews: {analytics.data.pageviews}")
asyncio.run(main())Django Integration
# settings.py
INSTALLED_APPS = [
# ...
'pxlpeak.django',
]
PXLPEAK = {
'API_KEY': os.environ.get('PXLPEAK_API_KEY'),
'SITE_ID': os.environ.get('PXLPEAK_SITE_ID'),
'AUTO_TRACK_PAGEVIEWS': True,
'TRACK_USER_ID': True,
}
# views.py
from pxlpeak.django import track_event, track_conversion
@track_event('product_viewed')
def product_detail(request, product_id):
product = get_object_or_404(Product, id=product_id)
return render(request, 'product.html', {'product': product})
def checkout_complete(request):
order = Order.objects.get(id=request.session['order_id'])
track_conversion(
request,
type='purchase',
value=order.total,
order_id=str(order.id)
)
return redirect('order_confirmation')Flask Integration
from flask import Flask
from pxlpeak.flask import PxlPeakFlask
app = Flask(__name__)
pxlpeak = PxlPeakFlask(app)
app.config['PXLPEAK_API_KEY'] = 'pk_live_...'
app.config['PXLPEAK_SITE_ID'] = 'site_123'
@app.route('/signup', methods=['POST'])
def signup():
user = create_user(request.form)
pxlpeak.track('user_signup', {
'plan': request.form.get('plan'),
'source': request.args.get('utm_source')
})
return redirect('/dashboard')Data Classes and Type Hints
from pxlpeak.types import (
TrackEvent,
Conversion,
AnalyticsQuery,
Segment,
SegmentRule
)
# Typed event creation
event = TrackEvent(
event="button_click",
properties={
"button_id": "hero-cta",
"variant": "B"
}
)
# Create segments with type safety
segment = Segment(
name="Power Users",
rules=[
SegmentRule(field="sessions_count", operator="gte", value=10),
SegmentRule(field="last_active", operator="within", value="7d")
]
)Batch Processing
from pxlpeak import PxlPeak
client = PxlPeak(api_key="pk_live_...")
# Batch multiple events
events = [
{"event": "page_view", "properties": {"page": "/"}},
{"event": "page_view", "properties": {"page": "/about"}},
{"event": "button_click", "properties": {"id": "cta"}},
]
# Send all events in a single request
client.track_batch(events)
# Context manager for automatic batching
with client.batch_context() as batch:
for item in large_dataset:
batch.track("item_processed", {"item_id": item.id})
# Automatically flushed on context exitPHP SDK
The PHP SDK provides a modern, PSR-compliant client for PHP applications.
Installation
composer require pxlpeak/pxlpeak-phpQuick Start
<?php
use PxlPeak\Client;
$client = new Client([
'api_key' => getenv('PXLPEAK_API_KEY'),
'site_id' => getenv('PXLPEAK_SITE_ID'),
]);
// Track an event
$client->track([
'event' => 'page_view',
'properties' => [
'page' => '/products',
'category' => 'electronics'
]
]);
// Record a conversion
$client->conversion([
'type' => 'purchase',
'value' => 299.99,
'currency' => 'USD',
'order_id' => 'order_789'
]);Laravel Integration
// config/pxlpeak.php
return [
'api_key' => env('PXLPEAK_API_KEY'),
'site_id' => env('PXLPEAK_SITE_ID'),
'queue' => env('PXLPEAK_QUEUE', 'default'),
];
// app/Providers/PxlPeakServiceProvider.php
use PxlPeak\Laravel\PxlPeakServiceProvider;
// Usage in controllers
use PxlPeak\Facades\PxlPeak;
class OrderController extends Controller
{
public function complete(Request $request)
{
$order = Order::find($request->order_id);
PxlPeak::conversion([
'type' => 'purchase',
'value' => $order->total,
'order_id' => $order->id,
'properties' => [
'items_count' => $order->items->count(),
'coupon_used' => $order->coupon?->code,
]
]);
return redirect()->route('order.confirmation');
}
}Middleware for Automatic Tracking
// app/Http/Middleware/TrackPageviews.php
namespace App\Http\Middleware;
use Closure;
use PxlPeak\Facades\PxlPeak;
class TrackPageviews
{
public function handle($request, Closure $next)
{
$response = $next($request);
if ($request->isMethod('GET') && !$request->ajax()) {
PxlPeak::track([
'event' => 'page_view',
'properties' => [
'url' => $request->fullUrl(),
'referrer' => $request->header('referer'),
'user_agent' => $request->userAgent(),
]
]);
}
return $response;
}
}Async with Queues
use PxlPeak\Laravel\Jobs\TrackEvent;
// Dispatch tracking to queue for better performance
TrackEvent::dispatch([
'event' => 'heavy_operation',
'properties' => ['duration' => $duration]
])->onQueue('analytics');Go SDK
The Go SDK provides a high-performance, concurrent-safe client for Go applications.
Installation
go get github.com/pxlpeak/pxlpeak-goQuick Start
package main
import (
"context"
"log"
"os"
"github.com/pxlpeak/pxlpeak-go"
)
func main() {
client := pxlpeak.NewClient(
pxlpeak.WithAPIKey(os.Getenv("PXLPEAK_API_KEY")),
pxlpeak.WithSiteID(os.Getenv("PXLPEAK_SITE_ID")),
)
ctx := context.Background()
// Track an event
err := client.Track(ctx, &pxlpeak.TrackEvent{
Event: "user_signup",
Properties: map[string]interface{}{
"plan": "enterprise",
"source": "referral",
},
})
if err != nil {
log.Printf("Track error: %v", err)
}
// Record a conversion
err = client.Conversion(ctx, &pxlpeak.Conversion{
Type: "purchase",
Value: 499.99,
Currency: "USD",
OrderID: "order_abc",
})
if err != nil {
log.Printf("Conversion error: %v", err)
}
}Concurrent Batch Processing
package main
import (
"context"
"sync"
"github.com/pxlpeak/pxlpeak-go"
)
func trackEvents(client *pxlpeak.Client, events []Event) error {
ctx := context.Background()
// Use buffered channel for rate limiting
semaphore := make(chan struct{}, 10)
var wg sync.WaitGroup
errChan := make(chan error, len(events))
for _, event := range events {
wg.Add(1)
semaphore <- struct{}{}
go func(e Event) {
defer wg.Done()
defer func() { <-semaphore }()
if err := client.Track(ctx, &pxlpeak.TrackEvent{
Event: e.Name,
Properties: e.Props,
}); err != nil {
errChan <- err
}
}(event)
}
wg.Wait()
close(errChan)
// Collect errors
var errs []error
for err := range errChan {
errs = append(errs, err)
}
if len(errs) > 0 {
return fmt.Errorf("tracking errors: %v", errs)
}
return nil
}HTTP Middleware
package middleware
import (
"net/http"
"time"
"github.com/pxlpeak/pxlpeak-go"
)
func PxlPeakMiddleware(client *pxlpeak.Client) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
start := time.Now()
// Wrap response writer to capture status
wrapped := &responseWriter{ResponseWriter: w, status: 200}
next.ServeHTTP(wrapped, r)
// Track pageview asynchronously
go client.Track(r.Context(), &pxlpeak.TrackEvent{
Event: "page_view",
Properties: map[string]interface{}{
"path": r.URL.Path,
"method": r.Method,
"status": wrapped.status,
"duration_ms": time.Since(start).Milliseconds(),
"user_agent": r.UserAgent(),
"referrer": r.Referer(),
},
})
})
}
}Ruby SDK
The Ruby SDK provides an idiomatic Ruby interface with support for Rails integration.
Installation
# Gemfile
gem 'pxlpeak'
# Or install directly
gem install pxlpeakQuick Start
require 'pxlpeak'
client = PxlPeak::Client.new(
api_key: ENV['PXLPEAK_API_KEY'],
site_id: ENV['PXLPEAK_SITE_ID']
)
# Track an event
client.track(
event: 'page_view',
properties: {
page: '/products',
category: 'shoes'
}
)
# Record a conversion
client.conversion(
type: 'purchase',
value: 89.99,
currency: 'USD',
order_id: 'order_xyz'
)Rails Integration
# config/initializers/pxlpeak.rb
PxlPeak.configure do |config|
config.api_key = Rails.application.credentials.pxlpeak[:api_key]
config.site_id = Rails.application.credentials.pxlpeak[:site_id]
config.async = true # Use background jobs
config.queue = :analytics
end
# app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
include PxlPeak::Rails::Tracking
after_action :track_pageview, unless: :skip_tracking?
private
def skip_tracking?
request.xhr? || request.format.json?
end
end
# app/controllers/orders_controller.rb
class OrdersController < ApplicationController
def create
@order = Order.create!(order_params)
pxlpeak.conversion(
type: 'purchase',
value: @order.total,
order_id: @order.id,
properties: {
items: @order.items.map(&:sku),
shipping_method: @order.shipping_method
}
)
redirect_to order_confirmation_path(@order)
end
endActiveJob Integration
# app/jobs/pxlpeak_track_job.rb
class PxlPeakTrackJob < ApplicationJob
queue_as :analytics
def perform(event_name, properties = {})
PxlPeak.client.track(
event: event_name,
properties: properties
)
end
end
# Usage
PxlPeakTrackJob.perform_later('user_upgraded', { plan: 'pro' })Common Patterns
Identifying Users
All SDKs support user identification for cross-device tracking:
// JavaScript
pxlpeak.identify({
userId: 'user_123',
traits: {
email: 'user@example.com',
plan: 'enterprise',
company: 'Acme Inc',
},
});# Python
client.identify(
user_id="user_123",
traits={
"email": "user@example.com",
"plan": "enterprise"
}
)Attribution Tracking
Track marketing attribution across all touchpoints:
// Automatically capture UTM parameters
pxlpeak.captureAttribution();
// Or manually set attribution
pxlpeak.setAttribution({
source: 'google',
medium: 'cpc',
campaign: 'spring_sale',
content: 'banner_a',
term: 'running shoes',
});A/B Testing Integration
// Track experiment exposure
pxlpeak.track('experiment_viewed', {
experiment_id: 'checkout_flow_v2',
variant: 'B',
});
// Track experiment conversion
pxlpeak.conversion({
type: 'experiment_conversion',
properties: {
experiment_id: 'checkout_flow_v2',
variant: 'B',
},
});Ecommerce Tracking
Standard ecommerce events across all SDKs:
// Product viewed
pxlpeak.track('product_viewed', {
product_id: 'SKU-123',
name: 'Running Shoes',
price: 129.99,
category: 'Footwear',
});
// Added to cart
pxlpeak.track('product_added_to_cart', {
product_id: 'SKU-123',
quantity: 1,
cart_value: 129.99,
});
// Checkout started
pxlpeak.track('checkout_started', {
cart_value: 259.98,
items_count: 2,
currency: 'USD',
});
// Purchase completed
pxlpeak.conversion({
type: 'purchase',
value: 259.98,
currency: 'USD',
orderId: 'order_456',
properties: {
items: ['SKU-123', 'SKU-456'],
shipping: 9.99,
tax: 20.00,
discount: 0,
},
});SDK Development
Contributing
All SDKs are open-source and welcome contributions:
- JavaScript: github.com/pxlpeak/pxlpeak-js
- Python: github.com/pxlpeak/pxlpeak-python
- PHP: github.com/pxlpeak/pxlpeak-php
- Go: github.com/pxlpeak/pxlpeak-go
- Ruby: github.com/pxlpeak/pxlpeak-ruby
Building Custom Integrations
If an official SDK doesn't exist for your language, you can build a custom integration using the REST API:
Base URL: https://api.pxlpeak.com/v1
Authentication: Bearer token in Authorization header
Content-Type: application/jsonKey endpoints:
POST /track- Track eventsPOST /conversion- Record conversionsPOST /identify- Identify usersGET /analytics- Query analytics data
See the API Endpoints documentation for complete details.
Support
- Documentation: docs.pxlpeak.com
- GitHub Issues: Report bugs on the respective SDK repository
- Discord: Join our developer community
- Email: sdk-support@pxlpeak.com
For urgent issues affecting production systems, contact support with your account ID for priority assistance.