JavaScript SDK
The @growth-rail/core package is a pure TypeScript, framework-agnostic SDK that works in any JavaScript environment — vanilla JS, Node.js, or as the foundation for the React and React Native SDKs.
Installation
npm install @growth-rail/core
# or
yarn add @growth-rail/core
# or
pnpm add @growth-rail/core@growth-rail/core@2.2.1. Requires Node.js 18+.Initialization
Initialize the SDK once at app startup. All subsequent calls use the singleton instance.
import { GrowthRail } from '@growth-rail/core';
GrowthRail.init({
projectSecretKey: process.env.GROWTH_RAIL_SECRET, // required
cookieDomain: '.yourapp.com', // optional: cross-subdomain tracking
autoPageTrack: true, // optional: auto-detect referral codes in URL
debug: true, // optional: verbose console logging
});Configuration Options
| Option | Type | Default | Description |
|---|---|---|---|
projectSecretKey | string | — | Required Your project secret (sk_...). |
cookieDomain | string? | current domain | Domain for tracking cookies. Use .yourapp.com for cross-subdomain attribution. |
autoPageTrack | boolean? | false | Auto-detect referralCode in URL and track referral on page load. |
debug | boolean? | false | Enable verbose console logging. Disable in production. |
User Management
initAppUser(clientProvidedId)
Registers a user with Growth Rail using your internal user ID. Creates the user if they don't exist, generates a unique referral code, and returns the user object with their referral link. It also binds any stored referral attribution token to this user. Use a stable database or auth-provider ID, never an email address.
const user = await GrowthRail.initAppUser('user_123');| Return Field | Type | Description |
|---|---|---|
id | string | Growth Rail's internal user ID (GUID) |
uniqueId | string | Unique identifier (e.g. appuser_k8xn2m) |
referralCode | string | 6-character alphanumeric code |
referralLink | string | Full shareable URL with referral code |
referrerExperience | object | Campaign UI config (trigger button, modal, theme) |
Other User Methods
| Method | Returns | Description |
|---|---|---|
isUserReady() | boolean | Whether initAppUser() has completed. |
ensureUserReady() | Promise<AppUserType> | Waits until the user is initialized, then returns the user object. |
getUserId() | string | undefined | Returns the current user's Growth Rail ID, or undefined if not initialized. |
getReferralCode() | string | undefined | Returns the current user's referral code. |
getReferralLink() | string | Returns the fully constructed referral link for the current user. |
getAttributionToken() | string | undefined | Returns the opaque token to pass as gr_attribution in supported checkout metadata. |
Referral Tracking
trackReferral(referralCode, rewardEventName?)
Tracks a referral when a new user arrives via a referral link. This is called automatically by the SDK when autoPageTrack is enabled and a referralCode is found in the URL. You only need to call this manually if you disable auto-tracking.
// Usually automatic — only call manually if needed
const result = await GrowthRail.trackReferral('ABC123', 'user_signup');Server-Side REST API (`POST /api/v1/sdk/track-reward-event`)
Reward tracking is performed server-side (or automatically via native Stripe & RevenueCat integrations). Send a POST request with your project secret key:
// Call POST /api/v1/sdk/track-reward-event from backend server
const response = await fetch('https://api.growthrail.dev/api/v1/sdk/track-reward-event', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'x-project-secret-key': 'sk_live_xxx'
},
body: JSON.stringify({
newUserId: 'user_123',
referralTrackingId: 'tr_789',
eventName: 'first_purchase',
environment: 'Production'
})
});Built-in UI
The core SDK includes rendered UI components that are injected into the DOM using Shadow DOM for style isolation. These work in any browser environment without framework dependencies.
Referral Dashboard (Modal / Drawer)
// Open with default campaign settings
await GrowthRail.showReferralDashboard();
// Override options at runtime
await GrowthRail.showReferralDashboard({
title: 'Share & Earn!',
description: 'Invite friends to get 500 credits each.',
type: 'drawer', // 'modal' or 'drawer'
theme: {
primaryColor: '#6366f1',
tintColor: '#000000',
backgroundColor: '#ffffff',
},
});The dashboard includes copy-to-clipboard, and social sharing buttons for Twitter, Facebook, LinkedIn, WhatsApp, and Email.
Floating Trigger Button
// Show the floating invite button
GrowthRail.createTriggerButton({
position: 'bottom-right', // 'bottom-right' | 'bottom-left' | 'top-right' | 'top-left'
displayMode: 'floating', // 'floating' | 'edge'
});
// Remove the button
GrowthRail.destroyTriggerButton();| Option | Values | Description |
|---|---|---|
position | bottom-right | bottom-left | top-right | top-left | Which corner of the viewport |
displayMode | floating | edge | floating: pill/FAB hovering over content. edge: tab pinned to viewport edge. |
Cookie Storage
The SDK uses cookies (30-day expiry) for referral attribution:
| Cookie | Purpose | Lifetime |
|---|---|---|
gr_ref_code | Stores the referral code detected from the URL | 30 days |
gr_tracked_referral | Stores the tracking ID after a referral is recorded | 30 days |
Set the cookieDomain option during initialization for cross-subdomain attribution (e.g. .yourapp.com allows tracking across www.yourapp.com and app.yourapp.com).
Utility Methods
| Method | Returns | Description |
|---|---|---|
GrowthRail.isInitialized() | boolean | Whether init() has been called. |
GrowthRail.isUserReady() | boolean | Whether initAppUser() has completed. |
GrowthRail.ensureUserReady() | Promise<AppUserType> | Awaits user initialization, then returns the user. |
TypeScript Types
All types are exported from the package for full type safety:
import type {
GrowthRailOptions,
AppUserType,
AppUserTypeWithId,
ReferralLink,
TrackReferralResponse,
ReferrerExperience,
ReferrerTriggerButton,
ReferrerModalOptions,
NewUserExperience,
TriggerButtonPosition,
EventPayload,
} from '@growth-rail/core';Complete Example
import { GrowthRail } from '@growth-rail/core';
// 1. Initialize the SDK
GrowthRail.init({
projectSecretKey: process.env.GROWTH_RAIL_SECRET!,
autoPageTrack: true,
debug: process.env.NODE_ENV !== 'production',
});
// 2. After user logs in, register them
async function onLogin(userId: string) {
await GrowthRail.initAppUser(userId);
// 3. Show the floating invite button
GrowthRail.createTriggerButton({
position: 'bottom-right',
displayMode: 'floating',
});
}
// 4. Track rewards (Server-side API / Webhook)
// Call POST /api/v1/sdk/track-reward-event from your server, or let Stripe/RevenueCat handle attribution automatically.
// 5. On logout
function onLogout() {
GrowthRail.destroyTriggerButton();
}Debugging
Enable debug: true during initialization to see detailed console logs for every SDK operation: