Temps SDKs
Official SDKs and libraries to integrate Temps into your applications. Choose the right SDK for your use case—from framework-specific analytics to server-side API access.
Analytics SDKs Overview
Temps provides analytics SDKs for every major frontend runtime. They all capture the same signals — pageviews, custom events, Web Vitals, engagement heartbeats, page-leave events, and optional session recording — and send them to the same /api/_temps endpoints on your Temps instance.
| Package | Use for | Install |
|---|---|---|
@temps-sdk/react-analytics | React / Next.js apps | npm install @temps-sdk/react-analytics |
@temps-sdk/analytics-browser | Plain HTML pages, Astro islands, non-React SPAs | npm install @temps-sdk/analytics-browser |
@temps-sdk/vue-analytics | Vue 3 apps | npm install @temps-sdk/vue-analytics |
@temps-sdk/svelte-analytics | Svelte 4 / 5 and SvelteKit apps | npm install @temps-sdk/svelte-analytics |
@temps-sdk/analytics-core | Building your own framework adapter | npm install @temps-sdk/analytics-core |
Every SDK wraps the same framework-agnostic @temps-sdk/analytics-core, so behavior — payload shape, localhost detection, session recording, retry logic — is identical across frameworks. Pick the one that matches your stack.
What gets tracked by default? Pageviews (on route change), Web Vitals (LCP, FID, CLS, FCP, TTFB, INP), engagement heartbeats (every 30s while active), and a page_leave event on unload. Session recording is opt-in via enableSessionRecording.
React Analytics
Track pageviews, custom events, performance metrics, and session replays in your React applications.
Installation
npm install @temps-sdk/react-analytics
Quick Start
import { TempsAnalyticsProvider, useTrackEvent } from '@temps-sdk/react-analytics';
function App() {
return (
<TempsAnalyticsProvider>
<YourApp />
</TempsAnalyticsProvider>
);
}
function YourComponent() {
const trackEvent = useTrackEvent();
const handleClick = () => {
trackEvent('button_clicked', {
buttonId: 'cta-button',
location: 'homepage'
});
};
return <button onClick={handleClick}>Click me</button>;
}
Features
- Name
Automatic Pageview Tracking- Description
Automatically tracks pageviews on route changes (Next.js App Router, Pages Router, React Router).
<TempsAnalyticsProvider autoTrackPageviews={true}> {children} </TempsAnalyticsProvider>
- Name
Custom Event Tracking- Description
Track custom events with properties:
const trackEvent = useTrackEvent(); trackEvent('purchase_completed', { productId: '123', amount: 99.99, currency: 'USD' });
- Name
Session Replay- Description
Record and replay user sessions for debugging:
<TempsAnalyticsProvider sessionReplay={{ enabled: true, sampling: 0.1, // Record 10% of sessions privacy: { maskAllInputs: false, blockSelector: '.sensitive-data' } }} > {children} </TempsAnalyticsProvider>
- Name
Performance Metrics- Description
Automatic Web Vitals tracking (LCP, FID, CLS, FCP, TTFB).
- Name
Engagement Tracking- Description
Track user engagement time, scroll depth, and interaction patterns.
Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
basePath | string | /api/_temps | Base endpoint path for analytics |
disabled | boolean | false | Disable analytics completely |
ignoreLocalhost | boolean | true | Ignore localhost traffic |
domain | string | window.location.hostname | Custom domain for analytics |
autoTrackPageviews | boolean | true | Automatically track pageviews |
autoTrackPageLeave | boolean | true | Track page leave events |
pageLeaveEventName | string | page_leave | Custom event name for page leave |
autoTrackSpeedAnalytics | boolean | true | Track Web Vitals automatically |
autoTrackEngagement | boolean | true | Track user engagement with heartbeats |
heartbeatInterval | number | 30000 | Heartbeat interval in milliseconds |
inactivityTimeout | number | 30000 | Inactivity timeout in milliseconds |
engagementThreshold | number | 10000 | Engagement threshold in milliseconds |
enableSessionRecording | boolean | false | Enable session recording |
sessionRecordingConfig | object | {} | Session recording configuration |
Next.js Integration
App Router:
// app/layout.tsx
import { TempsAnalyticsProvider } from '@temps-sdk/react-analytics';
export default function RootLayout({ children }) {
return (
<html>
<body>
<TempsAnalyticsProvider>
{children}
</TempsAnalyticsProvider>
</body>
</html>
);
}
Pages Router:
// pages/_app.tsx
import { TempsAnalyticsProvider } from '@temps-sdk/react-analytics';
export default function App({ Component, pageProps }) {
return (
<TempsAnalyticsProvider>
<Component {...pageProps} />
</TempsAnalyticsProvider>
);
}
Vanilla JS Analytics
Framework-free analytics for plain HTML pages, Astro islands, Alpine.js, htmx, or any JS runtime without a framework wrapper.
Installation
npm install @temps-sdk/analytics-browser
Quick Start (programmatic)
import { init, trackEvent } from '@temps-sdk/analytics-browser';
// Boot once, typically in your entry file
init({
basePath: '/api/_temps',
autoTrackPageviews: true,
autoTrackSpeedAnalytics: true,
autoTrackEngagement: true,
});
// Later, anywhere
trackEvent('signup_clicked', { plan: 'pro' });
init() returns an AnalyticsApi and also attaches it to window.temps so other scripts can call window.temps.trackEvent(...) without importing.
Quick Start (script tag)
Drop-in for static sites — no bundler required. The /auto entrypoint reads data-* attributes from its own <script> tag and boots on DOMContentLoaded:
<script
src="https://unpkg.com/@temps-sdk/analytics-browser/dist/auto.js"
data-domain="mysite.com"
data-base-path="/api/_temps"
data-session-recording="true"
data-excluded-paths="/admin/*,/internal/*"
defer
></script>
Supported data-* attributes:
| Attribute | Type | Description |
|---|---|---|
data-domain | string | Override window.location.hostname |
data-base-path | string | Endpoint path (default /api/_temps) |
data-disabled | true / false | Disable entirely |
data-ignore-localhost | true / false | Skip localhost (default true) |
data-auto-track-pageviews | true / false | Auto-track route changes |
data-auto-track-page-leave | true / false | Track page_leave events |
data-auto-track-speed | true / false | Track Web Vitals |
data-auto-track-engagement | true / false | Heartbeat engagement tracking |
data-session-recording | true / false | Enable rrweb session recording |
data-excluded-paths | comma list | Paths to skip for recording, supports * |
data-session-sample-rate | 0–1 | Fraction of sessions to record |
data-heartbeat-interval | number (ms) | Heartbeat interval |
data-inactivity-timeout | number (ms) | Inactivity timeout |
data-engagement-threshold | number (ms) | When a session becomes "engaged" |
API
import {
init,
getAnalytics,
trackEvent,
trackPageview,
destroy,
} from '@temps-sdk/analytics-browser';
init(options); // Boot. Safe to call once per page.
getAnalytics(); // Returns current AnalyticsApi or null.
trackEvent(name, data?); // Async — fires and forgets.
trackPageview(); // Manual pageview. Usually not needed with auto-tracking.
destroy(); // Tear down listeners, timers, and session recorder.
Vue Analytics
First-class Vue 3 support via a plugin + composables. Works with Nuxt, Vite, and any Vue 3 SPA.
Installation
npm install @temps-sdk/vue-analytics
Quick Start
// main.ts
import { createApp } from 'vue';
import { TempsAnalyticsPlugin } from '@temps-sdk/vue-analytics';
import App from './App.vue';
const app = createApp(App);
app.use(TempsAnalyticsPlugin, {
basePath: '/api/_temps',
autoTrackPageviews: true,
enableSessionRecording: false,
});
app.mount('#app');
Composables
<script setup lang="ts">
import {
useTempsAnalytics,
useTrackEvent,
useTrackPageview,
usePageLeave,
useEngagementTracking,
useScrollVisibility,
useSessionRecording,
} from '@temps-sdk/vue-analytics';
// Raw API
const analytics = useTempsAnalytics();
// Convenience helpers
const trackEvent = useTrackEvent();
const trackPageview = useTrackPageview();
function onCtaClick() {
trackEvent('cta_clicked', { location: 'hero' });
}
// Track when the current page is about to be left
usePageLeave((data) => {
console.log('Leaving with engagement:', data.engagement_time_seconds);
});
// Reactive engagement signal
const { engagement, isEngaged } = useEngagementTracking();
// Scroll visibility for a ref
import { ref } from 'vue';
const pricingSection = ref<HTMLElement | null>(null);
useScrollVisibility(pricingSection, () => {
trackEvent('pricing_viewed');
});
// Session recording toggle
const { isEnabled, enable, disable, toggle } = useSessionRecording();
</script>
<template>
<button @click="onCtaClick">Get started</button>
<section ref="pricingSection">…</section>
</template>
Global property
The plugin also registers $temps as a global property for Options API components:
<script>
export default {
methods: {
handleClick() {
this.$temps.trackEvent('legacy_button');
},
},
};
</script>
Nuxt 3
In plugins/temps.client.ts:
import { TempsAnalyticsPlugin } from '@temps-sdk/vue-analytics';
export default defineNuxtPlugin((nuxtApp) => {
nuxtApp.vueApp.use(TempsAnalyticsPlugin, {
basePath: '/api/_temps',
});
});
Svelte Analytics
Store-based analytics for Svelte 4, Svelte 5 runes mode, and SvelteKit.
Installation
npm install @temps-sdk/svelte-analytics
Quick Start
// src/lib/analytics.ts
import { initTempsAnalytics } from '@temps-sdk/svelte-analytics';
export const analytics = initTempsAnalytics({
basePath: '/api/_temps',
autoTrackPageviews: true,
autoTrackSpeedAnalytics: true,
});
Call initTempsAnalytics() once in your root layout (browser-only — wrap in if (browser) on SvelteKit):
<!-- src/routes/+layout.svelte -->
<script lang="ts">
import { browser } from '$app/environment';
import { onMount } from 'svelte';
import { initTempsAnalytics } from '@temps-sdk/svelte-analytics';
onMount(() => {
if (browser) {
initTempsAnalytics({ basePath: '/api/_temps' });
}
});
</script>
<slot />
Tracking events
<script lang="ts">
import { getTempsAnalytics } from '@temps-sdk/svelte-analytics';
function onClick() {
getTempsAnalytics()?.trackEvent('hero_cta_clicked', { variant: 'a' });
}
</script>
<button on:click={onClick}>Get started</button>
The trackVisibility action
Fire an event when an element scrolls into view:
<script lang="ts">
import { trackVisibility } from '@temps-sdk/svelte-analytics';
</script>
<section
use:trackVisibility={{
eventName: 'pricing_viewed',
once: true,
threshold: 0.5,
data: { section: 'pricing' },
}}
>
<h2>Pricing</h2>
</section>
Engagement store
<script lang="ts">
import { engagementStore } from '@temps-sdk/svelte-analytics';
const engagement = engagementStore();
</script>
<p>Engagement: {$engagement.engagement_time_seconds}s</p>
{#if $engagement.is_engaged}
<span>Active visitor</span>
{/if}
Session recording store
<script lang="ts">
import { sessionRecordingStore } from '@temps-sdk/svelte-analytics';
const recording = sessionRecordingStore();
</script>
<button on:click={recording.toggle}>
{$recording.enabled ? 'Stop' : 'Start'} recording
</button>
analyticsStore readable
A Svelte readable that resolves to the current AnalyticsApi (or null before init completes). Handy for reactive templates:
<script lang="ts">
import { analyticsStore } from '@temps-sdk/svelte-analytics';
</script>
{#if $analyticsStore}
<p>Analytics ready on {$analyticsStore.enabled ? 'prod' : 'local'}</p>
{/if}
Analytics Core
@temps-sdk/analytics-core is the framework-agnostic engine behind the React, Vue, Svelte, and vanilla packages. Use it directly only when building a custom integration (Solid, Qwik, Preact, Web Components, etc.).
Installation
npm install @temps-sdk/analytics-core
API
import {
createAnalytics,
EngagementTracker,
SpeedTracker,
SessionRecorder,
sendAnalytics,
sendAnalyticsReliable,
DEFAULT_BASE_PATH,
type AnalyticsApi,
type AnalyticsOptions,
type EngagementData,
type SpeedMetric,
} from '@temps-sdk/analytics-core';
const analytics: AnalyticsApi = createAnalytics({
basePath: DEFAULT_BASE_PATH, // "/api/_temps"
autoTrackPageviews: true,
autoTrackSpeedAnalytics: true,
autoTrackEngagement: true,
enableSessionRecording: false,
});
analytics.trackEvent('custom_event', { foo: 'bar' });
analytics.trackPageview();
analytics.enableSessionRecording();
// When your app unmounts
analytics.destroy();
Building your own adapter
The individual trackers are standalone classes:
import { EngagementTracker, SpeedTracker, SessionRecorder } from '@temps-sdk/analytics-core';
const engagement = new EngagementTracker({
basePath: '/api/_temps',
heartbeatInterval: 30000,
onHeartbeat: (data) => console.log('beat', data),
});
const speed = new SpeedTracker({ basePath: '/api/_temps' });
const session = new SessionRecorder({
basePath: '/api/_temps',
enabled: true,
excludedPaths: ['/admin/*'],
});
session.start();
// Later
engagement.destroy();
speed.destroy();
session.destroy();
All trackers are safe to call in SSR contexts — they no-op when window is undefined.
Node.js SDK
Complete TypeScript SDK for accessing the Temps API from Node.js, Bun, or serverless environments.
Installation
npm install @temps-sdk/node-sdk
Quick Start
import { TempsClient } from '@temps-sdk/node-sdk';
const client = new TempsClient({
baseUrl: 'https://your-temps-instance.com',
apiKey: 'your-api-key'
});
// List projects
const projects = await client.projects.list();
// Create a deployment
const deployment = await client.deployments.create({
projectId: 1,
environment: 'production',
branch: 'main'
});
// Get analytics metrics
const metrics = await client.analytics.getAnalyticsMetrics({
projectId: 1,
from: '2024-01-01',
to: '2024-01-31'
});
Available APIs
The Node.js SDK provides access to all Temps API endpoints:
- Name
Projects- Description
Create, update, delete, and manage projects:
await client.projects.create({ name: 'my-app', ... }); await client.projects.list(); await client.projects.get(projectId); await client.projects.update(projectId, { ... });
- Name
Deployments- Description
Trigger deployments, check status, view logs:
await client.deployments.create({ projectId, environment, branch }); await client.deployments.list({ projectId }); await client.deployments.get(deploymentId); await client.deployments.getLogs(deploymentId);
- Name
Analytics- Description
Query analytics data, metrics, visitors, sessions:
await client.analytics.getAnalyticsMetrics({ projectId, from, to }); await client.analytics.getVisitors({ projectId }); await client.analytics.getSessionDetails(sessionId);
- Name
Domains- Description
Manage custom domains and SSL certificates:
await client.domains.create({ projectId, hostname }); await client.domains.provision(domainId); await client.domains.list({ projectId });
- Name
Services- Description
Manage PostgreSQL, Redis, and S3 services:
await client.services.create({ type: 'postgres', name: 'db' }); await client.services.linkToProject(serviceId, projectId);
- Name
API Keys- Description
Create and manage API keys:
await client.apiKeys.create({ name: 'my-key', permissions: [...] }); await client.apiKeys.list();
- Name
Webhooks- Description
Configure webhooks for events:
await client.webhooks.create({ projectId, url: 'https://example.com/webhook', events: ['deployment.succeeded'] });
- Name
Error Tracking- Description
Query error tracking data:
await client.errorTracking.getErrors({ projectId }); await client.errorTracking.getErrorDetails(errorId);
Authentication
Using API Keys:
const client = new TempsClient({
baseUrl: 'https://your-temps-instance.com',
apiKey: 'your-api-key'
});
Using Deployment Tokens:
const client = new TempsClient({
baseUrl: 'https://your-temps-instance.com',
apiKey: 'your-deployment-token'
});
Environment Variables:
TEMPS_API_URL=https://your-temps-instance.com
TEMPS_API_KEY=your-api-key
# or
TEMPS_TOKEN=your-deployment-token
// Automatically uses environment variables
const client = new TempsClient();
Key-Value Store
Lightweight SDK for Temps KV (key-value store) operations. Perfect for caching, sessions, and temporary data.
Installation
npm install @temps-sdk/kv
Quick Start
import { kv, createClient } from '@temps-sdk/kv';
// Using default client (uses env vars)
await kv.set('user:123', { name: 'John', email: 'john@example.com' });
const user = await kv.get('user:123');
await kv.del('user:123');
// With expiration
await kv.set('session:abc', sessionData, { ex: 3600 }); // 1 hour
// Increment counter
const count = await kv.incr('page:views');
// Pattern matching
const keys = await kv.keys('user:*');
Custom Client
import { createClient } from '@temps-sdk/kv';
const client = createClient({
apiUrl: 'https://your-temps-instance.com',
token: 'your-deployment-token',
projectId: 1 // Required for API keys, optional for deployment tokens
});
await client.set('key', 'value');
const value = await client.get('key');
API Reference
- Name
get<T>(key)- Description
Get the value of a key. Returns
nullif key doesn't exist.const value = await kv.get<string>('my-key');
- Name
set(key, value, options?)- Description
Set a key-value pair. Supports expiration.
await kv.set('key', 'value'); await kv.set('key', 'value', { ex: 60 }); // Expire in 60 seconds
- Name
del(...keys)- Description
Delete one or more keys. Returns count of deleted keys.
await kv.del('key1', 'key2', 'key3');
- Name
incr(key)- Description
Increment a numeric value. Returns new value.
const count = await kv.incr('counter');
- Name
expire(key, seconds)- Description
Set expiration on an existing key.
await kv.expire('key', 3600); // Expire in 1 hour
- Name
ttl(key)- Description
Get time-to-live of a key. Returns seconds remaining or
-1if no expiration.const ttl = await kv.ttl('key');
- Name
keys(pattern)- Description
Find keys matching a pattern (supports
*wildcard).const userKeys = await kv.keys('user:*');
Use Cases
Session Storage:
// Store session
await kv.set(`session:${sessionId}`, sessionData, { ex: 86400 }); // 24 hours
// Retrieve session
const session = await kv.get(`session:${sessionId}`);
Rate Limiting:
const key = `rate:${userId}`;
const count = await kv.incr(key);
if (count === 1) {
await kv.expire(key, 60); // Set expiration on first increment
}
if (count > 100) {
throw new Error('Rate limit exceeded');
}
Caching:
const cacheKey = `cache:${query}`;
let result = await kv.get(cacheKey);
if (!result) {
result = await expensiveOperation();
await kv.set(cacheKey, result, { ex: 300 }); // Cache for 5 minutes
}
Blob Storage
SDK for Temps Blob storage—upload, download, and manage files and binary data.
Installation
npm install @temps-sdk/blob
Quick Start
import { blob, createClient } from '@temps-sdk/blob';
// Upload a file
const result = await blob.put('uploads/image.jpg', fileBuffer, {
contentType: 'image/jpeg'
});
console.log(result.url); // Public URL
// Download a file
const response = await blob.download(result.url);
const data = await response.arrayBuffer();
// List files
const list = await blob.list({ prefix: 'uploads/', limit: 10 });
// Delete files
await blob.del(result.url);
Custom Client
import { createClient } from '@temps-sdk/blob';
const client = createClient({
apiUrl: 'https://your-temps-instance.com',
token: 'your-deployment-token',
projectId: 1 // Required for API keys
});
await client.put('path/to/file.txt', 'content');
API Reference
- Name
put(pathname, body, options?)- Description
Upload a blob. Returns URL and metadata.
const result = await blob.put('uploads/file.txt', 'content', { contentType: 'text/plain', addRandomSuffix: false });Body types:
string,Uint8Array,Blob,ArrayBuffer
- Name
download(url)- Description
Download a blob. Returns
Responseobject.const response = await blob.download(url); const text = await response.text(); const buffer = await response.arrayBuffer();
- Name
head(url)- Description
Get blob metadata without downloading content.
const metadata = await blob.head(url); console.log(metadata.size, metadata.contentType);
- Name
list(options?)- Description
List blobs with pagination and filtering.
const result = await blob.list({ prefix: 'uploads/', limit: 50, cursor: 'next-page-token' });
- Name
del(urls)- Description
Delete one or more blobs by URL.
await blob.del(url); await blob.del([url1, url2, url3]);
- Name
copy(fromUrl, toPathname)- Description
Copy a blob to a new location.
const newBlob = await blob.copy(oldUrl, 'new/path/file.txt');
Use Cases
File Upload:
// Upload from form
const formData = new FormData();
formData.append('file', fileInput.files[0]);
const file = await fileInput.files[0].arrayBuffer();
const result = await blob.put(`uploads/${filename}`, file, {
contentType: fileInput.files[0].type
});
Image Processing:
// Upload image
const imageResult = await blob.put('images/photo.jpg', imageBuffer, {
contentType: 'image/jpeg'
});
// Later, copy to processed folder
await blob.copy(imageResult.url, 'processed/photo.jpg');
File Management:
// List all files in a directory
const files = await blob.list({ prefix: 'documents/' });
// Delete old files
const oldFiles = files.blobs.filter(f =>
new Date(f.uploadedAt) < new Date('2024-01-01')
);
await blob.del(oldFiles.map(f => f.url));
Environment Variables
All SDKs support configuration via environment variables:
# Required
TEMPS_API_URL=https://your-temps-instance.com
# Authentication (choose one)
TEMPS_API_KEY=your-api-key
# or
TEMPS_TOKEN=your-deployment-token
# Optional (for API keys)
TEMPS_PROJECT_ID=1
Error Handling
All SDKs provide structured error types:
import { KVError, BlobError } from '@temps-sdk/kv';
// or
import { BlobError } from '@temps-sdk/blob';
try {
await kv.set('key', 'value');
} catch (error) {
if (error instanceof KVError) {
console.error('KV Error:', error.message);
console.error('Status:', error.status);
console.error('Code:', error.code);
}
}
TypeScript Support
All SDKs are written in TypeScript and provide full type definitions:
// Full type safety
const user = await kv.get<{ name: string; email: string }>('user:123');
// user is typed as { name: string; email: string } | null
const deployment = await client.deployments.get(deploymentId);
// deployment is fully typed based on API response
Next Steps
- Set Up Analytics to start tracking user behavior
- Configure KV Storage for caching and sessions
- Use Blob Storage for file uploads
- Explore the API for advanced integrations