npm package: @keverdjs/fraud-sdk-react
Description: React SDK for Keverd fraud detection and device fingerprinting
Author: Keverd
Latest version: 3.0.0

# @keverdjs/fraud-sdk-react

React SDK for Keverd fraud detection and device fingerprinting. This SDK provides real-time risk assessment by analyzing device characteristics, behavioral biometrics, and session patterns.

## Installation

Install the package via npm or yarn:

```bash
npm install @keverdjs/fraud-sdk-react
```

or

```bash
yarn add @keverdjs/fraud-sdk-react
```

## Quick Start

### 1. Wrap your application with `KeverdProvider`

```tsx
import { KeverdProvider } from '@keverdjs/fraud-sdk-react';

function MyApp({ Component, pageProps }) {
  return (
    <KeverdProvider apiKey="pk_live_your_api_key_here">
      <Component {...pageProps} />
    </KeverdProvider>
  );
}

export default MyApp;
```

### 2. Use `useKeverd` in your components

```tsx
import { useKeverd } from '@keverdjs/fraud-sdk-react';

export default function Home() {
  const { deviceId, riskScore, isLoading } = useKeverd();
  if (isLoading) return <div>Loading...</div>;

  return (
    <div>
      <h1>Device ID: {deviceId}</h1>
      <p>Risk Score: {riskScore}</p>
    </div>
  );
}
```

## API Reference

### KeverdProvider

The provider component that initializes the SDK and makes it available to child components.

**Props:**

```typescript
interface KeverdProviderProps {
  apiKey?: string;
  endpoint?: string;
  debug?: boolean;
  loadOptions?: KeverdLoadOptions; // legacy compatibility
  children: React.ReactNode;
}
```

**KeverdLoadOptions:**

```typescript
interface KeverdLoadOptions {
  apiKey: string;              // Required: Your Keverd API key
  debug?: boolean;             // Optional: Enable debug logging (default: false)
}
```

### useKeverd

High-level hook for quick integrations.

```tsx
const { deviceId, riskScore, isLoading, error, refresh } = useKeverd();
```

### useKeverdVisitorData

Advanced hook to access full visitor and risk payloads.

```tsx
const { 
  data,           // KeverdVisitorData | null
  isLoading,      // boolean
  error,          // KeverdError | null
  getData         // () => Promise<void>
} = useKeverdVisitorData(options?);
```

**Options:**

```typescript
interface KeverdVisitorDataHookOptions {
  extendedResult?: boolean;    // Include extended device/session info (default: false)
  immediate?: boolean;          // Automatically fetch data on mount (default: false)
  ignoreCache?: boolean;        // Ignore cached data (default: false)
}
```

**Return Value:**

```typescript
interface KeverdVisitorDataResult {
  isLoading: boolean;          // Loading state
  error: KeverdError | null;   // Error if any
  data: KeverdVisitorData | null; // Visitor data
  getData: (options?: KeverdVisitorDataOptions) => Promise<KeverdVisitorData>;
}

interface KeverdVisitorData {
  visitorId: string;
  riskScore: number;           // 0-100
  score: number;               // 0.0-1.0
  action: 'allow' | 'soft_challenge' | 'hard_challenge' | 'block';
  reasons: string[];           // Array of risk reasons
  sessionId: string;           // Session identifier
  requestId: string;           // Request identifier
  simSwapEngine?: KeverdSimSwapEngine; // SIM swap detection (null for web)
  confidence?: number;         // Confidence score (if available)
}
```

### useKeverdContext

Hook to access the underlying SDK instance (for advanced usage).

```tsx
import { useKeverdContext } from '@keverdjs/fraud-sdk-react';

const sdk = useKeverdContext();
// Use sdk methods directly
```

## Configuration

### Debug Mode

Enable debug logging for development:

```tsx
<KeverdProvider
  apiKey="your-api-key"
  debug
>
  {children}
</KeverdProvider>
```

## Data Collection

The SDK automatically collects:

- **Device Information**: Screen resolution, timezone, language, user agent
- **Device Fingerprinting**: Canvas, WebGL fingerprints
- **Behavioral Biometrics**: Typing patterns, mouse movements, scroll behavior
- **Session Information**: Session duration, page views, interactions

**Note**: SIM data is not collected for web applications (only for mobile SDKs).

## Error Handling

The SDK provides error information through the `error` property:

```tsx
const { error } = useKeverdVisitorData();

if (error) {
  switch (error.code) {
    case 'NETWORK_ERROR':
      // Handle network issues
      break;
    case 'INVALID_API_KEY':
      // Handle invalid API key
      break;
    case 'SDK_NOT_INITIALIZED':
      // SDK not initialized
      break;
    default:
      // Handle other errors
  }
}
```

## TypeScript Support

The SDK is written in TypeScript and includes full type definitions. All types are exported for use in your code:

```typescript
import type {
  KeverdConfig,
  KeverdLoadOptions,
  KeverdVisitorData,
  KeverdVisitorDataOptions,
  KeverdVisitorDataHookOptions,
  KeverdVisitorDataResult,
  KeverdDeviceInfo,
  KeverdSessionInfo,
  KeverdBehavioralData,
  KeverdError,
} from '@keverdjs/fraud-sdk-react';

## Next.js Integration

The SDK works seamlessly with Next.js. Wrap your app in `_app.tsx`:

```tsx
// pages/_app.tsx
import type { AppProps } from 'next/app';
import { KeverdProvider } from '@keverdjs/fraud-sdk-react';

function MyApp({ Component, pageProps }: AppProps) {
  return (
    <KeverdProvider apiKey={process.env.NEXT_PUBLIC_KEVERD_API_KEY!}>
      <Component {...pageProps} />
    </KeverdProvider>
  );
}

export default MyApp;
```

For Next.js App Router, wrap your root layout:

```tsx
// app/layout.tsx
import { KeverdProvider } from '@keverdjs/fraud-sdk-react';

export default function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  return (
    <html>
      <body>
        <KeverdProvider apiKey={process.env.NEXT_PUBLIC_KEVERD_API_KEY!}>
          {children}
        </KeverdProvider>
      </body>
    </html>
  );
}
```

## Advanced Usage

### Manual Data Collection

You can access the SDK instance directly for manual operations:

```tsx
import { useKeverdContext } from '@keverdjs/fraud-sdk-react';

function MyComponent() {
  const sdk = useKeverdContext();
  
  const handleManualCheck = async () => {
    const result = await sdk.getVisitorData({ extendedResult: true });
    console.log('Risk assessment:', result);
  };

  return <button onClick={handleManualCheck}>Check Risk</button>;
}
```

### Using Collectors Directly

For advanced use cases, you can use collectors directly:

```tsx
import { KeverdDeviceCollector, KeverdBehavioralCollector } from '@keverd/fraud-sdk-react';

const deviceCollector = new KeverdDeviceCollector();
const behavioralCollector = new KeverdBehavioralCollector();

// Start collectors
behavioralCollector.start();

// Collect data manually
const deviceInfo = deviceCollector.collect();
const behavioralData = behavioralCollector.getData();
```

## Browser Support

- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)

## License

MIT

## Support

For issues, questions, or contributions, please visit the [GitHub repository](https://github.com/keverd/keverd-fraud-sdk-web).