GrowthRailDocs

Installation

bash
npm install @growth-rail/react @growth-rail/core
# or
yarn add @growth-rail/react @growth-rail/core
# or
pnpm add @growth-rail/react @growth-rail/core
Version: Current stable release is @growth-rail/react@2.1.1. Requires React 18+ and @growth-rail/core as a peer dependency.

GrowthRailProvider

Wrap your application root with GrowthRailProvider. This initializes the SDK and makes all hooks available throughout your component tree.

main.tsx
import { GrowthRailProvider } from '@growth-rail/react';

function App() {
  const { user } = useAuth(); // your auth hook

  return (
    <GrowthRailProvider
      projectSecretKey={import.meta.env.VITE_GROWTH_RAIL_SECRET}
      userId={user?.id}           // optional: auto-calls initAppUser
      debug={import.meta.env.DEV}  // verbose logging in dev
      cookieDomain=".yourapp.com"  // optional: cross-subdomain
      autoPageTrack={true}         // optional: auto-detect referral codes
    >
      <YourApp />
    </GrowthRailProvider>
  );
}

Provider Props

PropTypeRequiredDescription
projectSecretKeystringYesYour project secret (sk_...).
userIdstring?NoIf provided, automatically calls initAppUser(userId) on mount.
debugboolean?NoEnable verbose console logging.
cookieDomainstring?NoDomain for tracking cookies.
autoPageTrackboolean?NoAuto-detect referral codes in the URL.
When to pass userId: If your user is already authenticated when the provider mounts, pass their ID immediately. If they log in later, use the initAppUser() method from the hook instead.

useGrowthRail Hook

The primary hook for interacting with Growth Rail. Available in any component wrapped by GrowthRailProvider.

tsx
import { useGrowthRail } from '@growth-rail/react';

function MyComponent() {
  const {
    initAppUser,
    showReferralDashboard,
    showFloatingButton,
    hideFloatingButton,
    getAttributionToken,
    isLoading,
    error,
  } = useGrowthRail();

  // ...
}

Hook Return Values

PropertyTypeDescription
initAppUser(userId)(id: string) => Promise<AppUserType>Register a user and get their referral code/link.
showReferralDashboard(options?)(opts?) => voidOpen the referral sharing modal/drawer.
showFloatingButton(options)(opts) => voidShow the floating trigger button.
hideFloatingButton()() => voidRemove the floating trigger button.
getAttributionToken()() => string | undefinedGet the opaque token for gr_attribution checkout metadata.
isLoadingbooleanWhether an async operation is in progress.
errorError | nullLast error that occurred, or null.

Usage Examples

Initialize user after login

LoginPage.tsx
import { useGrowthRail } from '@growth-rail/react';

export function LoginPage() {
  const { initAppUser } = useGrowthRail();

  const handleLogin = async (credentials) => {
    const authUser = await loginService.login(credentials);

    // Register with Growth Rail after successful login
    await initAppUser(authUser.id);
  };

  return <LoginForm onSubmit={handleLogin} />;
}

Track a reward event (Server-Side)

Reward tracking is handled server-side (or automatically via Stripe / RevenueCat integrations). Call the backend SDK endpoint when a user completes a qualifying event:

Server-side reward tracking
POST https://api.growthrail.dev/api/v1/sdk/track-reward-event
Header: x-project-secret-key: sk_live_xxx

{
  "newUserId": "user_123",
  "referralTrackingId": "tr_789",
  "eventName": "user_signup"
}

Show referral sharing UI

InvitePage.tsx
import { useGrowthRail } from '@growth-rail/react';

export function InvitePage() {
  const { showReferralDashboard, showFloatingButton } = useGrowthRail();

  return (
    <div>
      <h2>Invite Friends</h2>
      <p>Share your referral link and earn rewards!</p>

      <button onClick={() => showReferralDashboard()}>
        Open Sharing Modal
      </button>

      <button onClick={() => showFloatingButton({ position: 'bottom-right' })}>
        Show Floating Button
      </button>
    </div>
  );
}

Override modal options

tsx
showReferralDashboard({
  title: 'Share & Earn!',
  description: 'Invite friends to get 500 credits each.',
  type: 'drawer',
  theme: {
    primaryColor: '#6366f1',
    tintColor: '#000000',
    backgroundColor: '#ffffff',
  },
});

ReferralDashboard Component

For embedding the referral dashboard directly in your page layout (instead of a modal/drawer overlay), use the ReferralDashboard component:

ReferralsPage.tsx
import { ReferralDashboard } from '@growth-rail/react';

export function ReferralsPage() {
  return (
    <div className="referrals-section">
      <h2>Your Referral Program</h2>
      <ReferralDashboard
        title="Invite Friends"
        appearance={{
          primaryColor: '#6366f1',
          backgroundColor: '#1e1e2e',
        }}
        onLinkCopied={() => toast.success('Referral link copied!')}
      />
    </div>
  );
}
PropTypeDescription
titlestring?Custom title override for the dashboard.
appearanceReferrerModalOptions?Theme options (primaryColor, backgroundColor, etc.).
onLinkCopied() => voidCallback fired when the user copies their referral link.

Complete Example

App.tsx
import { GrowthRailProvider, useGrowthRail } from '@growth-rail/react';

// 1. Wrap your app
function App() {
  return (
    <GrowthRailProvider
      projectSecretKey={import.meta.env.VITE_GROWTH_RAIL_SECRET}
      debug={import.meta.env.DEV}
      autoPageTrack={true}
    >
      <Router>
        <Routes>
          <Route path="/login" element={<LoginPage />} />
          <Route path="/dashboard" element={<Dashboard />} />
          <Route path="/signup-complete" element={<SignupComplete />} />
        </Routes>
      </Router>
    </GrowthRailProvider>
  );
}

// 2. Register users after login
function LoginPage() {
  const { initAppUser } = useGrowthRail();

  const onLogin = async (userId: string) => {
    await initAppUser(userId);
    navigate('/dashboard');
  };

  return <LoginForm onSubmit={onLogin} />;
}

// 3. Show referral UI on dashboard
function Dashboard() {
  const { showReferralDashboard } = useGrowthRail();

  return (
    <div>
      <h1>Dashboard</h1>
      <button onClick={() => showReferralDashboard()}>
        Invite Friends
      </button>
    </div>
  );
}

// 4. Track rewards (Server-Side or Webhook)
// Call POST /api/v1/sdk/track-reward-event from your backend after signup/purchase, or let Stripe/RevenueCat handle attribution automatically.

Error Handling

The hook exposes an error state for catching issues:

tsx
const { error, isLoading, initAppUser } = useGrowthRail();

useEffect(() => {
  if (error) {
    // Show toast, log to error tracker, etc.
  }
}, [error]);