JavaScript SDK
Complete reference for the Referral Engine JavaScript SDK.
The JavaScript SDK provides a simple interface for integrating Referral Engine into web applications. It handles link generation, event tracking, and automatic referral code detection.
Installation
npm install @referral-engine/sdkQuick Setup
lib/referral.tstypescript
import { ReferralEngine } from '@referral-engine/sdk'
const referral = new ReferralEngine({
apiKey: 'pk_live_xxxxx',
campaignId: 'camp_xxxxx'
})Configuration Options
interface ReferralEngineConfig {
// Required
apiKey: string // Your public or secret API key
campaignId: string // Campaign to use for link generation
// Optional
baseUrl?: string // API base URL (default: api.referralengine.com)
timeout?: number // Request timeout in ms (default: 10000)
retries?: number // Number of retry attempts (default: 3)
debug?: boolean // Enable debug logging (default: false)
}Methods
createLink()
Generate a unique referral link for a user.
const link = await referral.createLink({
userId: 'user_123', // Required: Your user's ID
metadata: { // Optional: Custom data
plan: 'pro',
source: 'dashboard'
}
})
// Returns:
{
url: 'https://refer.yourapp.com/abc123',
code: 'abc123',
userId: 'user_123',
createdAt: '2024-01-15T10:30:00Z'
}Links are idempotent — calling
createLink multiple times with the same userId returns the existing link rather than creating duplicates.getLink()
Retrieve an existing referral link without creating a new one.
const link = await referral.getLink({
userId: 'user_123'
})
// Returns null if no link exists for this usertrackEvent()
Track a conversion event (signup, purchase, or custom event).
await referral.trackEvent({
type: 'signup', // Event type
userId: 'new_user_456', // The referred user's ID
referralCode: 'abc123', // The referral code used
metadata: { // Optional: Additional data
email: 'user@example.com',
plan: 'starter'
}
})
// For purchases, include amount:
await referral.trackEvent({
type: 'purchase',
userId: 'user_456',
referralCode: 'abc123',
metadata: {
amount: 99.99,
currency: 'USD',
orderId: 'order_789'
}
})Use server-side tracking for purchases
For purchase events, we strongly recommend tracking from your server using your Secret API Key. This prevents users from spoofing events and protects the integrity of your referral program.
getReferralCode()
Extract the referral code from the current URL.
// If URL is https://yourapp.com/?ref=abc123
const code = referral.getReferralCode()
// Returns: 'abc123'
// Optionally specify the parameter name
const code = referral.getReferralCode({ param: 'referral' })
// Would look for ?referral=xxx insteadgetRewards()
Get rewards earned by a user.
const rewards = await referral.getRewards({
userId: 'user_123'
})
// Returns:
{
rewards: [
{
id: 'reward_xyz',
type: 'referrer',
amount: 10,
currency: 'USD',
status: 'pending',
referredUserId: 'user_456',
createdAt: '2024-01-15T10:30:00Z'
}
],
total: 1
}React Integration
For React applications, we provide hooks for easier integration. See the React SDK documentation.
App.tsxtsx
import { useReferral, ReferralProvider } from '@referral-engine/react'
function App() {
return (
<ReferralProvider
apiKey="pk_live_xxxxx"
campaignId="camp_xxxxx"
>
<ShareButton />
</ReferralProvider>
)
}
function ShareButton() {
const { createLink, loading } = useReferral()
const handleShare = async () => {
const link = await createLink({ userId: currentUser.id })
await navigator.share({ url: link.url })
}
return (
<button onClick={handleShare} disabled={loading}>
Share & Earn
</button>
)
}Error Handling
import { ReferralEngineError } from '@referral-engine/sdk'
try {
const link = await referral.createLink({ userId: 'user_123' })
} catch (error) {
if (error instanceof ReferralEngineError) {
console.error('API Error:', error.code, error.message)
// error.code examples:
// 'invalid_api_key' - API key is invalid
// 'campaign_not_found' - Campaign doesn't exist
// 'rate_limited' - Too many requests
// 'validation_error' - Invalid parameters
}
}TypeScript Support
The SDK is written in TypeScript and includes full type definitions. All methods and responses are fully typed.
import type {
ReferralLink,
ReferralEvent,
Reward
} from '@referral-engine/sdk'