GrowthRailDocs

Installation

bash
npm install @growth-rail/core
# or
yarn add @growth-rail/core
# or
pnpm add @growth-rail/core
Version: Current stable release is @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.

app.ts
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

OptionTypeDefaultDescription
projectSecretKeystringRequired Your project secret (sk_...).
cookieDomainstring?current domainDomain for tracking cookies. Use .yourapp.com for cross-subdomain attribution.
autoPageTrackboolean?falseAuto-detect referralCode in URL and track referral on page load.
debugboolean?falseEnable 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.

ts
const user = await GrowthRail.initAppUser('user_123');
Return FieldTypeDescription
idstringGrowth Rail's internal user ID (GUID)
uniqueIdstringUnique identifier (e.g. appuser_k8xn2m)
referralCodestring6-character alphanumeric code
referralLinkstringFull shareable URL with referral code
referrerExperienceobjectCampaign UI config (trigger button, modal, theme)

Other User Methods

MethodReturnsDescription
isUserReady()booleanWhether initAppUser() has completed.
ensureUserReady()Promise<AppUserType>Waits until the user is initialized, then returns the user object.
getUserId()string | undefinedReturns the current user's Growth Rail ID, or undefined if not initialized.
getReferralCode()string | undefinedReturns the current user's referral code.
getReferralLink()stringReturns the fully constructed referral link for the current user.
getAttributionToken()string | undefinedReturns 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.

ts
// 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:

ts
// 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)

ts
// 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

ts
// 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();
OptionValuesDescription
positionbottom-right | bottom-left | top-right | top-leftWhich corner of the viewport
displayModefloating | edgefloating: pill/FAB hovering over content. edge: tab pinned to viewport edge.

Cookie Storage

The SDK uses cookies (30-day expiry) for referral attribution:

CookiePurposeLifetime
gr_ref_codeStores the referral code detected from the URL30 days
gr_tracked_referralStores the tracking ID after a referral is recorded30 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

MethodReturnsDescription
GrowthRail.isInitialized()booleanWhether init() has been called.
GrowthRail.isUserReady()booleanWhether 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:

ts
import type {
  GrowthRailOptions,
  AppUserType,
  AppUserTypeWithId,
  ReferralLink,
  TrackReferralResponse,
  ReferrerExperience,
  ReferrerTriggerButton,
  ReferrerModalOptions,
  NewUserExperience,
  TriggerButtonPosition,
  EventPayload,
} from '@growth-rail/core';

Complete Example

app.ts
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:

Initialization status and project validation
User creation and referral code generation
Referral tracking events and cookie storage
API request/response payloads
UI component rendering events