npm package: @referrals/referagent
Description: Official ReferAgent SDK for Next.js - Easy referral campaign tracking and management
Author: ReferAgent
Latest version: 1.0.2

# @referrals/referagent

[![npm version](https://img.shields.io/npm/v/@referrals/referagent.svg)](https://www.npmjs.com/package/@referrals/referagent)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

Official SDK for integrating ReferAgent referral tracking into your Next.js application. Build powerful referral campaigns with just a few lines of code.

## Installation

```bash
npm install @referrals/referagent
# or
pnpm add @referrals/referagent
# or
yarn add @referrals/referagent
```

## Quick Start

### 1. Setup Provider

Wrap your app with the ReferAgentProvider:

```tsx
// app/layout.tsx
import { ReferAgentProvider } from "@referrals/referagent/react"

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <ReferAgentProvider config={{ apiKey: process.env.REFERAGENT_API_KEY! }}>
          {children}
        </ReferAgentProvider>
      </body>
    </html>
  )
}
```

### 2. Use Referral Links

```tsx
import { ReferralLink } from "@referrals/referagent/react"

export default function HomePage() {
  return (
    <ReferralLink campaignId="camp_123" alias="SUMMER2024">
      <button>Share with Friends</button>
    </ReferralLink>
  )
}
```

### 3. Track Conversions

```tsx
import { useReferAgent } from "@referrals/referagent/react"

export default function CheckoutPage() {
  const client = useReferAgent()
  const code = "SUMMER2024" // Get from URL params or cookies

  const handlePurchase = async () => {
    // Your purchase logic...
    
    // Track conversion
    await client.trackConversion({
      code,
      value: 99.99,
      metadata: { plan: "pro" },
    })
  }

  return <button onClick={handlePurchase}>Complete Purchase</button>
}
```

## AI Features

The SDK includes powerful AI-powered features to help optimize your referral campaigns:

### Campaign Suggestions

```tsx
const suggestions = await client.aiGetCampaignSuggestions("domain_123")
// Returns: Array of campaign suggestions with confidence scores
```

### Link Optimization

```tsx
// Optimize new link aliases
const optimizations = await client.aiOptimizeLink("campaign_123")

// Analyze existing link performance
const analysis = await client.aiOptimizeLink("campaign_123", "link_456")
```

### Timing Optimization

```tsx
const timing = await client.aiGetTimingOptimization("campaign_123")
// Returns: Best times to share, optimal duration, seasonal trends
```

### Strategy Recommendations

```tsx
const strategy = await client.aiGetStrategyRecommendations("campaign_123")
// Returns: Insights, recommendations, opportunities, risks, next steps
```

### Performance Prediction

```tsx
const prediction = await client.aiPredictPerformance("campaign_123", 30)
// Returns: Projected clicks, conversions, revenue for next 30 days
```

### Personal Recommendations

```tsx
const recommendations = await client.aiGetPersonalRecommendations()
// Returns: Personalized recommendations based on your account performance
```

## API Reference

### ReferAgent Client

```tsx
import ReferAgent from "@referrals/referagent"

const client = new ReferAgent({
  apiKey: "your-api-key",
  baseUrl: "https://api.referagent.com", // optional
})
```

### Methods

#### Campaign Management
- `campaignsCreate(data)` - Create a new campaign
- `campaignsList()` - List all campaigns
- `campaignsGet(id)` - Get campaign by ID

#### Link Management
- `linksCreate(campaignId, alias?)` - Create a referral link
- `trackClick(options)` - Track a click event
- `trackConversion(options)` - Track a conversion event

#### AI-Powered Features
- `aiGetCampaignSuggestions(domainId)` - Get AI-powered campaign suggestions
- `aiOptimizeLink(campaignId, linkId?)` - Optimize link alias or analyze link performance
- `aiGetTimingOptimization(campaignId)` - Get optimal timing recommendations
- `aiGetStrategyRecommendations(campaignId)` - Get strategic recommendations
- `aiPredictPerformance(campaignId, days?)` - Predict campaign performance
- `aiGetPersonalRecommendations()` - Get personalized recommendations

## React Components & Hooks

### `<ReferralLink>`

Automatically generates and wraps content with a referral link.

```tsx
<ReferralLink campaignId="camp_123" alias="SUMMER2024">
  Share Now
</ReferralLink>
```

### `useReferAgent()`

Access the ReferAgent client instance.

```tsx
const client = useReferAgent()
const link = await client.linksCreate("camp_123")
```

### `useReferralTracking()`

Automatic click tracking hook.

```tsx
const { trackClick } = useReferralTracking({
  code: "SUMMER2024",
  autoTrack: true,
})
```

## TypeScript Support

This package includes TypeScript definitions. No additional `@types` package needed.

## Requirements

- Node.js 18+ 
- React 18+ (for React components)
- Next.js 16+ (recommended, but not required)

## Error Handling

All SDK methods throw errors that you can catch:

```tsx
try {
  const campaign = await client.campaignsCreate({
    name: "My Campaign",
    targetUrl: "https://example.com",
  })
} catch (error) {
  console.error("Failed to create campaign:", error.message)
}
```

## Rate Limiting

The SDK automatically handles rate limiting. If you hit rate limits, the API will return a 429 status code with retry information.

## Contributing

Contributions are welcome! Please read our [contributing guidelines](https://github.com/referagent/referagent-sdk/blob/main/CONTRIBUTING.md) first.

## Support

- 📖 [Documentation](https://referagent.com/docs)
- 💬 [Discord Community](https://discord.gg/referagent)
- 📧 [Email Support](mailto:support@referagent.com)
- 🐛 [Report Issues](https://github.com/referagent/referagent-sdk/issues)

## License

MIT © [ReferAgent](https://referagent.com)