Temps SDKs

Official SDKs and libraries to integrate Temps into your applications. Choose the right SDK for your use case—from React analytics to server-side API access.


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

OptionTypeDefaultDescription
basePathstring/api/_tempsBase endpoint path for analytics
disabledbooleanfalseDisable analytics completely
ignoreLocalhostbooleantrueIgnore localhost traffic
domainstringwindow.location.hostnameCustom domain for analytics
autoTrackPageviewsbooleantrueAutomatically track pageviews
autoTrackPageLeavebooleantrueTrack page leave events
pageLeaveEventNamestringpage_leaveCustom event name for page leave
autoTrackSpeedAnalyticsbooleantrueTrack Web Vitals automatically
autoTrackEngagementbooleantrueTrack user engagement with heartbeats
heartbeatIntervalnumber30000Heartbeat interval in milliseconds
inactivityTimeoutnumber30000Inactivity timeout in milliseconds
engagementThresholdnumber10000Engagement threshold in milliseconds
enableSessionRecordingbooleanfalseEnable session recording
sessionRecordingConfigobject{}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>
  );
}

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 null if 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 -1 if 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 Response object.

    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

Was this page helpful?