hivecfm-js
v4.3.0
Published
HiveCFM JS SDK allows you to connect your app to HiveCFM, display surveys and trigger events.
Maintainers
Readme
HiveCFM JavaScript SDK
The official HiveCFM JavaScript SDK for integrating customer feedback surveys into your web applications.
Table of Contents
- Installation
- Quick Start
- Configuration
- API Reference
- Framework Examples
- TypeScript Support
- Troubleshooting
Installation
Install the SDK using your preferred package manager:
# npm
npm install hivecfm-js
# pnpm
pnpm add hivecfm-js
# yarn
yarn add hivecfm-jsQuick Start
1. Import the SDK
import hivecfm from 'hivecfm-js';2. Initialize the SDK
if (typeof window !== "undefined") {
hivecfm.setup({
environmentId: 'your-environment-id',
appUrl: 'https://hivecfm.xcai.io' // Your HiveCFM instance URL
});
}3. Identify Users (Optional but Recommended)
// Set user ID for tracking
hivecfm.setUserId('user-123');
// Set user email
hivecfm.setEmail('[email protected]');
// Set custom attributes
hivecfm.setAttributes({
plan: 'premium',
company: 'Acme Inc',
role: 'admin'
});4. Track Events
// Track a custom event
hivecfm.track('button_clicked');
// Track event with hidden fields (passed to survey)
hivecfm.track('purchase_completed', {
hiddenFields: {
orderId: '12345',
amount: 99.99
}
});Configuration
Setup Options
| Option | Type | Required | Description |
|--------|------|----------|-------------|
| environmentId | string | Yes | Your HiveCFM environment ID |
| appUrl | string | Yes | Your HiveCFM instance URL |
Getting Your Environment ID
- Log in to your HiveCFM dashboard
- Navigate to Settings → Setup Checklist
- Copy your Environment ID from the configuration section
API Reference
setup(config)
Initializes the HiveCFM SDK. Must be called before any other methods.
hivecfm.setup({
environmentId: string;
appUrl: string;
}): Promise<void>Example:
await hivecfm.setup({
environmentId: 'clxxxxxxxxxxxxxxxxxx',
appUrl: 'https://hivecfm.xcai.io'
});setUserId(userId)
Sets the user ID for the current user. This enables user-level tracking and targeting.
hivecfm.setUserId(userId: string): Promise<void>Example:
await hivecfm.setUserId('user-456');setEmail(email)
Sets the email address for the current user.
hivecfm.setEmail(email: string): Promise<void>Example:
await hivecfm.setEmail('[email protected]');setAttribute(key, value)
Sets a single custom attribute for the current user.
hivecfm.setAttribute(key: string, value: string): Promise<void>Example:
await hivecfm.setAttribute('plan', 'enterprise');setAttributes(attributes)
Sets multiple custom attributes for the current user at once.
hivecfm.setAttributes(attributes: Record<string, string>): Promise<void>Example:
await hivecfm.setAttributes({
plan: 'enterprise',
company: 'Acme Corp',
department: 'Engineering',
role: 'Developer'
});setLanguage(language)
Sets the preferred language for the user (affects survey language).
hivecfm.setLanguage(language: string): Promise<void>Example:
await hivecfm.setLanguage('es'); // Spanish
await hivecfm.setLanguage('fr'); // French
await hivecfm.setLanguage('en'); // Englishtrack(eventName, properties?)
Tracks a custom event. Events can trigger surveys based on your targeting rules.
hivecfm.track(
eventName: string,
properties?: {
hiddenFields?: Record<string | number, string | number | string[]>
}
): Promise<void>Examples:
// Simple event tracking
await hivecfm.track('page_viewed');
await hivecfm.track('feature_used');
await hivecfm.track('checkout_started');
// Event with hidden fields (passed to survey responses)
await hivecfm.track('order_completed', {
hiddenFields: {
orderId: 'ORD-12345',
total: 149.99,
items: ['product-1', 'product-2']
}
});registerRouteChange()
Notifies HiveCFM of a route/page change. Useful for Single Page Applications (SPAs).
hivecfm.registerRouteChange(): Promise<void>Example (React Router):
import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import hivecfm from 'hivecfm-js';
function App() {
const location = useLocation();
useEffect(() => {
hivecfm.registerRouteChange();
}, [location]);
return <YourApp />;
}logout()
Logs out the current user and clears all user data. Call this when users sign out.
hivecfm.logout(): Promise<void>Example:
async function handleLogout() {
await hivecfm.logout();
// Continue with your logout logic
}setNonce(nonce)
Sets a CSP (Content Security Policy) nonce for inline styles. Required if your app uses strict CSP.
hivecfm.setNonce(nonce: string | undefined): Promise<void>Example:
// Set nonce for CSP compliance
await hivecfm.setNonce('abc123xyz');
// Clear nonce
await hivecfm.setNonce(undefined);Framework Examples
React Application
// src/App.jsx
import { useEffect } from 'react';
import hivecfm from 'hivecfm-js';
function App() {
useEffect(() => {
// Initialize HiveCFM on app load
hivecfm.setup({
environmentId: process.env.REACT_APP_HIVECFM_ENV_ID,
appUrl: process.env.REACT_APP_HIVECFM_URL
});
}, []);
return <YourApp />;
}Next.js Application (App Router)
// src/app/providers.tsx
'use client';
import { useEffect } from 'react';
import hivecfm from 'hivecfm-js';
export function HiveCFMProvider({ children }: { children: React.ReactNode }) {
useEffect(() => {
hivecfm.setup({
environmentId: process.env.NEXT_PUBLIC_HIVECFM_ENV_ID!,
appUrl: process.env.NEXT_PUBLIC_HIVECFM_URL!
});
}, []);
return <>{children}</>;
}// src/app/layout.tsx
import { HiveCFMProvider } from './providers';
export default function RootLayout({ children }: { children: React.ReactNode }) {
return (
<html>
<body>
<HiveCFMProvider>{children}</HiveCFMProvider>
</body>
</html>
);
}Next.js Application (Pages Router)
// src/pages/_app.tsx
import { useEffect } from 'react';
import type { AppProps } from 'next/app';
import hivecfm from 'hivecfm-js';
export default function App({ Component, pageProps }: AppProps) {
useEffect(() => {
hivecfm.setup({
environmentId: process.env.NEXT_PUBLIC_HIVECFM_ENV_ID!,
appUrl: process.env.NEXT_PUBLIC_HIVECFM_URL!
});
}, []);
return <Component {...pageProps} />;
}Vue.js Application
// main.js
import { createApp } from 'vue';
import App from './App.vue';
import hivecfm from 'hivecfm-js';
const app = createApp(App);
// Initialize HiveCFM
hivecfm.setup({
environmentId: import.meta.env.VITE_HIVECFM_ENV_ID,
appUrl: import.meta.env.VITE_HIVECFM_URL
});
app.mount('#app');Angular Application
// src/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import hivecfm from 'hivecfm-js';
import { environment } from '../environments/environment';
@Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
ngOnInit() {
hivecfm.setup({
environmentId: environment.hivecfmEnvId,
appUrl: environment.hivecfmUrl
});
}
}User Identification on Login
async function handleLogin(user) {
// After successful authentication
await hivecfm.setUserId(user.id);
await hivecfm.setEmail(user.email);
await hivecfm.setAttributes({
name: user.name,
plan: user.subscription.plan,
signupDate: user.createdAt
});
}Tracking E-commerce Events
// Track product view
hivecfm.track('product_viewed', {
hiddenFields: {
productId: 'SKU-123',
productName: 'Premium Widget',
category: 'Electronics'
}
});
// Track add to cart
hivecfm.track('add_to_cart', {
hiddenFields: {
productId: 'SKU-123',
quantity: 2,
price: 29.99
}
});
// Track purchase
hivecfm.track('purchase_completed', {
hiddenFields: {
orderId: 'ORD-456',
total: 59.98,
items: ['SKU-123', 'SKU-456']
}
});TypeScript Support
The SDK includes full TypeScript support. Types are automatically available when you import the package.
import hivecfm from 'hivecfm-js';
// All methods are fully typed
await hivecfm.setup({
environmentId: 'your-env-id',
appUrl: 'https://hivecfm.xcai.io'
});
// TypeScript will validate attribute types
await hivecfm.setAttributes({
plan: 'premium', // ✓ Valid - string value
company: 'Acme' // ✓ Valid - string value
});Troubleshooting
SDK Not Loading
Problem: Surveys aren't appearing after setup.
Solutions:
- Verify your
environmentIdis correct - Check that
appUrlpoints to your HiveCFM instance - Open browser DevTools and check for console errors
- Ensure the SDK is initialized before tracking events
- Make sure you're calling
setup()only on the client side (usetypeof window !== "undefined"check)
Events Not Triggering Surveys
Problem: Events are tracked but surveys don't appear.
Solutions:
- Verify your survey targeting rules in the HiveCFM dashboard
- Check that the event name matches exactly (case-sensitive)
- Ensure the user meets all targeting criteria
- Check survey scheduling settings
- Verify the survey is published and active
CSP Errors
Problem: Content Security Policy blocks the SDK.
Solutions:
- Add your HiveCFM domain to your CSP
script-srcandconnect-srcdirectives:script-src 'self' https://hivecfm.xcai.io; connect-src 'self' https://hivecfm.xcai.io; - Use
setNonce()if you have strict inline style policies
User Data Not Persisting
Problem: User attributes reset on page reload.
Solutions:
- Call
setUserId()aftersetup()completes on each page load - Store user data in your app state and re-apply after initialization
- Check that
logout()isn't being called unintentionally
Multiple Initialization Errors
Problem: Console shows "HiveCFM is already initializing" warning.
Solutions:
- Ensure
setup()is called only once (use useEffect with empty dependency array in React) - Use a flag to track initialization state
- Move initialization to a root component or provider
Environment Variables
Example .env file:
# For React (Create React App)
REACT_APP_HIVECFM_ENV_ID=your-environment-id
REACT_APP_HIVECFM_URL=https://hivecfm.xcai.io
# For Next.js
NEXT_PUBLIC_HIVECFM_ENV_ID=your-environment-id
NEXT_PUBLIC_HIVECFM_URL=https://hivecfm.xcai.io
# For Vite
VITE_HIVECFM_ENV_ID=your-environment-id
VITE_HIVECFM_URL=https://hivecfm.xcai.ioSupport
- Documentation: https://hivecfm.xcai.io/docs
- GitHub Issues: https://github.com/amrhym/hivecfm-js/issues
- Email: [email protected]
License
MIT License - see LICENSE for details.
