npm package: @retakeapi/nextjs
Description: Next.js integration for Retake API - Abandoned Cart Recovery
Author: Retake
Latest version: 1.0.0

# @retakeapi/nextjs

Official Next.js integration for **Retake** — Revenue Recovery Infrastructure for SaaS & E-commerce.

[![npm version](https://img.shields.io/npm/v/@retakeapi/nextjs.svg)](https://www.npmjs.com/package/@retakeapi/nextjs)
[![npm downloads](https://img.shields.io/npm/dm/@retakeapi/nextjs.svg)](https://www.npmjs.com/package/@retakeapi/nextjs)
[![license](https://img.shields.io/npm/l/@retakeapi/nextjs.svg)](https://github.com/retakeapi/nextjs/blob/main/LICENSE)

Zero-config React hooks and API handlers. Your API keys stay server-side, always.

## Installation

```bash
npm install @retakeapi/nextjs
# or
pnpm add @retakeapi/nextjs
# or
yarn add @retakeapi/nextjs
```

## Quick Start

### 1. Create API Route

```typescript
// app/api/retake/route.ts
import { createRetakeHandler } from '@retakeapi/nextjs/server';

export const POST = createRetakeHandler(process.env.RETAKE_API_KEY!);
```

### 2. Add Provider

```tsx
// app/layout.tsx
import { RetakeProvider } from '@retakeapi/nextjs/client';

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <RetakeProvider endpoint="/api/retake">
          {children}
        </RetakeProvider>
      </body>
    </html>
  );
}
```

### 3. Track Revenue Intents

#### SaaS Applications

```tsx
"use client";

import { useIntentTracking, useConversionTracking } from '@retakeapi/nextjs/client';

function PricingPage({ user, selectedPlan }) {
  // Automatically tracks pricing page visits
  useIntentTracking({
    type: 'pricing',
    email: user.email,
    value: selectedPlan.price,
    metadata: { plan: selectedPlan.name }
  });

  return <div>...</div>;
}

function CheckoutSuccess({ user, subscription }) {
  const { track } = useConversionTracking();

  useEffect(() => {
    track({
      transactionId: subscription.id,
      value: subscription.amount
    });
  }, []);

  return <div>Thank you!</div>;
}
```

#### E-commerce Applications

```tsx
"use client";

import { useCartTracking, useOrderComplete } from '@retakeapi/nextjs/client';

function Cart({ items, user }) {
  const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);

  // Automatically tracks cart changes with debouncing
  useCartTracking({
    items,
    total,
    customerEmail: user?.email,
    debounceMs: 2000,
    disabled: items.length === 0
  });

  return <div>...</div>;
}

function Checkout({ total }) {
  const { track, isLoading } = useOrderComplete();

  async function handlePurchase() {
    const orderId = await processPayment();
    await track(orderId, total);
    router.push('/thank-you');
  }

  return (
    <button onClick={handlePurchase} disabled={isLoading}>
      Complete Purchase
    </button>
  );
}
```

## Webhook Handler

```typescript
// app/api/webhooks/retake/route.ts
import { createWebhookHandler } from '@retakeapi/nextjs/server';

export const POST = createWebhookHandler(process.env.WEBHOOK_SECRET!, {
  onIntentConverted: async (data) => {
    console.log('Recovered revenue:', data);
  },
  onEmailOpened: async (data) => {
    console.log('Email opened:', data);
  },
  onPaymentRecovered: async (data) => {
    console.log('Payment recovered:', data);
  }
});
```

## API Reference

### Server (`@retakeapi/nextjs/server`)

| Export | Description |
|--------|-------------|
| `createRetakeHandler(apiKey)` | Creates secure API route handler |
| `createWebhookHandler(secret, handlers)` | Creates webhook handler with signature verification |
| `createServerClient(apiKey)` | Creates server-side client for Server Components |

### Client (`@retakeapi/nextjs/client`)

| Export | Description |
|--------|-------------|
| `<RetakeProvider>` | Context provider (wrap your app) |
| `useIntentTracking(options)` | Track any intent with debouncing |
| `useCartTracking(options)` | Track cart changes (e-commerce) |
| `useConversionTracking()` | Returns `{ track, isLoading, error }` |
| `useOrderComplete()` | Track order completion |
| `useRetake()` | Access context directly |
| `useAutoRecovery()` | Auto-restore cart from recovery links |

### `useIntentTracking(options)`

```typescript
interface Options {
  type: 'cart' | 'checkout' | 'pricing' | 'trial_expiring' | 'upgrade' | 'payment_failed' | 'custom';
  value?: number;
  email?: string;
  name?: string;
  metadata?: Record<string, unknown>;
  items?: CartItem[];
  debounceMs?: number;  // Default: 2000
  disabled?: boolean;
}
```

## SaaS Use Cases

### Trial Expiration

```tsx
function TrialBanner({ user, daysRemaining }) {
  useIntentTracking({
    type: 'trial_expiring',
    email: user.email,
    value: 49,
    metadata: { daysRemaining, plan: 'pro' },
    disabled: daysRemaining > 3  // Only track last 3 days
  });

  return <div>Your trial ends in {daysRemaining} days</div>;
}
```

### Upgrade Page

```tsx
function UpgradePage({ user, plans }) {
  const [selectedPlan, setSelectedPlan] = useState(plans[0]);

  useIntentTracking({
    type: 'upgrade',
    email: user.email,
    value: selectedPlan.price,
    metadata: {
      currentPlan: user.plan,
      targetPlan: selectedPlan.name
    }
  });

  return <div>...</div>;
}
```

## Security Architecture

Your API keys **never** reach the browser:

```
┌─────────────┐     ┌─────────────────┐     ┌─────────────┐
│   Browser   │────▶│  /api/retake    │────▶│  Retake API │
│  (React)    │     │  (Your Server)  │     │             │
└─────────────┘     └─────────────────┘     └─────────────┘
                           │
                    API Key stored here
                    (server-side only)
```

- ✅ CORS-safe (requests come from your domain)
- ✅ API key hidden from client
- ✅ Full request validation

## Requirements

- Next.js 13.0+
- React 18.0+
- Node.js 18+

## Links

- [Documentation](https://retakeapi.com/docs)
- [Dashboard](https://retakeapi.com/dashboard)
- [@retakeapi/js](https://www.npmjs.com/package/@retakeapi/js) — Core SDK

## License

MIT © [Retake](https://retakeapi.com)