Skip to main content

Context Variables

Context variables allow you to personalize conversations and make data-driven decisions in your flows.

What are Context Variables?​

Context variables are key-value pairs that persist throughout a conversation session. They can be:

  • Passed on initialization (user info, cart data, page context)
  • Captured during conversation (user inputs, selections)
  • Used for conditional logic in flows (branching, personalization)

Passing Context on Initialization​

The most common way to set context is during SDK initialization:

new ChatBoxSDK({
apiKey: 'YOUR_API_KEY',
context: {
// User information
userId: '12345',
userName: 'John Doe',
userEmail: 'john@example.com',

// Business data
cartTotal: 149.99,
cartItems: 3,
orderStatus: 'pending',

// Page context
pageUrl: window.location.href,
referrer: document.referrer,
pageTitle: document.title
}
});

Dynamic Context Updates​

Update context during the conversation using the setContext method:

const chatbox = new ChatBoxSDK({
apiKey: 'YOUR_API_KEY'
});

// Later, update context
chatbox.setContext({
cartTotal: 199.99,
cartItems: 5
});

Use Cases​

1. Lead Generation​

Capture campaign and source information:

context: {
source: 'landing-page',
campaign: 'summer-2024',
utmSource: new URLSearchParams(window.location.search).get('utm_source'),
utmMedium: new URLSearchParams(window.location.search).get('utm_medium'),
utmCampaign: new URLSearchParams(window.location.search).get('utm_campaign')
}

Flow Builder Usage:

  • Personalize welcome message: "Welcome from {{utmSource}}!"
  • Route based on campaign type
  • Send leads to different CRMs based on source

2. E-commerce Support​

Provide order tracking and support:

context: {
orderId: 'ORD-12345',
orderStatus: 'shipped',
trackingNumber: '1Z999AA10123456784',
estimatedDelivery: '2024-01-15',
orderTotal: 149.99
}

Flow Builder Usage:

  • Auto-answer "Where's my order?" questions
  • Show tracking information directly in chat
  • Offer relevant support based on order status

3. User Segmentation​

Personalize experience based on user type:

context: {
userType: 'premium',
subscriptionTier: 'pro',
accountAge: 365,
lifetimeValue: 2499.99,
lastLoginDate: '2024-01-10'
}

Flow Builder Usage:

  • Show premium features to premium users
  • Offer upgrade paths to free users
  • Provide VIP support to high-value customers

4. Product Recommendations​

Provide personalized product suggestions:

context: {
viewingProduct: 'laptop-pro-15',
productCategory: 'electronics',
priceRange: 'premium',
previousPurchases: ['phone-x', 'tablet-y'],
wishlistItems: 3
}

Flow Builder Usage:

  • Recommend complementary products
  • Show relevant accessories
  • Offer bundle deals

5. Support Ticket Context​

Pre-fill support information:

context: {
ticketId: 'SUPPORT-789',
issueType: 'technical',
priority: 'high',
affectedService: 'api',
errorCode: 'ERR_500'
}

Flow Builder Usage:

  • Auto-populate support forms
  • Route to specialized support teams
  • Provide instant troubleshooting steps

Context in Flow Builder​

Context variables can be used throughout your flows:

Message Personalization​

Use \{\{variableName\}\} syntax in messages:

Hi {{userName}}, your order {{orderId}} is {{orderStatus}}.

Conditional Branching​

Create branches based on context values:

IF {{userType}} equals "premium"
→ Show premium support options
ELSE
→ Show standard support options

API Calls​

Pass context to external APIs:

{
"userId": "{{userId}}",
"orderTotal": "{{cartTotal}}",
"source": "{{utmSource}}"
}

Reserved Variable Names​

Some variable names are reserved by the system:

VariableDescriptionAuto-Set
sessionIdUnique session identifierYes
conversationIdCurrent conversation IDYes
flowIdActive flow IDYes
pageUrlCurrent page URLYes (if not provided)
referrerDocument referrerYes (if not provided)
userAgentBrowser user agentYes
timestampSession start timeYes

Data Types​

Context variables support multiple data types:

context: {
// String
userName: 'John Doe',

// Number
cartTotal: 149.99,
cartItems: 3,

// Boolean
isPremium: true,
hasSubscription: false,

// Array
productIds: ['prod_1', 'prod_2', 'prod_3'],
tags: ['vip', 'returning-customer'],

// Object
address: {
street: '123 Main St',
city: 'San Francisco',
state: 'CA',
zip: '94105'
},

// Date (as ISO string)
lastPurchaseDate: new Date().toISOString()
}

Security Considerations​

Never Pass Sensitive Data

DO NOT pass the following in context variables:

  • Passwords or authentication tokens
  • Credit card information
  • Social security numbers
  • Private medical information
  • API keys or secrets

Why?

  • Context variables may be logged for analytics
  • They're transmitted over the network (even with HTTPS)
  • They may be stored in browser memory
  • Support teams can see conversation history

What's Safe to Pass:

  • User IDs and names
  • Order IDs and status
  • Product information
  • Non-sensitive business data
  • Page context and navigation data

Best Practices​

1. Use Consistent Naming​

// Good - camelCase, descriptive
context: {
userId: '12345',
userName: 'John Doe',
orderTotal: 149.99
}

// Avoid - inconsistent, unclear
context: {
user_id: '12345',
Name: 'John Doe',
total: 149.99
}

2. Validate Data Types​

context: {
userId: String(userId), // Ensure string
cartTotal: parseFloat(cartTotal), // Ensure number
isPremium: Boolean(isPremium) // Ensure boolean
}

3. Limit Context Size​

Keep context under 10KB for best performance:

// Good - concise, relevant data
context: {
userId: '12345',
orderId: 'ORD-789',
orderStatus: 'shipped'
}

// Avoid - excessive, unnecessary data
context: {
userId: '12345',
fullOrderHistory: [...], // Large array
allUserPreferences: {...}, // Large object
completeUserProfile: {...} // Unnecessary detail
}

4. Update Context Dynamically​

const chatbox = new ChatBoxSDK({
apiKey: 'YOUR_API_KEY',
context: {
pageUrl: window.location.href
}
});

// Listen to cart updates
window.addEventListener('cartUpdated', (event) => {
chatbox.setContext({
cartTotal: event.detail.total,
cartItems: event.detail.items
});
});

// Listen to navigation
window.addEventListener('popstate', () => {
chatbox.setContext({
pageUrl: window.location.href
});
});

Debugging Context​

Enable debug mode to see context values:

const chatbox = new ChatBoxSDK({
apiKey: 'YOUR_API_KEY',
debug: true,
context: {
userId: '12345'
}
});

Check browser console for:

[ChatBoxSDK] Context initialized: { userId: '12345', sessionId: 'sess_abc123', ... }
[ChatBoxSDK] Context updated: { cartTotal: 199.99 }

API Reference​

setContext(newContext)​

Update context variables during conversation:

chatbox.setContext({
cartTotal: 199.99,
cartItems: 5
});

getContext()​

Get all current context variables:

const currentContext = chatbox.getContext();
console.log(currentContext);
// { userId: '12345', cartTotal: 199.99, ... }

clearContext()​

Clear all non-system context variables:

chatbox.clearContext();

Next Steps​