Skip to content

Example Integrations

This guide shows how to integrate Coherence into your application

Authentication Modes

Coherence supports two primary authentication modes:

  • Direct Integration: Frontend SDK communicates directly with Coherence
  • No Backend Changes: Works with your existing OAuth/OIDC provider
  • Automatic Token Management: SDK handles token refresh and validation
  • Best For: SPAs, serverless apps, rapid prototyping

Backend SDK Mode (Enterprise & Custom Auth)

  • Full Control: Your backend manages all authentication
  • Custom Logic: Add validation, logging, or transformations
  • Legacy Support: Works with any authentication system
  • Best For: Enterprise apps, custom auth

Basic React Integration

Here's a simple React component that integrates Coherence with OAuth authentication:

import { useEffect } from 'react';
import { get_supabase_client } from '@/utils';

export default function CoherenceComponent() {
  const supabase = get_supabase_client();
  const chatAppId = 'YOUR_APP_ID';

  useEffect(() => {
    // Load ChatBridge SDK
    if (!window.Coherence) {
      window.Coherence = { isInitialized: false };
      const script = document.createElement("script");
      script.src = "https://app.withcoherence.com/sdk/coherence-sdk.js";
      script.onload = async function() {
        if (!window.Coherence.isInitialized) {
          try {
            window.Coherence.init({
              modalConfig: {
                showTriggerButton: false
              },
              oauth: {
                enabled: true,
                appId: chatAppId,
                getToken: async () => {
                  const { data: { session } } = await supabase.auth.getSession();
                  return session?.access_token;
                },
              },
            });
            window.Coherence.isInitialized = true;
          }
          catch (error) {
            console.error("Failed to initialize Coherence:", error);
          }
        }
      };
      (document.head || document.body).appendChild(script);
    }
  }, []);

  return null;
}

You would then import and include in your app before using the triggers below.

Three Ways to Trigger Chat

1. Default Floating Trigger (Simplest)

Enable the default floating trigger button in your configuration:

window.Coherence.init({
  modalConfig: {
    showTriggerButton: true // Enable the default floating trigger
  },
  oauth: {
    enabled: true,
    appId: chatAppId,
    getToken: async () => {
      const { data: { session } } = await supabase.auth.getSession();
      return session?.access_token;
    },
  },
});

This automatically shows a floating chat button in the bottom-right corner of your application.

2. Custom Button

Create your own button that opens the chat modal:

// In your component after initializing Coherence
<button 
  onClick={() => window.Coherence?.show()}
  className="my-custom-chat-button"
>
  Chat with AI
</button>

3. Custom Input with sendMessage

Build a custom input that sends messages and opens the modal:

import { useState } from 'react';

function CustomChatInput() {
  const [message, setMessage] = useState('');

  const handleSendMessage = async (e) => {
    e.preventDefault();
    if (message.trim() && window.Coherence) {
      await window.Coherence.sendMessage(message, {
        autoShow: true // This opens the modal
      });
      setMessage('');
    }
  };

  return (
    <form onSubmit={handleSendMessage}>
      <input
        type="text"
        value={message}
        onChange={(e) => setMessage(e.target.value)}
        placeholder="Ask me anything..."
      />
      <button type="submit">Send</button>
    </form>
  );
}

Backend SDK Mode Implementation

For applications using custom authentication or requiring full backend control, use Backend SDK Mode:

Basic Backend SDK Setup

// Initialize in Backend SDK mode
await window.Coherence.init({
  chatEndpoint: '/api/chat', // Your backend chat endpoint
});

Backend on Different Host

When your frontend and backend are on different domains:

// Frontend on https://app.mycompany.com
// Backend on https://api.mycompany.com
await window.Coherence.init({
  chatEndpoint: '/api/chat',
  appBackendUrl: 'https://api.mycompany.com', // Backend host
});

Backend Implementation Required:

You'll need to add a chat endpoint to your backend:

# Example Flask endpoint
@app.route('/api/chat', methods=['GET', 'POST'])
def chat():
    if request.method == 'GET':
        # Return auth token for user
        token = coherence_sdk.get_user_token(user_id=current_user.id)
        return {'token': token}

    if request.method == 'POST':
        # Send message and return response
        data = request.json
        response = coherence_sdk.send_message(
            user_id=current_user.id,
            message=data['message'],
            conversation_id=data.get('conversation_id')
        )
        return response

Custom UI Implementation

For more advanced use cases, you can build your own chat UI using the SDK's headless mode:

// Initialize in headless mode
await window.Coherence.init({
  modalConfig: {
    headless: true // Don't inject any UI
  },
  oauth: {
    enabled: true,
    appId: "your-app-id",
    getToken: async () => getAuthToken()
  }
});

// Access the conversation store
const store = window.Coherence.getInstance().getStore();

// Subscribe to conversation updates
store.subscribe((state) => {
  console.log('Messages:', state.messages);
  // Update your custom UI
});

// Send a message
await store.sendMessage({
  content: [{ type: 'text', text: 'Hello!' }]
});

Questions?

For more complex integrations or questions about customization, please reach out to discuss your specific requirements!

Next Steps

  • Review the Architecture to understand how Coherence works
  • Check the SDK Reference for all available methods
  • Configure your settings in the Coherence dashboard