KapaProvider Context Provider
The KapaProvider
component serves as the foundation for the Kapa SDK,
providing the necessary context for the AI chat functionality throughout your
application. It must wrap any component that needs access to the Kapa AI
features.
Basic usage
import React from "react";
import { KapaProvider } from "@kapaai/react-sdk";
function App() {
return (
<KapaProvider
integrationId="your-integration-id"
callbacks={{
askAI: {
onQuerySubmit: (data) => {
console.log("Question asked:", data.question);
},
},
}}
>
<YourApplication />
</KapaProvider>
);
}
Props
Prop | Type | Required | Default | Description |
---|---|---|---|---|
integrationId | string | Yes | - | Your Kapa integration ID from the dashboard. |
fingerprintingEnabled | boolean | No | false | Enable browser fingerprinting for user tracking. When enabled, the SDK generates anonymized IDs for end users. |
callbacks | Callbacks | Yes | - | Callback functions for tracking user interactions with the SDK. |
botProtectionMechanism | "recaptcha" | "hcaptcha" | No | "recaptcha" | Choose which captcha provider to use for bot protection. |
hasConsentForCaptcha | boolean | No | true | Whether the user has provided consent for captcha. Set to false if you need to obtain consent before enabling captcha. |
apiService | KapaApiService | No | Default API Service | Optional API service implementation for testing or custom networking. You can provide a custom implementation that follows the KapaApiService interface. |
Integration ID
The integrationId
is a unique identifier for your Kapa integration. To find
your integration ID:
- Log in to your Kapa dashboard
- Navigate to the "Integrations" section
- Select or create a widget integration
- Copy the Integration ID from the setup page
<KapaProvider
integrationId="7d04c434-4090-4ebf-aeb3-8e90645a504d" // Your actual integration ID
callbacks={{...}}
>
<YourApplication />
</KapaProvider>
Callbacks
The callbacks
prop allows you to track and respond to user interactions. The
structure is:
interface Callbacks {
askAI?: {
onQuerySubmit?: (data: QuerySubmitPayload) => void;
onAnswerGenerationCompleted?: (
data: AnswerGenerationCompletedPayload,
) => void;
onAnswerGenerationStop?: (data: AnswerGenerationStopPayload) => void;
onConversationReset?: (data: ConversationResetPayload) => void;
onFeedbackSubmit?: (data: FeedbackSubmitPayload) => void;
};
}
Callback events
Event | Triggered when | Payload data |
---|---|---|
onQuerySubmit | User submits a question | Question text, thread ID, conversation history |
onAnswerGenerationCompleted | AI finishes generating an answer | Thread ID, question, answer, conversation history |
onAnswerGenerationStop | User stops answer generation | Thread ID, question, conversation history |
onConversationReset | User resets the conversation | Thread ID, conversation history |
onFeedbackSubmit | User submits feedback | Reaction, comment, conversation details |
User fingerprinting
The fingerprintingEnabled
prop allows you to generate anonymous user
identifiers:
<KapaProvider
integrationId="your-integration-id"
fingerprintingEnabled={true}
callbacks={{...}}
>
<YourApplication />
</KapaProvider>
When enabled:
- The SDK generates a unique visitor ID
- This ID persists across sessions (using localStorage)
- No personal information is collected, only browser characteristics
- This allows tracking conversations for users who aren't logged in
Bot protection
The SDK uses captcha verification to protect against automated bots:
<KapaProvider
integrationId="your-integration-id"
botProtectionMechanism="hcaptcha" // "recaptcha" (default) or "hcaptcha"
hasConsentForCaptcha={true} // Set to false if you need explicit consent
callbacks={{...}}
>
<YourApplication />
</KapaProvider>
If you need to obtain explicit user consent before enabling captcha:
function App() {
const [captchaConsent, setCaptchaConsent] = useState(false);
return (
<>
{!captchaConsent && (
<div className="consent-banner">
<p>We use CAPTCHA to protect our service from bots.</p>
<button onClick={() => setCaptchaConsent(true)}>
Accept
</button>
</div>
)}
<KapaProvider
integrationId="your-integration-id"
hasConsentForCaptcha={captchaConsent}
callbacks={{...}}
>
<YourApplication />
</KapaProvider>
</>
);
}
Custom API service
For testing or special networking requirements, you can provide a custom API service:
import { KapaProvider, DefaultKapaApiService } from '@kapaai/react-sdk';
// Custom proxy URL
const customApiService = new DefaultKapaApiService('https://your-custom-proxy.example.com');
function App() {
return (
<KapaProvider
integrationId="your-integration-id"
callbacks={{...}}
apiService={customApiService}
>
<YourApplication />
</KapaProvider>
);
}
For more complex customization, see the Custom API Services documentation.
User Identification
You can provide user identification by setting the global kapaSettings
object:
// Set this before mounting the KapaProvider
window.kapaSettings = {
user: {
email: 'user@example.com', // Optional: user's email
uniqueClientId: 'user-123', // Optional: your system's user ID
metadata: {
companyName: 'Acme Corp', // Optional: company/org name
firstName: 'Jane', // Optional: user's first name
lastName: 'Doe' // Optional: user's last name
}
}
};
// Then render your provider
<KapaProvider integrationId="your-integration-id" callbacks={{...}}>
<YourApplication />
</KapaProvider>
For dynamic user identification (e.g., after login):
function App() {
const { user } = useAuth(); // Your auth hook
useEffect(() => {
if (user) {
window.kapaSettings = {
user: {
email: user.email,
uniqueClientId: user.id,
metadata: {
companyName: user.organization,
firstName: user.firstName,
lastName: user.lastName
}
}
};
} else {
window.kapaSettings = { user: undefined };
}
}, [user]);
return (
<KapaProvider integrationId="your-integration-id" callbacks={{...}}>
<YourApplication />
</KapaProvider>
);
}
Best practices
- Place the provider as high as needed - but no higher. Only wrap components that need access to the Kapa functionality.
- Initialize user data before mounting - Set
window.kapaSettings
before rendering the provider when possible. - Handle authentication changes - When a user logs in or out, update the user identification accordingly.
- Use meaningful callback names - Name your callback handler functions descriptively for better code readability.
- Consider lazy loading - If the chat functionality isn't needed immediately, consider lazy loading it:
import React, { lazy, Suspense } from 'react';
const ChatWidget = lazy(() => import('./ChatWidget'));
function App() {
const [showChat, setShowChat] = useState(false);
return (
<div>
<button onClick={() => setShowChat(true)}>
Open Chat
</button>
{showChat && (
<Suspense fallback={<div>Loading chat...</div>}>
<KapaProvider integrationId="your-integration-id" callbacks={{...}}>
<ChatWidget />
</KapaProvider>
</Suspense>
)}
</div>
);
}
Error handling
The KapaProvider
handles internal errors, but you should implement UI
feedback for users when errors occur:
function ChatInterface() {
const { error } = useChat();
return (
<div>
{error && (
<div className="error-message">
<p>{error}</p>
<p>Please try again or refresh the page.</p>
</div>
)}
{/* Rest of chat interface */}
</div>
);
}
For more complex error handling, see the Troubleshooting guide.