Skip to main content

JavaScript SDK Overview

The Cimigo Collect JavaScript SDK provides a simple, powerful way to integrate surveys into any web application. Built with TypeScript and supporting all major frameworks, it offers flexible display modes, comprehensive event handling, and seamless customization options.

๐ŸŽฏ Key Featuresโ€‹

  • ๐ŸŒ Framework Agnostic - Works with React, Vue, Angular, and vanilla JS
  • ๐Ÿ“ฑ Responsive Design - Mobile-optimized survey rendering
  • ๐ŸŽจ Theme Customization - Brand colors, logos, and styling
  • โšก Multiple Display Modes - Widget (modal), iframe, and inline embedding
  • ๐Ÿ”” Event-Driven - Real-time response handling and callbacks
  • ๐Ÿ”’ Secure - JWT authentication and HTTPS-only communication
  • ๐Ÿ“Š Analytics Ready - Built-in event tracking for analytics integration
  • ๐ŸŒ Multi-language - Automatic locale detection and custom language support

๐Ÿš€ Quick Startโ€‹

Installationโ€‹

# Using npm
npm install @cimigo/collect-sdk

# Using yarn
yarn add @cimigo/collect-sdk

# Using CDN (vanilla JS)
<script src="https://cdn.cimigo.com/collect-sdk/latest/cimigo-collect.min.js"></script>

Basic Usageโ€‹

import { CimigoCollect } from '@cimigo/collect-sdk';

// Initialize the SDK
const collect = new CimigoCollect({
apiBaseUrl: 'https://collect-api.cimigo.online',
tenantId: 'your-tenant-id'
});

// Show a survey
await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'widget',
theme: {
primaryColor: '#1976d2',
logoUrl: 'https://your-company.com/logo.png'
},
onComplete: (response) => {
console.log('Survey completed!', response);
}
});

๐ŸŽ›๏ธ Display Modesโ€‹

Widget Mode (Modal)โ€‹

Perfect for non-intrusive survey collection that overlays your existing content.

await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'widget',
theme: {
primaryColor: '#2196f3'
},
onComplete: (response) => {
console.log('Survey completed:', response);
},
onClose: () => {
console.log('Survey closed without completion');
}
});

Features:

  • โœ… Modal overlay with backdrop blur
  • โœ… Responsive sizing for all devices
  • โœ… Escape key and click-outside to close
  • โœ… Smooth animations and transitions
  • โœ… Z-index management for proper layering

Iframe Modeโ€‹

Ideal for embedding surveys in specific sections of your page with isolation.

await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'iframe',
container: '#survey-iframe-container',
height: '600px',
width: '100%',
theme: {
primaryColor: '#4caf50'
}
});

Features:

  • โœ… Complete content isolation
  • โœ… Customizable dimensions
  • โœ… Cross-origin communication
  • โœ… Automatic height adjustment
  • โœ… Security sandbox options

Inline Modeโ€‹

Best for seamless integration where surveys feel like part of your application.

await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'inline',
container: '#survey-container',
theme: {
primaryColor: '#ff9800',
backgroundColor: '#fafafa'
}
});

Features:

  • โœ… Direct DOM integration
  • โœ… Inherits parent page styling
  • โœ… No iframe boundaries
  • โœ… Native scroll behavior
  • โœ… Accessibility compliance

๐ŸŽจ Theme Customizationโ€‹

Basic Theme Configurationโ€‹

const theme = {
// Brand colors
primaryColor: '#1976d2',
secondaryColor: '#dc004e',
backgroundColor: '#ffffff',
textColor: '#333333',

// Typography
fontFamily: '"Roboto", "Helvetica", "Arial", sans-serif',
fontSize: '16px',

// Branding
logoUrl: 'https://your-company.com/logo.png',
logoHeight: '40px',

// Layout
borderRadius: '8px',
spacing: 'normal', // 'compact', 'normal', 'spacious'

// Advanced styling
customCSS: `
.survey-container {
box-shadow: 0 4px 20px rgba(0,0,0,0.1);
}
.question-title {
font-weight: 600;
}
`
};

await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'widget',
theme: theme
});

Dark Mode Supportโ€‹

const darkTheme = {
primaryColor: '#90caf9',
backgroundColor: '#121212',
textColor: '#ffffff',
secondaryColor: '#f48fb1',
borderColor: '#333333',
inputBackground: '#1e1e1e',
customCSS: `
.survey-container {
background: linear-gradient(135deg, #1e1e1e 0%, #2d2d2d 100%);
}
`
};

Brand-Specific Themesโ€‹

// Corporate theme
const corporateTheme = {
primaryColor: '#003f7f',
secondaryColor: '#00a0d2',
fontFamily: '"Arial", sans-serif',
spacing: 'compact',
logoUrl: 'https://corporate.com/logo.png'
};

// Playful theme
const playfulTheme = {
primaryColor: '#ff6b6b',
secondaryColor: '#4ecdc4',
backgroundColor: '#fff5f5',
borderRadius: '16px',
fontFamily: '"Poppins", sans-serif',
customCSS: `
.survey-button {
background: linear-gradient(45deg, #ff6b6b, #ffa726);
transform: scale(1.02);
}
`
};

๐Ÿ”” Event Handlingโ€‹

The SDK provides comprehensive event handling for tracking user interactions and survey lifecycle.

Survey Lifecycle Eventsโ€‹

// Initialize with global event listeners
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',
onSurveyLoaded: (event) => {
console.log('Survey loaded:', event.surveyId);
analytics.track('Survey Loaded', {
surveyId: event.surveyId,
loadTime: event.loadTime
});
},
onSurveyStarted: (event) => {
console.log('Survey started:', event.surveyId);
analytics.track('Survey Started', {
surveyId: event.surveyId,
timestamp: event.timestamp
});
},
onSurveyCompleted: (event) => {
console.log('Survey completed:', event);
analytics.track('Survey Completed', {
surveyId: event.surveyId,
responseId: event.responseId,
completionTime: event.completionTime,
questionCount: event.questionCount
});
}
});

// Add event listeners after initialization
collect.on('response.submitted', (event) => {
console.log('Response submitted:', event.data);

// Send to your CRM or analytics platform
sendToCRM(event.data);
});

collect.on('survey.page_changed', (event) => {
console.log(`Page changed: ${event.currentPage}/${event.totalPages}`);

// Track progress
analytics.track('Survey Progress', {
surveyId: event.surveyId,
currentPage: event.currentPage,
totalPages: event.totalPages,
progress: event.progress
});
});

collect.on('survey.closed', (event) => {
console.log('Survey closed:', event.reason);

// Track abandonment
if (event.reason === 'user_closed') {
analytics.track('Survey Abandoned', {
surveyId: event.surveyId,
currentQuestion: event.currentQuestion,
progress: event.progress
});
}
});

Response Processing Eventsโ€‹

// Real-time response processing
collect.on('question.answered', (event) => {
console.log('Question answered:', event);

// Real-time validation or processing
if (event.questionType === 'nps' && event.value <= 6) {
// Trigger follow-up action for detractors
showDetractorFollowUp(event.value);
}
});

collect.on('validation.error', (event) => {
console.log('Validation error:', event);

// Custom error handling
showCustomErrorMessage(event.errors);
});

// Batch response updates
collect.on('responses.batch_update', (event) => {
console.log('Multiple responses updated:', event.responses);

// Sync with external systems
syncWithExternalSystem(event.responses);
});

๐ŸŒ Internationalizationโ€‹

Automatic Language Detectionโ€‹

// The SDK automatically detects browser language
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',
autoDetectLanguage: true, // Default: true
fallbackLanguage: 'en' // Default fallback
});

// Current detected language
console.log('Detected language:', collect.getCurrentLanguage());

Custom Language Configurationโ€‹

// Set specific language
await collect.showSurvey({
linkId: 'survey-link-id',
locale: 'es', // Spanish
mode: 'widget'
});

// Dynamic language switching
await collect.setLanguage('fr'); // Switch to French

// Get available languages for a survey
const languages = await collect.getSurveyLanguages('survey-link-id');
console.log('Available languages:', languages); // ['en', 'es', 'fr']

Language-Specific Themesโ€‹

const themes = {
'en': {
primaryColor: '#1976d2',
fontFamily: '"Roboto", sans-serif'
},
'ar': {
primaryColor: '#1976d2',
fontFamily: '"Cairo", sans-serif',
direction: 'rtl', // Right-to-left support
customCSS: `
.survey-container {
text-align: right;
}
`
},
'zh': {
primaryColor: '#d32f2f',
fontFamily: '"Noto Sans SC", sans-serif',
fontSize: '14px'
}
};

// Apply language-specific theme
const currentLanguage = collect.getCurrentLanguage();
await collect.showSurvey({
linkId: 'survey-link-id',
theme: themes[currentLanguage] || themes['en']
});

๐Ÿ”ง Advanced Configurationโ€‹

SDK Initialization Optionsโ€‹

const collect = new CimigoCollect({
// Required
tenantId: 'your-tenant-id',

// API Configuration
apiBaseUrl: 'https://collect-api.cimigo.online',
apiVersion: 'v1',
timeout: 30000, // 30 seconds

// Authentication (optional)
apiKey: 'your-api-key',
userId: 'current-user-id',

// Behavior
autoDetectLanguage: true,
fallbackLanguage: 'en',
retryAttempts: 3,
retryDelay: 1000,

// Caching
enableCaching: true,
cacheTimeout: 300000, // 5 minutes

// Development
debug: process.env.NODE_ENV === 'development',
logLevel: 'info', // 'debug', 'info', 'warn', 'error'

// Global event handlers
onError: (error) => {
console.error('SDK Error:', error);
errorReporting.capture(error);
},
onSurveyLoaded: (event) => {
console.log('Survey loaded:', event);
},
onSurveyCompleted: (event) => {
console.log('Survey completed:', event);
}
});

Survey Display Optionsโ€‹

await collect.showSurvey({
// Required
linkId: 'survey-link-id',

// Display configuration
mode: 'widget', // 'widget', 'iframe', 'inline'
container: '#survey-container', // Required for iframe/inline

// Dimensions (iframe mode)
width: '100%',
height: '600px',
minHeight: '400px',
maxHeight: '800px',

// Behavior
closeOnComplete: true,
closeOnOutsideClick: true,
showCloseButton: true,
preventBackgroundScroll: true, // Widget mode

// Personalization
personalization: {
user_id: 'user123',
user_name: 'John Doe',
company: 'Acme Corp',
custom_field: 'custom_value'
},

// Theme and styling
theme: {
primaryColor: '#1976d2',
logoUrl: 'https://company.com/logo.png'
},

// Language
locale: 'en',

// Advanced options
allowMultipleResponses: false,
saveProgress: true,
validateOnSubmit: true,

// Event handlers
onLoad: (survey) => {
console.log('Survey loaded:', survey);
},
onStart: (event) => {
console.log('Survey started:', event);
},
onComplete: (response) => {
console.log('Survey completed:', response);
// Handle completion
},
onClose: (reason) => {
console.log('Survey closed:', reason);
},
onError: (error) => {
console.error('Survey error:', error);
},
onProgress: (progress) => {
console.log('Survey progress:', progress);
}
});

๐Ÿ“Š Analytics Integrationโ€‹

Google Analytics 4โ€‹

// Initialize SDK with GA4 integration
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',
analytics: {
provider: 'ga4',
trackingId: 'G-XXXXXXXXXX',
enabled: true
}
});

// Custom event tracking
collect.on('survey.started', (event) => {
gtag('event', 'survey_started', {
survey_id: event.surveyId,
survey_title: event.surveyTitle,
custom_parameter: 'value'
});
});

collect.on('survey.completed', (event) => {
gtag('event', 'survey_completed', {
survey_id: event.surveyId,
completion_time: event.completionTime,
question_count: event.questionCount,
value: 1
});
});

Adobe Analyticsโ€‹

// Adobe Analytics integration
collect.on('response.submitted', (event) => {
s.tl(true, 'o', 'Survey Response Submitted', {
'prop1': event.surveyId,
'eVar1': event.responseId,
'event1': 'survey_response'
});
});

Custom Analytics Platformโ€‹

// Custom analytics integration
class CustomAnalytics {
track(event, properties) {
// Send to your analytics platform
fetch('/analytics/track', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ event, properties })
});
}
}

const analytics = new CustomAnalytics();

collect.on('survey.started', (event) => {
analytics.track('Survey Started', {
surveyId: event.surveyId,
timestamp: event.timestamp,
userAgent: navigator.userAgent
});
});

๐Ÿ”’ Security Featuresโ€‹

Authenticationโ€‹

// JWT token authentication
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',
apiKey: 'your-api-key',

// User context for personalization
userContext: {
userId: 'user123',
roles: ['customer', 'premium'],
permissions: ['survey:complete']
}
});

// Dynamic token refresh
collect.setAuthToken('new-jwt-token');

Data Privacyโ€‹

// Privacy-compliant configuration
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',

privacy: {
// GDPR compliance
gdprCompliant: true,
consentRequired: true,
anonymizeData: true,

// Data retention
retentionPeriod: 365, // days
autoDelete: true,

// Cookie settings
cookieConsent: true,
cookieDomain: '.your-domain.com'
}
});

// Handle consent
collect.on('consent.required', () => {
showConsentDialog((granted) => {
collect.setConsent(granted);
});
});

Content Security Policy (CSP)โ€‹

<!-- CSP headers for secure integration -->
<meta http-equiv="Content-Security-Policy"
content="
default-src 'self';
script-src 'self' https://cdn.cimigo.com;
connect-src 'self' https://collect-api.cimigo.online;
frame-src https://collect.cimigo.online;
img-src 'self' data: https:;
style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
font-src 'self' https://fonts.gstatic.com;
">

๐Ÿš€ Performance Optimizationโ€‹

Lazy Loadingโ€‹

// Lazy load SDK when needed
async function showSurveyWhenNeeded() {
// Dynamically import SDK
const { CimigoCollect } = await import('@cimigo/collect-sdk');

const collect = new CimigoCollect({
tenantId: 'your-tenant-id'
});

await collect.showSurvey({
linkId: 'survey-link-id',
mode: 'widget'
});
}

// Trigger on user interaction
document.getElementById('feedback-button').addEventListener('click', showSurveyWhenNeeded);

Caching and Preloadingโ€‹

const collect = new CimigoCollect({
tenantId: 'your-tenant-id',

// Enable caching
enableCaching: true,
cacheTimeout: 300000, // 5 minutes

// Preload surveys
preloadSurveys: ['survey-1', 'survey-2'],
});

// Manual preloading
await collect.preloadSurvey('survey-link-id');

// Cache management
collect.clearCache();
collect.getCacheSize();

Bundle Size Optimizationโ€‹

// Import only what you need
import { CimigoCollect } from '@cimigo/collect-sdk/core';
import { WidgetRenderer } from '@cimigo/collect-sdk/renderers/widget';
import { BasicTheme } from '@cimigo/collect-sdk/themes/basic';

// Tree-shaking friendly imports
const collect = new CimigoCollect({
tenantId: 'your-tenant-id',
renderers: [WidgetRenderer],
themes: [BasicTheme]
});

๐Ÿงช Testing Integrationโ€‹

Unit Testingโ€‹

// Mock the SDK for testing
jest.mock('@cimigo/collect-sdk', () => ({
CimigoCollect: jest.fn().mockImplementation(() => ({
showSurvey: jest.fn().mockResolvedValue({}),
on: jest.fn(),
off: jest.fn()
}))
}));

// Test your integration
import { CimigoCollect } from '@cimigo/collect-sdk';
import { showFeedbackSurvey } from './survey-integration';

test('should show feedback survey', async () => {
const mockShowSurvey = jest.fn().mockResolvedValue({});
CimigoCollect.mockImplementation(() => ({
showSurvey: mockShowSurvey
}));

await showFeedbackSurvey();

expect(mockShowSurvey).toHaveBeenCalledWith({
linkId: 'feedback-survey-link',
mode: 'widget',
theme: expect.objectContaining({
primaryColor: '#1976d2'
})
});
});

End-to-End Testingโ€‹

// Playwright E2E testing
import { test, expect } from '@playwright/test';

test('should complete survey flow', async ({ page }) => {
await page.goto('/survey-test-page');

// Trigger survey
await page.click('#show-survey-button');

// Wait for survey to load
await page.waitForSelector('.cimigo-survey-widget');

// Fill out survey
await page.fill('#question-1', 'Test response');
await page.selectOption('#question-2', 'option-1');
await page.click('#submit-survey');

// Verify completion
await expect(page.locator('.survey-thank-you')).toBeVisible();
});

๐Ÿ“š Next Stepsโ€‹

Now that you understand the SDK capabilities, explore these topics:

  • Getting Started Guide - Detailed setup instructions (coming soon)
  • Configuration Reference - Complete configuration options (coming soon)
  • Framework Integration - React, Vue, Angular examples (coming soon)
  • Event Reference - All available events and handlers (coming soon)
  • Troubleshooting - Common issues and solutions (coming soon)

The JavaScript SDK is designed to make survey integration simple while providing the flexibility and power needed for complex use cases. Start with the basic integration and gradually add advanced features as needed.