Convrs NPM SDK
Install Convrs as an npm package for type-safe analytics tracking in JavaScript and TypeScript applications. Perfect for React, Next.js, Vue, Angular, and other web frameworks.
Why use the SDK?
- TypeScript support - Full type definitions for autocomplete and type safety
- Tree-shakeable - Only import what you need
- Framework agnostic - Works with React, Vue, Angular, Svelte and vanilla JS
- Automatic tracking - Built-in page view, session, and device tracking
- Offline-ready - Queues events when offline and syncs when back online
Installation
npm install convrs
Check out the official NPM package for more details.
Quick Start
Basic setup
import { initConvrs } from "convrs";
// Initialize the SDK
const convrs = await initConvrs({
websiteId: "dfid_******",
domain: "your_domain.com", // optional, defaults to current hostname
autoCapturePageviews: true, // auto-tracks initial + SPA route changes
});
// That's it - pageviews are tracked automatically.
// Track custom events
convrs.track("signup", { email: "user@example.com" });
// Identify users
convrs.identify("user_123", {
email: "user@example.com",
plan: "pro",
});
React / Next.js example
// lib/analytics.ts
import { initConvrs } from "convrs";
let convrs: any = null;
export async function getAnalytics() {
if (!convrs) {
convrs = await initConvrs({
websiteId: process.env.NEXT_PUBLIC_CONVRS_WEBSITE_ID!,
domain: process.env.NEXT_PUBLIC_CONVRS_DOMAIN,
autoCapturePageviews: true,
});
}
return convrs;
}
Then use it in your app:
// app/page.tsx or components/SignupButton.tsx
import { getAnalytics } from '@/lib/analytics';
export default function SignupButton() {
const handleSignup = async () => {
const analytics = await getAnalytics();
// Track the signup event
analytics.track('signup', {
email: 'user@example.com',
name: 'John Doe',
});
};
return <button onClick={handleSignup}>Sign Up</button>;
}
Automatic page view tracking in Next.js
With autoCapturePageviews: true, the SDK handles page view tracking automatically. It hooks into the History API and captures initial load plus SPA navigations out of the box.
If you need more control, you can pass an options object:
const convrs = await initConvrs({
websiteId: "dfid_******",
autoCapturePageviews: {
trackHashChanges: true, // include hash-route changes (default: false)
captureInitialPageview: true, // fire pageview on init (default: true)
debounceMs: 100, // debounce rapid navigations (default: 100)
},
});
If you prefer manual tracking (for example, to add custom data), disable auto capture and use usePathname:
// app/layout.tsx or pages/_app.tsx
'use client';
import { useEffect } from 'react';
import { usePathname } from 'next/navigation';
import { getAnalytics } from '@/lib/analytics';
export default function RootLayout({ children }) {
const pathname = usePathname();
useEffect(() => {
(async () => {
const analytics = await getAnalytics();
analytics.trackPageview();
})();
}, [pathname]);
return <html><body>{children}</body></html>;
}
Configuration Options
interface ConvrsWebConfig {
websiteId: string; // Required: Your Convrs website ID
domain?: string; // Optional: Domain (defaults to current hostname)
apiUrl?: string; // Optional: Custom API endpoint
debug?: boolean; // Optional: Enable debug logging
flushInterval?: number; // Optional: Flush interval in ms (default: 5000)
maxQueueSize?: number; // Optional: Max queue size before flush (default: 10)
autoCapturePageviews?:
| boolean
| {
enabled?: boolean; // Default true when object is provided
trackHashChanges?: boolean; // Track hash-route changes (default: false)
captureInitialPageview?: boolean; // Fire pageview on init (default: true)
debounceMs?: number; // Debounce rapid navigations (default: 100)
};
allowLocalhost?: boolean; // Allow tracking on localhost (default: false)
allowIframe?: boolean; // Allow tracking inside iframes (default: false)
allowedHostnames?: string[]; // Hostnames for cross-domain tracking
}
Localhost and iframe behavior: By default, the SDK disables tracking on localhost,
file://protocol, and inside iframes. It also detects bots and headless browsers automatically. To enable tracking during local development, setallowLocalhost: true. To enable tracking inside iframes, setallowIframe: true.
API Methods
Track custom events
// Simple event
convrs.track("button_click");
// Event with custom data
convrs.track("purchase", {
amount: 99.99,
currency: "USD",
product: "Premium Plan",
});
Track page views
If you enabled autoCapturePageviews, pageviews are tracked automatically. If you prefer manual control:
// Track current page (sends full URL including query params and UTMs)
convrs.trackPageview();
// Track a specific path
convrs.trackPageview("/custom/path");
Identify users
// Simple identification
convrs.identify("user_123");
// With user properties
convrs.identify("user_123", {
email: "user@example.com",
name: "John Doe",
plan: "premium",
signup_date: "2024-01-15",
});
Flush events manually
By default, events are queued and sent automatically. You can manually flush:
// Force send all queued events immediately
await convrs.flush();
Reset the client
Clear visitor ID and session (useful for logout):
convrs.reset();
Cross-domain tracking (SDK)
If you need to track users across different root domains using the SDK, use the cross-domain helpers:
const convrs = await initConvrs({
websiteId: "dfid_******",
allowedHostnames: ["myapp.io"], // declare your other domains
});
// Get the tracking params to pass to another domain
const params = convrs.getTrackingParams();
// => { _df_vid: 'abc-123', _df_sid: 's456-789' }
// Build a URL with tracking params appended
const url = convrs.buildCrossDomainUrl("https://myapp.io/signup");
// => 'https://myapp.io/signup?_df_vid=abc-123&_df_sid=s456-789'
When the user lands on the other domain (also running the SDK), initConvrs reads the _df_vid and _df_sid params from the URL, restores the visitor and session, and cleans the params from the address bar.
For the script tag approach, see track across domains.
Advanced Usage
Custom storage adapter (web)
import { createConvrsClient, createMemoryStorageAdapter } from "convrs";
// Use in-memory storage (no persistence)
const convrs = await createConvrsClient({
websiteId: "dfid_******",
storage: createMemoryStorageAdapter(),
// ... other config
});
Server-side tracking (Node.js)
import { createConvrsClient } from "@convrs/core";
const convrs = await createConvrsClient({
websiteId: "dfid_******",
domain: "your_domain.com",
// Provide custom storage and network adapters for Node.js
});
Access the singleton client
After initialization, you can access the client anywhere:
import { getConvrsClient } from "convrs";
const convrs = getConvrsClient();
convrs.track("event_name");
Package Structure
convrs - Main SDK for web applications
- Entry point:
convrsorconvrs/web - Includes localStorage and fetch adapters
- Auto-detects device, viewport, referrer
convrs/react-native - React Native / Expo implementation
- Entry point:
convrs/react-native - Uses AsyncStorage, NetInfo, and Expo device/constants under the hood
- Provides mobile-friendly helpers like
trackScreenalongsidetrack,identify, andreset
TypeScript Support
All packages include full TypeScript definitions:
import type { ConvrsClient, ConvrsConfig, TrackEventData } from "convrs";
const config: ConvrsConfig = {
websiteId: "dfid_******",
debug: true,
};
Troubleshooting
Events not showing up?
- Check your
websiteIdis correct - Enable
debug: trueto see console logs - Verify your domain matches your Convrs dashboard settings
- Check network requests in browser DevTools
TypeScript errors?
- Ensure you are using TypeScript 5.0+
- Run
npm install @types/nodeif needed
On this page
- Convrs NPM SDK
- Why use the SDK?
- Installation
- Quick Start
- Basic setup
- React / Next.js example
- Automatic page view tracking in Next.js
- Configuration Options
- API Methods
- Track custom events
- Track page views
- Identify users
- Flush events manually
- Reset the client
- Cross-domain tracking (SDK)
- Advanced Usage
- Custom storage adapter (web)
- Server-side tracking (Node.js)
- Access the singleton client
- Package Structure
- TypeScript Support
- Troubleshooting