JavaScript / TypeScript SDK
The ScryWatch JavaScript SDK works in Node.js, Deno, Bun, and modern browsers. Zero dependencies. Automatic event batching. Built-in session tracking.
What you’ll need
- A ScryWatch project API key (see API Keys & Settings)
- Node.js 18+ / Deno / Bun, or a browser environment
Step 1: Install the SDK
npm install @scrywatch/sdk
Or with other package managers:
pnpm add @scrywatch/sdk
bun add @scrywatch/sdk
For Deno, import directly:
import { ScryWatch } from 'npm:@scrywatch/sdk';
Step 2: Initialize the client
import { ScryWatch } from '@scrywatch/sdk';
const logger = new ScryWatch({
apiKey: 'sw_your_api_key_here',
service: 'my-api', // optional — tags all events with this service name
environment: 'production', // optional — tags all events with this environment
});
Tip: Create one shared logger instance per service. Pass it around as a module-level singleton or inject it as a dependency.
Step 3: Log events
// Info level
logger.info('User signed in', { userId: '1234', method: 'email' });
// Warning level
logger.warn('Rate limit approaching', { endpoint: '/api/ingest', remaining: 5 });
// Error level
logger.error('Payment failed', { orderId: 'ord_abc', error: err.message });
Each call accepts:
message(string) — the log messagemetadata(object, optional) — any additional fields you want to attach
Step 4: Track sessions
Sessions group events by a shared session ID, letting you trace a user’s journey through your app.
// Start a session for a user
const session = logger.startSession({ userId: '1234' });
// Log events within the session
session.info('Product page viewed', { productId: 'prod_xyz' });
session.info('Added to cart', { productId: 'prod_xyz', quantity: 2 });
session.error('Checkout failed', { reason: 'card_declined' });
// End the session
session.end();
Sessions appear on the Sessions page in the dashboard.
Step 5: Track page navigation (browser)
In browser environments, track navigation events automatically:
// Track a navigation
logger.trackNavigation('/checkout', { referrer: '/cart' });
// Or track manually
logger.info('Page viewed', { path: window.location.pathname });
Step 6: Track API calls
const start = Date.now();
const response = await fetch('/api/data');
const duration = Date.now() - start;
logger.info('API call completed', {
method: 'GET',
path: '/api/data',
status: response.status,
duration_ms: duration,
});
Step 7: Understand batching
The SDK batches events and flushes automatically:
- Every 10 seconds — if there are pending events
- Every 50 events — if the buffer fills up
To force an immediate flush (e.g. before a process exits):
await logger.flush();
Tip: Always call
await logger.flush()at the end of serverless function handlers to ensure all events are sent before the function terminates.
Step 8: Handle errors gracefully
The SDK retries failed requests with exponential backoff. If all retries fail, the SDK logs the error to the console but does not throw — your application continues normally.
You can configure error handling:
const logger = new ScryWatch({
apiKey: 'your_key',
onError: (err) => {
console.error('ScryWatch delivery failed:', err);
},
});
You’re done
You now know how to:
- Install and initialize the SDK
- Log info, warn, and error events with metadata
- Track user sessions
- Understand batching and flush behavior
Related docs
Full SDK reference — all constructor options, methods, session API, and retry configuration.