contexa-sdk
v1.0.0
Published
Official JavaScript SDK for Contexa - High-performance event tracking, search, and personalized recommendations
Downloads
3
Maintainers
Readme
Contexa SDK
Official JavaScript SDK for Contexa - High-performance event tracking, search, and personalized product recommendations.
Installation
NPM
npm install contexa-sdkYarn
yarn add contexa-sdkCDN (Browser)
<script src="https://api.contexa.co/sdk/contexa-sdk.js"></script>Quick Start
Node.js / ES6
const contexa = require('contexa-sdk');
// Initialize the SDK
contexa.init({
apiKey: 'your-api-key-here',
ingestionUrl: 'https://api.contexa.co', // Optional
apiUrl: 'https://api.contexa.co' // Optional
});
// Track events
contexa.pageView();
contexa.track('button_clicked', { buttonId: 'checkout' });Browser (CDN)
<script src="https://api.contexa.co/sdk/contexa-sdk.js"></script>
<script>
// SDK is automatically available as window.contexa
contexa.init({
apiKey: 'your-api-key-here',
ingestionUrl: 'https://api.contexa.co',
apiUrl: 'https://api.contexa.co'
});
// Track page view
contexa.pageView();
</script>Configuration
contexa.init({
apiKey: 'your-api-key-here', // Required: Your Contexa API key
ingestionUrl: 'https://api.contexa.co', // Optional: Ingestion server URL
apiUrl: 'https://api.contexa.co', // Optional: Main API URL
batchSize: 50, // Optional: Events per batch (default: 50)
flushInterval: 5000 // Optional: Flush interval in ms (default: 5000)
});Features
1. Event Tracking
Track user interactions and custom events with automatic batching and queue management.
Page Views
// Track page view with automatic URL and referrer
contexa.pageView();
// Track with custom properties
contexa.pageView({
category: 'products',
subcategory: 'shoes'
});Custom Events
// Track any custom event
contexa.track('button_clicked', {
buttonId: 'checkout',
buttonText: 'Complete Purchase'
});
// Or use the event alias
contexa.event('form_submitted', {
formId: 'contact-form',
fields: ['name', 'email']
});E-commerce Events
// Track product view
contexa.viewProduct('product-123', 'Running Shoes', {
price: 89.99,
category: 'footwear',
brand: 'Nike'
});
// Track add to cart
contexa.addToCart('product-123', 'Running Shoes', 1, {
price: 89.99,
currency: 'USD'
});
// Track remove from cart
contexa.removeFromCart('product-123', 1);User Identity
// Identify a user
contexa.identify('user-456', {
email: '[email protected]',
name: 'John Doe',
plan: 'premium'
});2. Search
Perform text-based product searches with automatic event tracking.
// Search for products
const results = await contexa.search('running shoes', {
limit: 20,
filters: {
category: 'footwear',
minPrice: 50,
maxPrice: 200
}
});
console.log(results); // Array of matching products3. Recommendations
Get personalized product recommendations based on user behavior.
Personalized Recommendations
// Get recommendations based on visitor's search history
const personalizedProducts = await contexa.getPersonalizedRecommendations();Trending Products
// Get trending products across all users
const trendingProducts = await contexa.getTrendingProducts();Similar Products
// Get products similar to a specific product
const similarProducts = await contexa.getSimilarProducts('product-123');Frequently Bought Together
// Get products frequently bought together
const bundleProducts = await contexa.getFrequentlyBoughtTogether('product-123');Cart-Based Recommendations
// Get recommendations based on tracked cart events
const cartRecs = await contexa.getCartRecommendations();
// Or pass cart items manually
const cartRecs = await contexa.getCartRecommendations([
{ productId: 'product-123', name: 'Running Shoes', quantity: 1 },
{ productId: 'product-456', name: 'Athletic Socks', quantity: 2 }
]);Advanced Usage
Manual Flush
By default, events are automatically flushed every 5 seconds or when the batch size is reached. You can manually trigger a flush:
contexa.flush();Stop Auto-Flush
contexa.stopAutoFlush();Restart Auto-Flush
contexa.startAutoFlush();Complete Example
const contexa = require('contexa-sdk');
// Initialize
contexa.init({
apiKey: 'your-api-key-here',
ingestionUrl: 'https://api.contexa.co',
apiUrl: 'https://api.contexa.co'
});
// Track page view
contexa.pageView();
// Identify user
contexa.identify('user-789', {
email: '[email protected]',
memberSince: '2024-01-15'
});
// Search for products
const searchResults = await contexa.search('wireless headphones');
// Track product view
contexa.viewProduct('product-999', 'Wireless Headphones Pro', {
price: 199.99,
category: 'electronics'
});
// Get personalized recommendations
const recommendations = await contexa.getPersonalizedRecommendations();
console.log('Recommended for you:', recommendations);
// Track add to cart
contexa.addToCart('product-999', 'Wireless Headphones Pro', 1, {
price: 199.99
});
// Get cart recommendations
const cartRecs = await contexa.getCartRecommendations();
console.log('Complete your purchase with:', cartRecs);
// Manually flush events
await contexa.flush();TypeScript Support
The SDK includes TypeScript definitions for better IDE support and type safety.
import * as contexa from 'contexa-sdk';
interface Product {
id: string;
name: string;
price: number;
}
contexa.init({
apiKey: 'your-api-key-here'
});
const results: Product[] = await contexa.search('laptops');Browser Support
- Chrome (latest)
- Firefox (latest)
- Safari (latest)
- Edge (latest)
- Modern mobile browsers
Node.js Support
- Node.js 14.x and above
API Reference
init(config)
Initialize the SDK with your API key and configuration.
Parameters:
config.apiKey(string, required): Your Contexa API keyconfig.ingestionUrl(string, optional): Ingestion server URLconfig.apiUrl(string, optional): Main API URLconfig.batchSize(number, optional): Events per batch (default: 50)config.flushInterval(number, optional): Flush interval in ms (default: 5000)
track(type, properties)
Track a custom event.
Parameters:
type(string): Event typeproperties(object, optional): Event properties
pageView(properties)
Track a page view.
Parameters:
properties(object, optional): Additional properties
identify(userId, traits)
Identify a user.
Parameters:
userId(string): User identifiertraits(object, optional): User traits
search(query, options)
Search for products.
Parameters:
query(string): Search queryoptions(object, optional): Search options
Returns: Promise<Array> - Array of products
getPersonalizedRecommendations()
Get personalized recommendations.
Returns: Promise<Array> - Array of recommended products
getTrendingProducts()
Get trending products.
Returns: Promise<Array> - Array of trending products
getSimilarProducts(productId)
Get similar products.
Parameters:
productId(string): Product identifier
Returns: Promise<Array> - Array of similar products
getFrequentlyBoughtTogether(productId)
Get frequently bought together products.
Parameters:
productId(string): Product identifier
Returns: Promise<Array> - Array of products
getCartRecommendations(cartItems)
Get cart-based recommendations.
Parameters:
cartItems(array, optional): Array of cart items
Returns: Promise<Array> - Array of recommended products
viewProduct(productId, productName, additionalProps)
Track product view.
Parameters:
productId(string): Product identifierproductName(string): Product nameadditionalProps(object, optional): Additional properties
addToCart(productId, productName, quantity, additionalProps)
Track add to cart.
Parameters:
productId(string): Product identifierproductName(string): Product namequantity(number, optional): Quantity (default: 1)additionalProps(object, optional): Additional properties
removeFromCart(productId, quantity, additionalProps)
Track remove from cart.
Parameters:
productId(string): Product identifierquantity(number, optional): Quantity (default: 1)additionalProps(object, optional): Additional properties
flush()
Manually flush queued events.
Returns: Promise<void>
startAutoFlush()
Start automatic event flushing.
stopAutoFlush()
Stop automatic event flushing.
Getting Your API Key
- Sign up at https://contexa.co
- Create a new project
- Copy your API key from the dashboard
- Navigate to Settings > API Keys
Support
- Documentation: https://contexa.co/documentation
- Email: [email protected]
- GitHub Issues: https://github.com/contexa/contexa-sdk/issues
License
MIT License - see LICENSE file for details
