How to pass CRM customer ID through the Web Messaging SDK startChat() method
What You Will Build
- You will configure a Genesys Cloud Web Chat client to inject a specific CRM customer identifier into the chat session before it connects to an agent.
- You will use the
@genesys-cloud/web-chat-sdkto intercept thestartChatflow and modify theattributespayload. - You will use JavaScript/TypeScript in a standard web browser environment (Node.js is not supported for this SDK as it requires DOM access).
Prerequisites
- Genesys Cloud Organization: An active Genesys Cloud account with Web Chat enabled.
- Web Chat Configuration: A published Web Chat configuration ID (found in Admin > Omnichannel > Messaging > Web Chat > Configurations).
- SDK Version:
@genesys-cloud/web-chat-sdkversion 1.0.0 or later. - Language/Runtime: JavaScript (ES6+) or TypeScript running in a browser environment.
- Dependencies:
@genesys-cloud/web-chat-sdk@genesys-cloud/web-chat-elements(optional, for UI components)
Authentication Setup
The Web Chat SDK does not use standard OAuth2 client credentials flows for the end-user session. Instead, it uses a Web Chat Configuration ID to establish a session with the Genesys Cloud Messaging service. The “authentication” is the validation of the configuration ID against your organization’s domain.
You must obtain your Configuration ID from the Genesys Cloud Admin portal. This ID is a string that uniquely identifies the chat widget settings, including the outbound queue and messaging rules.
Critical Note: Do not expose your Admin API credentials (Client ID/Secret) in the browser. The Web Chat SDK handles its own token exchange via the Configuration ID. You are responsible for passing the user data (CRM ID) securely from your own application logic to the SDK.
Implementation
Step 1: Initialize the Web Chat Client
First, you must import the SDK and create an instance of the client. The client is the primary interface for controlling the chat lifecycle.
import { createClient } from '@genesys-cloud/web-chat-sdk';
// Replace with your actual Configuration ID from Genesys Cloud Admin
const CONFIGURATION_ID = 'your-configuration-id-here';
// Initialize the client
const client = createClient({
configurationId: CONFIGURATION_ID,
});
export default client;
This code sets up the connection to the Genesys Cloud messaging infrastructure. At this stage, no chat session exists. The client is ready to receive commands to start a chat.
Step 2: Prepare the CRM Customer ID Payload
Before calling startChat, you must define the data you want to pass. Genesys Cloud Web Chat supports custom attributes in the startChat method. These attributes are attached to the conversation and are visible to agents and downstream integrations (such as CRM callbacks or Pure Cloud scripts).
The standard way to pass external identifiers is through the attributes object. You should use a reserved or custom namespace to avoid conflicts with internal Genesys Cloud attributes. A common pattern is to use externalId or a custom key like crmCustomerId.
// This function simulates retrieving the customer ID from your CRM system
function getCustomerContext() {
// In a real app, this might come from a Redux store, Context API, or local storage
return {
crmCustomerId: 'CRM-12345-XYZ',
customerEmail: 'john.doe@example.com',
customerTier: 'Gold'
};
}
// Prepare the attributes object for the SDK
const customerData = getCustomerContext();
const chatAttributes = {
// Use a consistent key name that your backend integrations expect
'externalId': customerData.crmCustomerId,
'email': customerData.customerEmail,
'tier': customerData.customerTier
};
Why use attributes?
The startChat method accepts an optional object parameter. This object is merged into the initial message payload sent to the Genesys Cloud messaging service. These attributes become part of the conversation metadata. Agents can see these in the Agent Desktop, and you can query them via the Analytics API later.
Step 3: Execute startChat with Attributes
Now you will call the startChat method on the client instance, passing the attributes object.
async function initiateChatWithCRMId() {
try {
// Ensure the client is initialized
if (!client) {
throw new Error('Web Chat Client not initialized');
}
// Define the attributes to pass
const attributes = {
'externalId': 'CRM-12345-XYZ',
'customField_1': 'Value_A'
};
// Call startChat with the attributes object
// The second argument is the options object, which includes 'attributes'
await client.startChat({
attributes: attributes
});
console.log('Chat started successfully with CRM ID attached.');
} catch (error) {
console.error('Failed to start chat:', error);
// Handle specific errors
if (error.message.includes('configuration')) {
console.error('Invalid Configuration ID. Check your Genesys Cloud Admin settings.');
} else if (error.message.includes('network')) {
console.error('Network error. Check internet connection.');
}
}
}
Key Parameter Explanation:
attributes: An object of key-value pairs. Keys must be strings. Values can be strings, numbers, or booleans. Complex objects (arrays, nested objects) are not guaranteed to be preserved or displayed correctly in all agent views. Keep it flat.
Step 4: Verify the Data in Genesys Cloud
To confirm the data was passed correctly, you do not need to wait for an agent. You can inspect the conversation in real-time using the Genesys Cloud API or by checking the network traffic in your browser’s developer tools.
Browser Network Tab Verification:
- Open your browser’s Developer Tools (F12).
- Go to the Network tab.
- Trigger the
startChatfunction. - Look for a POST request to a URL ending in
/conversations/webchat. - Inspect the Payload or Request Body. You should see your
attributesobject inside the JSON payload.
API Verification (Post-Chat):
After the chat is complete, you can query the conversation details using the Analytics API or the Conversations API.
// This is a separate backend script to verify the data was stored
// Requires Genesys Cloud API Credentials (Client ID, Secret, Environment)
const axios = require('axios');
async function verifyConversationAttributes(conversationId) {
const environment = 'mypurecloud.ie'; // Change to your region
const clientId = 'YOUR_CLIENT_ID';
const clientSecret = 'YOUR_CLIENT_SECRET';
// 1. Get OAuth Token
const tokenResponse = await axios.post(`https://${environment}/oauth/token`, {
grant_type: 'client_credentials',
client_id: clientId,
client_secret: clientSecret
});
const accessToken = tokenResponse.data.access_token;
// 2. Get Conversation Details
// Endpoint: GET /api/v2/conversations/webchat/{conversationId}
const conversationResponse = await axios.get(
`https://${environment}/api/v2/conversations/webchat/${conversationId}`,
{
headers: {
Authorization: `Bearer ${accessToken}`
}
}
);
const conversation = conversationResponse.data;
// The attributes are typically found in the participant details or the conversation metadata
// For Web Chat, check the 'participants' array for the user participant
const userParticipant = conversation.participants.find(p => p.role === 'user');
if (userParticipant && userParticipant.attributes) {
console.log('User Attributes:', userParticipant.attributes);
console.log('CRM ID Found:', userParticipant.attributes.externalId);
} else {
console.log('No attributes found for user participant.');
}
}
Complete Working Example
This is a complete, copy-pasteable React component that demonstrates the full flow. It initializes the SDK, retrieves a mock CRM ID, and starts the chat with the ID attached.
import React, { useEffect, useState } from 'react';
import { createClient } from '@genesys-cloud/web-chat-sdk';
// Configuration
const CONFIGURATION_ID = 'your-configuration-id-here';
const WebChatWithCRM = () => {
const [client, setClient] = useState(null);
const [isChatting, setIsChatting] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
// Initialize the client when the component mounts
const newClient = createClient({
configurationId: CONFIGURATION_ID,
});
setClient(newClient);
// Cleanup on unmount
return () => {
if (newClient) {
newClient.destroy();
}
};
}, []);
const handleStartChat = async () => {
if (!client) {
setError('Client not initialized');
return;
}
setError(null);
setIsChatting(true);
try {
// 1. Retrieve CRM Data (Simulated)
// In production, fetch this from your CRM API or state management
const crmData = {
customerId: 'CRM-98765',
lastName: 'Doe',
priority: 'High'
};
// 2. Prepare Attributes
// Use consistent keys. Avoid special characters in keys.
const attributes = {
crmCustomerId: crmData.customerId,
customerName: crmData.lastName,
customerPriority: crmData.priority
};
// 3. Start Chat with Attributes
await client.startChat({
attributes: attributes
});
console.log('Chat started with CRM ID:', crmData.customerId);
// Optional: Show the chat UI if you are using custom elements
// setIsChatting(false);
} catch (err) {
console.error('Chat start failed:', err);
setError(err.message || 'Unknown error occurred');
setIsChatting(false);
}
};
return (
<div style={{ padding: '20px', fontFamily: 'Arial, sans-serif' }}>
<h2>Web Chat with CRM Integration</h2>
{error && (
<div style={{ color: 'red', marginBottom: '10px' }}>
Error: {error}
</div>
)}
<button
onClick={handleStartChat}
disabled={isChatting || !client}
style={{
padding: '10px 20px',
backgroundColor: isChatting ? '#ccc' : '#0070f3',
color: 'white',
border: 'none',
borderRadius: '4px',
cursor: isChatting ? 'not-allowed' : 'pointer'
}}
>
{isChatting ? 'Starting Chat...' : 'Start Chat with CRM ID'}
</button>
<p>
Click the button to start a chat. The CRM ID <strong>CRM-98765</strong> will be attached to the conversation.
</p>
<details>
<summary>Debug: Check Network Payload</summary>
<p>Open Developer Tools > Network Tab. Look for POST requests to `/conversations/webchat` after clicking the button. Inspect the payload for the `attributes` object.</p>
</details>
</div>
);
};
export default WebChatWithCRM;
Common Errors & Debugging
Error: Invalid Configuration ID
- What causes it: The
configurationIdprovided tocreateClientdoes not exist, is disabled, or does not belong to the Genesys Cloud organization associated with the SDK’s base URL. - How to fix it:
- Log in to Genesys Cloud Admin.
- Navigate to Omnichannel > Messaging > Web Chat > Configurations.
- Ensure the configuration is Published.
- Copy the Configuration ID (not the name).
- Verify that your website’s domain is allowed in the Allowed Origins setting of the Web Chat configuration. If your domain is not listed, the SDK will reject the connection for security reasons.
Error: Attributes not visible to Agent
- What causes it: The attributes were passed correctly in the
startChatcall, but the agent does not see them in the Agent Desktop. - How to fix it:
- Check Agent Desktop Settings: Agents may need to have the “Show Customer Attributes” option enabled in their profile or workspace settings.
- Check Data Privacy Rules: If Genesys Cloud Data Privacy rules are configured to mask certain data, ensure your custom attributes are not accidentally masked.
- Verify Key Names: Ensure you are using the exact key names you defined in the
startChatcall. The Agent Desktop displays these keys as labels. If you usecrmCustomerId, the agent will seecrmCustomerId: CRM-12345.
Error: 429 Too Many Requests
- What causes it: You are attempting to start too many chats in a short period from the same IP address or client ID. Genesys Cloud enforces rate limits on chat initiation.
- How to fix it:
- Implement exponential backoff in your
startChathandler. - Ensure you are not calling
startChatin a loop or on every render cycle in React. UseuseEffectdependencies correctly to prevent re-initialization. - Check if multiple users are sharing the same browser session (e.g., in a testing environment).
- Implement exponential backoff in your
Error: CORS Error
- What causes it: Your website’s domain is not listed in the Allowed Origins for the Web Chat configuration in Genesys Cloud Admin.
- How to fix it:
- Go to Genesys Cloud Admin > Omnichannel > Messaging > Web Chat > Configurations.
- Select your configuration.
- Go to the Security or General tab (depending on version).
- Add your website’s domain (e.g.,
https://www.yourcompany.com) to the Allowed Origins list. - Save and Publish the configuration.