Skip to main content

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

PropTypeRequiredDefaultDescription
integrationIdstringYes-Your Kapa integration ID from the dashboard.
fingerprintingEnabledbooleanNofalseEnable browser fingerprinting for user tracking. When enabled, the SDK generates anonymized IDs for end users.
callbacksCallbacksYes-Callback functions for tracking user interactions with the SDK.
botProtectionMechanism"recaptcha" | "hcaptcha"No"recaptcha"Choose which captcha provider to use for bot protection.
hasConsentForCaptchabooleanNotrueWhether the user has provided consent for captcha. Set to false if you need to obtain consent before enabling captcha.
apiServiceKapaApiServiceNoDefault API ServiceOptional 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:

  1. Log in to your Kapa dashboard
  2. Navigate to the "Integrations" section
  3. Select or create a widget integration
  4. 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

EventTriggered whenPayload data
onQuerySubmitUser submits a questionQuestion text, thread ID, conversation history
onAnswerGenerationCompletedAI finishes generating an answerThread ID, question, answer, conversation history
onAnswerGenerationStopUser stops answer generationThread ID, question, conversation history
onConversationResetUser resets the conversationThread ID, conversation history
onFeedbackSubmitUser submits feedbackReaction, 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

  1. Place the provider as high as needed - but no higher. Only wrap components that need access to the Kapa functionality.
  2. Initialize user data before mounting - Set window.kapaSettings before rendering the provider when possible.
  3. Handle authentication changes - When a user logs in or out, update the user identification accordingly.
  4. Use meaningful callback names - Name your callback handler functions descriptively for better code readability.
  5. 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.