Skip to main content

JavaScript SDK Examples

Practical code examples to help you get started with the Resync JavaScript SDK.

Basic Initialization

import Resync from 'resync-javascript';

async function initializeApp() {
try {
await Resync.init({
key: process.env.RESYNC_API_KEY,
appId: parseInt(process.env.RESYNC_APP_ID),
storage: localStorage,
environment: 'production',
});

console.log('Resync initialized successfully');
} catch (error) {
console.error('Failed to initialize Resync:', error);
}
}

initializeApp();

Remote Configuration

Feature Flags

// Check if a feature is enabled
const newUIEnabled = Resync.getConfig('ENABLE_NEW_UI');
const darkModeAvailable = Resync.getConfig('DARK_MODE_AVAILABLE');

if (newUIEnabled) {
renderNewUI();
} else {
renderLegacyUI();
}

Configuration Objects

// Get configuration objects
const apiSettings = Resync.getConfig('API_SETTINGS');
console.log('API timeout:', apiSettings?.timeout);
console.log('Max retries:', apiSettings?.maxRetries);

Dynamic API Endpoints

const apiUrl = Resync.getConfig('API_BASE_URL');
const authEndpoint = Resync.getConfig('AUTH_ENDPOINT');

fetch(`${apiUrl}${authEndpoint}`, {
method: 'POST',
// ... request options
});

Campaigns & A/B Testing

Simple A/B Test

const variant = await Resync.getVariant('homepage_experiment');

if (variant === 123) {
// Show variant A (content view ID 123)
renderVariantA();
} else if (variant === 124) {
// Show variant B (content view ID 124)
renderVariantB();
} else {
// Show control (no variant assigned)
renderControl();
}

Multi-Variant Test

const checkoutVariant = await Resync.getVariant('checkout_flow_test');

switch(checkoutVariant) {
case 101:
renderOnePageCheckout();
break;
case 102:
renderTwoPageCheckout();
break;
case 103:
renderThreePageCheckout();
break;
default:
renderDefaultCheckout();
}

Event Tracking

Simple Event

Resync.logEvent({
eventId: 'evt_user_signup',
});

Event with Metadata

Resync.logEvent({
eventId: 'evt_purchase_completed',
logId: 'order_789',
metadata: {
amount: 99.99,
currency: 'USD',
productId: 'prod_123',
quantity: 2,
},
});

Tracking User Journey

// App opened
Resync.logEvent({
eventId: 'evt_app_opened',
metadata: { timestamp: Date.now() },
});

// Button clicked
document.getElementById('cta-button').addEventListener('click', () => {
Resync.logEvent({
eventId: 'evt_cta_clicked',
metadata: {
buttonId: 'cta-button',
page: 'homepage',
},
});
});

// Purchase completed
async function completePurchase(orderId, amount) {
await processPayment();

Resync.logEvent({
eventId: 'evt_purchase_completed',
logId: orderId,
metadata: {
amount,
currency: 'USD',
timestamp: Date.now(),
},
});
}

User Identification & Attributes

Set User ID

// Simple user ID
await Resync.loginUser('user_12345');

// With metadata
await Resync.loginUser('user_12345', {
email: 'user@example.com',
name: 'John Doe',
phone: '+1234567890',
language: 'en',
});

Set User Attributes

await Resync.setUserAttributes({
email: 'user@example.com',
name: 'Jane Smith',
phone: '+1234567890',
language: 'en',
attributes: {
subscriptionTier: 'premium',
country: 'US',
signupDate: '2025-01-15',
},
});

User Segmentation

// Set user attributes for targeting
await Resync.loginUser('user_123', {
email: 'user@example.com',
name: 'Alice',
});

await Resync.setUserAttributes({
attributes: {
userTier: 'premium',
region: 'north-america',
},
});

// Get variant (assignment may be based on attributes)
const variant = await Resync.getVariant('premium_feature_test');

if (variant) {
// Show experiment variant
showPremiumFeature();
} else {
// Show control
showStandardFeature();
}

Content Blocks

Fetch All Content

const contentViews = Resync.getContent();

// Find specific content view
const bannerContent = contentViews.find(
(view) => view.name === 'PromoAnnouncement'
);

// Iterate through all published content
contentViews
.filter((view) => view.status === 'published')
.forEach((view) => {
console.log(`Content view: ${view.name}`);
});

Dynamic Content Loading

const contentViews = Resync.getContent();
const dynamicBanner = contentViews.find(
(view) => view.name === 'DynamicHomeBanner'
);

if (dynamicBanner && dynamicBanner.items) {
// Render dynamic banner content
renderBanner(dynamicBanner.items);
}

Form Submission

Submit Form Data

try {
const success = await Resync.submitForm({
contentViewId: 456,
data: {
name: 'John Doe',
email: 'john@example.com',
message: 'Hello!',
},
});

if (success) {
console.log('Form submitted successfully');
showSuccessMessage();
}
} catch (error) {
console.error('Form submission failed:', error);
showErrorMessage();
}

Real-time Configuration Updates

Subscribe to Updates

await Resync.init({
key: 'your-api-key',
appId: 7,
storage: localStorage,
callback: () => {
console.log('Initial config loaded');
},
environment: 'production',
});

// Subscribe to future updates
Resync.subscribe((config) => {
console.log('Config updated!', config);
updateAppSettings();
});

React Component Example

import { useEffect, useState } from 'react';
import Resync from 'resync-javascript';

function FeatureFlaggedComponent() {
const [featureEnabled, setFeatureEnabled] = useState(false);

useEffect(() => {
const handleConfigUpdate = (config) => {
const enabled = Resync.getConfig('ENABLE_NEW_FEATURE');
setFeatureEnabled(enabled);
};

// Initial check
handleConfigUpdate();

// Subscribe to updates
Resync.subscribe(handleConfigUpdate);

return () => {
Resync.unsubscribe(handleConfigUpdate);
};
}, []);

return featureEnabled ? <NewFeature /> : <OldFeature />;
}

Error Handling

Graceful Fallbacks

try {
await Resync.init({
key: 'your-api-key',
appId: 7,
storage: localStorage,
environment: 'production',
});
} catch (error) {
console.error('Failed to initialize Resync:', error);
// Fallback to default configuration
useDefaultConfig();
}

Safe Config Access

const apiUrl = Resync.getConfig('API_URL') || 'https://api.example.com';
const timeout = Resync.getConfig('REQUEST_TIMEOUT') || 5000;

Complete Example: E-commerce App

import Resync from 'resync-javascript';

class EcommerceApp {
async initialize() {
// Initialize Resync
await Resync.init({
key: process.env.RESYNC_API_KEY,
appId: 7,
storage: localStorage,
callback: () => this.onConfigLoaded(),
environment: 'production',
});

// Set user info
const user = this.getCurrentUser();
if (user) {
await Resync.loginUser(user.id, {
email: user.email,
name: user.name,
});

await Resync.setUserAttributes({
attributes: {
customerTier: user.tier,
totalPurchases: user.purchaseCount,
},
});
}
}

onConfigLoaded() {
// Apply remote config
const theme = Resync.getConfig('APP_THEME');
this.applyTheme(theme);

// Check feature flags
const newCheckoutEnabled = Resync.getConfig('ENABLE_NEW_CHECKOUT');
if (newCheckoutEnabled) {
this.enableNewCheckout();
}
}

async loadHomepage() {
// Get campaign variant for homepage
const variant = await Resync.getVariant('homepage_promo');

if (variant === 101) {
this.showPromoA();
} else if (variant === 102) {
this.showPromoB();
}

// Track page view
Resync.logEvent({
eventId: 'evt_homepage_viewed',
});
}

async checkout(items, total) {
// Track checkout started
Resync.logEvent({
eventId: 'evt_checkout_started',
metadata: {
itemCount: items.length,
total: total,
},
});

// Process checkout...
const orderId = await this.processOrder(items, total);

// Track purchase
Resync.logEvent({
eventId: 'evt_purchase_completed',
logId: orderId,
metadata: {
amount: total,
currency: 'USD',
itemCount: items.length,
},
});
}
}

// Initialize app
const app = new EcommerceApp();
app.initialize();

More Examples