React SDK
React hooks and components for seamless integration in React applications
Installation
npm (Recommended)
Install the React SDK using npm, the Node.js package manager. This is the recommended installation method for most React projects.
npm install @keverdjs/fraud-sdk-reactyarn
Alternatively, install using Yarn if you prefer it over npm.
yarn add @keverdjs/fraud-sdk-reactPeer Dependencies
The React SDK requires React 16.8.0 or higher (for hooks support) and React DOM 16.8.0 or higher. These should already be installed in your React project, but if not, install them:
npm install react react-dom
# or
yarn add react react-domNote: The SDK uses React hooks (useState, useEffect, useCallback, useContext) internally, so React 16.8.0+ is required. The SDK is compatible with both class components and function components, but hooks can only be used in function components.
Quick Start
1. Wrap Your App with KeverdProvider
The KeverdProvider component initializes the SDK and provides it to all child components via React Context. Wrap your root component (or the highest component that needs access to the SDK) with KeverdProvider.
Important: The endpoint must use HTTPS. The SDK will throw an error if you provide an HTTP URL. The default API endpoint is https://api.keverd.com.
For Next.js: Place the provider in your _app.tsx or _app.js file. For Create React App or other React setups, place it in your root App.js or index.js.
import { KeverdProvider } from '@keverdjs/fraud-sdk-react';
// Next.js: _app.tsx or _app.js
function MyApp({ Component, pageProps }) {
return (
<KeverdProvider
loadOptions={{
apiKey: process.env.NEXT_PUBLIC_KEVERD_API_KEY, // Use environment variables
endpoint: 'https://api.keverd.com', // Optional: defaults to https://api.keverd.com
debug: process.env.NODE_ENV === 'development', // Enable debug in dev only
}}
>
<Component {...pageProps} />
</KeverdProvider>
);
}
export default MyApp;Context Pattern: The KeverdProvider uses React Context to provide the SDK instance to all child components. This ensures the SDK is initialized once and shared across your entire application.
Initialization: The SDK is initialized automatically when the provider mounts. The initialization is synchronous and non-blocking, but you should wait for the SDK to be ready before making API calls (the useKeverdVisitorData hook handles this automatically).
2. Use the Hook in Your Components
The useKeverdVisitorData hook provides a React-friendly interface for accessing visitor data and risk assessment. The hook manages loading states, error handling, and data fetching automatically.
Performance: Data collection typically completes in under 50ms. The total time (including network request) is typically under 200ms (p99 latency). The hook uses React's state management to prevent unnecessary re-renders.
import { useKeverdVisitorData } from '@keverdjs/fraud-sdk-react';
export default function Home() {
const { isLoading, error, data, getData } = useKeverdVisitorData({
extendedResult: true, // Include extended result data
immediate: true, // Automatically fetch data on mount
});
// Handle loading state
if (isLoading) {
return <div>Loading risk assessment...</div>;
}
// Handle error state
if (error) {
return (
<div>
<p>Error: {error.message}</p>
<button onClick={() => getData({ ignoreCache: true })}>
Retry
</button>
</div>
);
}
// Handle success state
return (
<div>
<button onClick={() => getData({ ignoreCache: true })}>
Reload data
</button>
<p>Visitor ID: {data?.visitorId}</p>
<p>Risk Score: {data?.riskScore}/100</p>
<p>Action: {data?.action}</p>
<p>Reasons: {data?.reasons.join(', ')}</p>
{/* Handle risk score */}
{data && data.riskScore >= 70 && (
<div className="alert alert-warning">
High risk detected. Additional verification required.
</div>
)}
</div>
);
}API Reference
KeverdProvider
React Context Provider component that initializes the Keverd SDK and makes it available to all child components via React Context. This component should wrap your application root or the highest component that needs access to the SDK.
KeverdProvider Props
| Prop | Type | Required | Description |
|---|---|---|---|
| loadOptions | KeverdLoadOptions | Yes | Configuration object for SDK initialization. See KeverdLoadOptions below for details. |
| children | ReactNode | Yes | React children components that will have access to the SDK via context. |
KeverdLoadOptions
| Property | Type | Required | Default | Description |
|---|---|---|---|---|
| apiKey | string | Yes | — | API key for authenticating requests to the Keverd API. Obtain your API key from the API Keys page in the dashboard. Keep your API key secure and never commit it to version control. Use environment variables in production. |
| endpoint | string | No | 'https://api.keverd.com' | Base URL for the fingerprint API endpoint. Must start with "https://" (HTTP is not allowed for security). Only change this if you're using a custom endpoint or testing environment. |
| debug | boolean | No | false | Enable debug logging. When true, the SDK will log debug information to the browser console. Set to true during development and false in production. |
Usage Example
<KeverdProvider
loadOptions={{
apiKey: process.env.NEXT_PUBLIC_KEVERD_API_KEY,
endpoint: 'https://api.keverd.com',
debug: process.env.NODE_ENV === 'development',
}}
>
{children}
</KeverdProvider>Lifecycle: The SDK is initialized when the provider mounts and destroyed when it unmounts. The initialization is synchronous and non-blocking.
Context: The provider uses React Context to share the SDK instance with all child components. Child components can access the SDK using the useKeverdContext hook or the useKeverdVisitorData hook.
useKeverdVisitorData
React hook for accessing visitor data and risk assessment. This hook provides a React-friendly interface that manages loading states, error handling, and data fetching automatically. The hook must be used within a KeverdProvider component.
useKeverdVisitorData(options?: KeverdVisitorDataHookOptions)
Hook that returns visitor data, loading state, error state, and a function to manually fetch data.
Parameters:
options(optional): Hook configuration object- -
extendedResult(boolean, optional): Include extended result data in the response. Default:false - -
immediate(boolean, optional): Automatically fetch data when the component mounts. Default:false - -
ignoreCache(boolean, optional): Ignore cached results and force a fresh API call. Default:false
Returns: KeverdVisitorDataResult object containing:
isLoading(boolean): Whether data is currently being fetched. This istrueduring the initial fetch and whengetDatais called.error(KeverdError | null): Error object if the request failed. This isnullwhen there's no error.data(KeverdVisitorData | null): Visitor data and risk assessment. This isnulluntil data is successfully fetched.getData(function): Function to manually fetch data. Accepts optionalKeverdVisitorDataOptionsparameter. Returns a Promise that resolves toKeverdVisitorData.
Performance: The hook uses React's state management to prevent unnecessary re-renders. Data collection typically completes in under 50ms, and the total time (including network request) is typically under 200ms (p99 latency).
Error Handling: Errors are automatically caught and stored in the error state. The hook will not throw errors, so you can safely use it without try-catch blocks. However, the getData function can throw errors if called manually.
Usage Example
const { isLoading, error, data, getData } = useKeverdVisitorData({
extendedResult: true,
immediate: true,
});
// Manual fetch with options
await getData({ ignoreCache: true });useKeverdContext
Hook to access the Keverd SDK instance directly from React Context. This hook provides direct access to the SDK instance and the ready state, allowing you to call SDK methods directly if needed. The hook must be used within a KeverdProvider component.
useKeverdContext(): KeverdContextValue
Hook that returns the SDK instance and ready state from React Context.
Parameters: None
Returns: KeverdContextValue object containing:
sdk(KeverdSDK): The SDK instance. Use this to call SDK methods directly (e.g.,sdk.getVisitorData()).isReady(boolean): Whether the SDK is initialized and ready to use. This istrueafter the provider has initialized the SDK.
Throws: Throws an error if called outside of a KeverdProvider component.
import { useKeverdContext } from '@keverdjs/fraud-sdk-react';
function MyComponent() {
const { sdk, isReady } = useKeverdContext();
const handleCustomAction = async () => {
if (isReady) {
const data = await sdk.getVisitorData();
// Custom logic with direct SDK access
}
};
return <button onClick={handleCustomAction}>Check Risk</button>;
}KeverdVisitorData
The visitor data object returned by the SDK. This object contains the risk assessment, action recommendation, and session information.
KeverdVisitorData Interface
interface KeverdVisitorData {
visitorId: string; // Unique visitor identifier (UUID)
riskScore: number; // Risk score (0-100, where 100 is highest risk)
score: number; // Risk score as float (0.0-1.0, normalized)
action: 'allow' | 'soft_challenge' | 'hard_challenge' | 'block';
reasons: string[]; // Array of risk reasons
sessionId: string; // Session identifier (UUID)
requestId: string; // Request identifier (UUID, same as sessionId)
simSwapEngine?: { // SIM swap detection results (null for web SDKs)
risk: number;
flags: {
sim_changed?: boolean;
device_changed?: boolean;
behavior_anomaly?: boolean;
time_anomaly?: boolean;
velocity_anomaly?: boolean;
};
};
confidence?: number; // Confidence score (inverse of risk, 0.0-1.0)
}visitorId: Unique visitor identifier in UUID format. This identifier is consistent across sessions for the same device/browser.
riskScore: Risk score as an integer from 0 (lowest risk) to 100 (highest risk). Use this score to make security decisions in your application.
score: Normalized risk score as a float between 0.0 (lowest risk) and 1.0 (highest risk). This is equal to riskScore / 100.
action: Recommended action based on the risk score. Possible values: 'allow', 'soft_challenge', 'hard_challenge', or 'block'.
reasons: Array of strings explaining why the risk score was assigned. Each string describes a specific risk factor.
sessionId: Unique session identifier in UUID format. This identifier is generated client-side and is consistent across requests within the same browser session.
requestId: Unique request identifier in UUID format. This is the same as sessionId and is included for backward compatibility.
simSwapEngine: SIM swap detection data. This field is always null or undefined for web SDKs, as SIM card information is only available on mobile devices.
confidence: Confidence score as a float between 0.0 and 1.0. This is the inverse of the risk score (confidence = 1.0 - score). Higher values indicate higher confidence in the assessment.
Data Collection
The React SDK collects the same types of data as the Vanilla JavaScript SDK: device information, session information, and behavioral data. All sensitive identifiers are hashed client-side before transmission to ensure privacy and compliance with data protection regulations. No personally identifiable information (PII) is collected or transmitted in plain text.
Device Information
Collected automatically by the SDK. Includes device fingerprint, screen dimensions, timezone, locale, and hardware information. All sensitive data is hashed using SHA-256 before transmission.
Session Information
Tracks session and installation data. Session data is persisted in localStorage and is consistent across page reloads within the same browser session.
Behavioral Data
Collected passively as users interact with your application. The collector tracks mouse movements, keyboard input, touch gestures, and scroll events. Data collection starts automatically when the SDK is initialized and stops when the provider unmounts.
Privacy: Behavioral data is aggregated and anonymized. Individual keystrokes or mouse movements are not transmitted; only statistical summaries are sent to the API.
Hashing and Privacy
All sensitive identifiers are hashed using SHA-256 before transmission. The SDK handles all hashing operations internally. This approach ensures compliance with GDPR, CCPA, and other data protection regulations.
Complete Example
Here's a complete example showing how to integrate the React SDK into a Next.js application. This example demonstrates provider setup, hook usage, risk assessment, and error handling.
import { KeverdProvider, useKeverdVisitorData } from '@keverdjs/fraud-sdk-react';
// App.tsx or _app.tsx
function App() {
return (
<KeverdProvider
loadOptions={{
apiKey: 'your-api-key-here',
endpoint: 'https://api.keverd.com',
debug: false,
}}
>
<HomePage />
</KeverdProvider>
);
}
// HomePage.tsx
function HomePage() {
const { isLoading, error, data, getData } = useKeverdVisitorData({
extendedResult: true,
immediate: true,
});
const handleRiskCheck = async () => {
try {
await getData({ ignoreCache: true });
} catch (err) {
console.error('Failed to get visitor data:', err);
}
};
if (isLoading) {
return <div>Loading risk assessment...</div>;
}
if (error) {
return (
<div>
<p>Error: {error.message}</p>
<button onClick={handleRiskCheck}>Retry</button>
</div>
);
}
if (!data) {
return <button onClick={handleRiskCheck}>Check Risk</button>;
}
// Handle risk score
const getRiskLevel = () => {
if (data.riskScore >= 70) return 'high';
if (data.riskScore >= 30) return 'medium';
return 'low';
};
return (
<div>
<h1>Risk Assessment</h1>
<div>
<p>Risk Score: {data.riskScore}/100</p>
<p>Action: {data.action}</p>
<p>Reasons: {data.reasons.join(', ')}</p>
<p>Risk Level: {getRiskLevel()}</p>
</div>
<button onClick={handleRiskCheck}>Refresh</button>
</div>
);
}Error Handling
The React SDK handles errors gracefully and provides them through the error state in the useKeverdVisitorData hook. Here's how to handle different error scenarios:
Network Errors
Network errors occur when the device cannot connect to the API or when the request times out. The SDK uses 30-second timeouts for connection, read, and write operations.
const { isLoading, error, data, getData } = useKeverdVisitorData({
immediate: true,
});
useEffect(() => {
if (error) {
if (error.message.includes('timeout') || error.message.includes('Timeout')) {
// Handle timeout - retry with exponential backoff
console.warn('Request timed out, retrying...');
setTimeout(() => getData({ ignoreCache: true }), 1000);
} else if (error.message.includes('network') || error.message.includes('Network')) {
// Handle network connectivity issues
console.error('Network error:', error.message);
showNetworkError();
}
}
}, [error, getData]);API Errors
API errors occur when the server returns an error status code (4xx or 5xx). Common causes include invalid API keys, rate limiting, or server errors.
useEffect(() => {
if (error) {
if (error.message.includes('401') || error.message.includes('Unauthorized')) {
// Invalid API key
console.error('Invalid API key. Please check your configuration.');
showConfigurationError();
} else if (error.message.includes('429') || error.message.includes('rate limit')) {
// Rate limit exceeded
console.warn('Rate limit exceeded. Please retry after some time.');
showRateLimitError();
} else if (error.message.includes('500') || error.message.includes('502') || error.message.includes('503')) {
// Server errors - retry with backoff
console.error('Server error:', error.message);
retryWithBackoff();
} else {
// Other API errors
console.error('API error:', error.message);
handleApiError(error);
}
}
}, [error]);SDK Not Ready Errors
These errors occur when you try to use the SDK before it's initialized or when the provider hasn't mounted yet.
const { isLoading, error, data, getData } = useKeverdVisitorData({
immediate: true,
});
useEffect(() => {
if (error && error.code === 'SDK_NOT_READY') {
// SDK not initialized - wait a bit and retry
console.warn('SDK not ready, retrying...');
setTimeout(() => getData({ ignoreCache: true }), 100);
}
}, [error, getData]);Best Practices for Error Handling
- Use useEffect to monitor errors: Set up a
useEffecthook to monitor theerrorstate and handle errors appropriately. - Implement retry logic: For transient errors (network timeouts, server errors), implement retry logic with exponential backoff.
- Fail gracefully: Decide on a fail-open or fail-closed strategy. Fail-open allows access when the SDK fails, while fail-closed blocks access. Choose based on your security requirements.
- Log errors: Log errors to your error tracking service (e.g., Sentry, LogRocket) for debugging and monitoring.
- User feedback: Provide clear feedback to users when errors occur, especially for authentication or security-related failures.
Best Practices
Follow these best practices to ensure optimal performance, security, and user experience when integrating the React SDK:
Provider Setup
- Place provider high in component tree: Place the
KeverdProvideras high as possible in your component tree (ideally at the root level) to ensure all components have access to the SDK. - Use environment variables: Store your API key in environment variables and never commit it to version control. Use different API keys for development, staging, and production environments.
- Enable debug in development only: Set
debug: trueonly in development environments. Disable it in production to avoid exposing sensitive information in the console.
Hook Usage
- Use immediate option wisely: Set
immediate: trueonly when you need data immediately on component mount. For on-demand fetching, useimmediate: falseand callgetData()manually. - Avoid excessive calls: Don't call
getData()on every render or user interaction. Use it strategically for high-value or high-risk operations. - Handle loading and error states: Always handle the
isLoadinganderrorstates in your components to provide good user experience.
Security
- Protect your API key: Never expose your API key in client-side code that can be viewed in the browser. Use environment variables or a secure configuration management system.
- Use HTTPS: Always use HTTPS endpoints. The SDK will not work with HTTP endpoints for security reasons.
- Validate risk scores: Don't blindly trust risk scores. Use them as one factor in your security decision-making process, along with other signals.
- Monitor for anomalies: Set up monitoring and alerting for unusual patterns in risk scores or error rates.
Performance
- Non-blocking: The SDK is designed to be non-blocking. Data collection and API calls happen asynchronously and won't block your UI.
- Minimal impact: Behavioral data collection is passive and has minimal impact on page performance. The SDK uses efficient event listeners that are automatically cleaned up.
- Bundle size: The SDK is lightweight and has a small bundle size. It won't significantly impact your application's load time.
Privacy and Compliance
- GDPR compliance: The SDK is designed to be GDPR-compliant. All sensitive data is hashed client-side, and no PII is collected or transmitted.
- User consent: Consider obtaining user consent before initializing the SDK, especially in regions with strict privacy regulations.
- Privacy policy: Update your privacy policy to inform users about data collection and how it's used for fraud detection.
Risk Score Interpretation
| Score Range | Action | Meaning |
|---|---|---|
| 0-29 | allow | Low risk, proceed with login |
| 30-69 | soft_challenge or hard_challenge | Moderate risk, require MFA |
| 70-100 | block | High risk, deny access |
Features
React Hooks
Easy-to-use hooks for React components
Provider Pattern
Centralized configuration with context
TypeScript Support
Full type definitions included
Next.js Compatible
Works seamlessly with Next.js
Requirements
- React 16.8.0 or higher
- React DOM 16.8.0 or higher
- Modern browser with ES2020 support