React/Web SDK Guide
Complete guide to integrating AppFig into your React or web application.
Installation
SDK Download Repository: https://github.com/smartconfigui/AppFig-SDKs
Requirements: Modern browser with ES6+ support (Chrome 90+, Firefox 88+, Safari 14+, Edge 90+)
Step 1: Download the SDK
Download the SDK files from:
https://github.com/smartconfigui/AppFig-SDKs/tree/v2.5.0/react
You'll need:
AppFigReactSDK.js(required) - Minified SDK bundleAppFigReactSDK.d.ts(required) - TypeScript type definitions
Step 2: Add to Your Project
Copy both files to your project directory (e.g., src/lib/appfig/).
Step 3: Import in Your Code
import AppFig from './lib/appfig/AppFigReactSDK.js';
TypeScript Support:
If you copied AppFigReactSDK.d.ts to the same folder, TypeScript will automatically discover the type definitions. No additional configuration needed.
Bundler Compatibility: The minified bundle works with all modern bundlers:
- ✅ Vite
- ✅ Webpack
- ✅ Rollup
- ✅ Parcel
- ✅ Create React App
Benefits:
- No npm installation required
- No build steps
- No dependency conflicts
- No version management hassles
- Works in any JavaScript/TypeScript project
Quick Start
import AppFig from './AppFigReactSDK';
// Initialize with your credentials (auto-refresh enabled by default)
await AppFig.init({
companyId: 'your-company-id',
tenantId: 'your-tenant-id',
env: 'prod', // 'dev' or 'prod'
apiKey: 'your-api-key',
autoRefresh: true, // Auto-refresh rules (default: true) ✨ NEW
pollInterval: 3600000, // 1 hour (default: follows your plan)
debugMode: false, // Enable debug logging (default: false) ✨ NEW
sessionTimeoutMs: 1800000, // 30 minutes (default: 30 min) ✨ NEW
maxEvents: 5000, // Max events to store (default: 5000)
maxEventAgeDays: 7 // Max event age in days (default: 7)
});
// Log events
AppFig.logEvent('button_clicked', {
button_id: 'upgrade',
page: 'home'
});
// Check features
const welcomeMsg = AppFig.getConfig('welcome_message');
const showPremium = AppFig.getConfig('show_premium_banner');
if (showPremium === 'on') {
showPremiumFeatures();
}
When to Do What: Timing Guide
Understanding WHEN to call each SDK method is crucial for proper React/Web integration:
| Action | When to Call | Where to Place | Code Example |
|---|---|---|---|
| Initialize SDK | Once at app startup | main.tsx or App.tsx top-level | await AppFig.init(...) |
| Log Events | Immediately after user action | Event handlers, onClick | AppFig.logEvent('button_click') |
| Set User Properties | Once at login, when value changes | Auth callback, state change | AppFig.setUserProperties({ tier: 'premium' }) |
| Evaluate Features | When component mounts or renders | useEffect, component render | AppFig.getConfig('feature_name') |
| Apply Features | Immediately after evaluation | Same render cycle | if (value) return <Component /> |
| Refresh Rules | On demand (auto-refresh handles this) | Manual: Settings page | AppFig.refreshRules() |
Complete Lifecycle Example
import React, { useEffect, useState } from 'react';
import AppFig from './AppFigReactSDK';
// 1. INITIALIZE: Once at app startup (main.tsx or App.tsx)
async function initializeApp() {
await AppFig.init({
companyId: 'your-company-id',
tenantId: 'your-tenant-id',
env: 'prod',
apiKey: 'your-api-key'
});
// 2. TRACK: Log app open
AppFig.logEvent('app_open');
}
// Call initialization
initializeApp();
function App() {
const [showWelcome, setShowWelcome] = useState(false);
const [playerLives, setPlayerLives] = useState(3);
useEffect(() => {
// 3. EVALUATE: Check features when component mounts
checkWelcomeBonus();
configureGameSettings();
}, []);
const checkWelcomeBonus = () => {
// Evaluate right before using
const bonusValue = AppFig.getConfig('welcome_bonus');
// 4. APPLY: Update state immediately
if (bonusValue === 'on') {
setShowWelcome(true);
}
};
const configureGameSettings = () => {
// Evaluate with fallback
const maxLives = parseInt(AppFig.getConfig('max_lives') || '3');
// Apply to state
setPlayerLives(maxLives);
};
const handleLevelComplete = () => {
// TRACK: Log immediately after action
AppFig.logEvent('level_complete', {
level: currentLevel.toString()
});
// Re-evaluate features that depend on level
checkNewUnlocks();
};
const handleSubscriptionPurchase = (tier: string) => {
// Update property when it changes
AppFig.setUserProperties({ subscription_tier: tier });
// Re-evaluate premium features
updatePremiumFeatures();
};
return (
<div>
{showWelcome && <WelcomeBonusModal />}
<div>Lives: {playerLives}</div>
<button onClick={handleLevelComplete}>Complete Level</button>
</div>
);
}
Timing Best Practices
Initialize Once at Startup
// ✅ CORRECT: Initialize in main.tsx before rendering
import AppFig from './AppFigReactSDK';
await AppFig.init({
companyId: '...',
tenantId: '...',
env: 'prod',
apiKey: '...'
});
const root = ReactDOM.createRoot(document.getElementById('root')!);
root.render(<App />);
// ❌ WRONG: Don't initialize in every component
function MyComponent() {
useEffect(() => {
AppFig.init({...}); // Bad! SDK already initialized
}, []);
}
Log Events Immediately
// ✅ CORRECT: Log right when action happens
const handlePurchaseClick = () => {
AppFig.logEvent('purchase_initiated', {
item_id: 'premium_plan'
});
showPurchaseDialog();
};
// ❌ WRONG: Don't batch events
const pendingEvents: string[] = [];
const handleClick = () => {
pendingEvents.push('button_clicked'); // Bad!
};
Cache Feature Values with State
// ✅ CORRECT: Check once and cache in state
function GameComponent() {
const [hasDoubleXP, setHasDoubleXP] = useState(false);
useEffect(() => {
const doubleXP = AppFig.getConfig('double_xp') === 'on';
setHasDoubleXP(doubleXP);
}, []);
const calculateXP = (baseXP: number) => {
return hasDoubleXP ? baseXP * 2 : baseXP;
};
return <div>XP: {calculateXP(100)}</div>;
}
// ❌ WRONG: Don't check on every render
function BadComponent() {
// This checks on every single render - very inefficient!
const hasDoubleXP = AppFig.getConfig('double_xp') === 'on';
return <div>Has XP: {hasDoubleXP}</div>;
}
Evaluate in useEffect, Not Render
// ✅ CORRECT: Evaluate in useEffect
function WelcomeScreen() {
const [showBonus, setShowBonus] = useState(false);
useEffect(() => {
const bonusEnabled = AppFig.getConfig('welcome_bonus') === 'on';
setShowBonus(bonusEnabled);
}, []);
return (
<div>
{showBonus && <BonusModal />}
</div>
);
}
// ❌ WRONG: Don't evaluate in render without memoization
function BadWelcomeScreen() {
// This evaluates on every render
const showBonus = AppFig.getConfig('welcome_bonus') === 'on';
return (
<div>
{showBonus && <BonusModal />}
</div>
);
}
API Reference
Initialization
await AppFig.init({
companyId: string, // Required: Your company ID
tenantId: string, // Required: Your tenant/project ID
env: 'dev' | 'prod', // Required: Environment
apiKey: string, // Required: Your API key
autoRefresh?: boolean, // Optional: Auto-refresh rules (default: true) ✨ NEW DEFAULT
pollInterval?: number, // Optional: leave out to follow your plan
debugMode?: boolean, // Optional: Enable debug logging (default: false) ✨ NEW
sessionTimeoutMs?: number, // Optional: Session timeout (default: 1800000 = 30 min) ✨ NEW
maxEvents?: number, // Optional: Max events to store (default: 5000, max: 100000)
maxEventAgeDays?: number, // Optional: Max event age in days (default: 7, max: 365)
cdnBaseUrl?: string, // Optional: rules host (default: production) 🆕 2.3
// Deprecated (use autoRefresh instead):
autoUpdate?: boolean // Deprecated: Use autoRefresh instead
})
Parameters:
companyId(required) - Your company ID from AppFig dashboardtenantId(required) - Your tenant/project ID from AppFig dashboardenv(required) - Environment:'dev'or'prod'apiKey(required) - Your API key from AppFig dashboardautoRefresh(optional) - Enable automatic rule refreshing (default: true) ⚠️ Breaking ChangepollInterval(optional) - Auto-refresh interval in milliseconds. Leave it out and the SDK checks for changes every minute, on every plan 🆕 New in 2.3. A value you set is kept, but never faster than your plan allows.debugMode(optional) - Enable debug console logs (default: false) 🆕 New in v2.0sessionTimeoutMs(optional) - Session timeout in milliseconds (default: 1800000 = 30 min, range: 60000-7200000) 🆕 New in v2.0maxEvents(optional) - Maximum events to store locally (100-100000, default: 5000)maxEventAgeDays(optional) - Maximum age of events in days (1-365, default: 7)cdnBaseUrl(optional) - The rules host to read from, e.g.https://rules-stage.appfig.comfor a staging build. Leave it out for production (https://rules-prod.appfig.com). Must start withhttps://. 🆕 New in 2.3autoUpdate(deprecated) - UseautoRefreshinstead (backward compatibility maintained)
Examples:
// Basic initialization (auto-refresh enabled by default)
await AppFig.init({
companyId: 'acme-games',
tenantId: 'space-shooter',
env: 'prod',
apiKey: 'sk_live_abc123xyz'
});
// With custom settings
await AppFig.init({
companyId: 'acme-games',
tenantId: 'space-shooter',
env: 'prod',
apiKey: 'sk_live_abc123xyz',
autoRefresh: true, // Explicit (but this is already the default)
pollInterval: 3600000, // 1 hour
debugMode: true, // See what's happening
sessionTimeoutMs: 900000, // 15 minutes instead of 30
maxEvents: 10000 // Store more events
});
// Disable auto-refresh (opt-out)
await AppFig.init({
companyId: 'acme-games',
tenantId: 'space-shooter',
env: 'prod',
apiKey: 'sk_live_abc123xyz',
autoRefresh: false // Manual refresh only
});
Logging Events
AppFig.logEvent(name: string, params?: Record<string, any>)
Examples:
// Simple event
AppFig.logEvent('page_view');
// Event with parameters
AppFig.logEvent('purchase_completed', {
item_id: 'premium_plan',
price: 29.99,
currency: 'USD'
});
// Button click
AppFig.logEvent('button_clicked', {
button_id: 'cta',
page: 'landing',
variant: 'blue'
});
Checking Features
AppFig.getConfig(flagName: string): any
Returns the feature value, or null if no rules match.
Examples:
// Get feature value
const welcomeMsg = AppFig.getConfig('welcome_message');
if (welcomeMsg) {
setMessage(welcomeMsg);
}
// Boolean features
const showPremium = AppFig.getConfig('show_premium_banner');
if (showPremium === 'on') {
renderPremiumBanner();
}
// Numeric features
const maxRetries = AppFig.getConfig('max_api_retries');
const retries = parseInt(maxRetries || '3', 10);
// Complex features
const pricingConfig = AppFig.getConfig('pricing_tiers');
// Returns: { basic: 9, pro: 29, enterprise: 99 }
Setting Properties
// User properties
AppFig.setUserProperties(props: Record<string, any>)
// Device properties
AppFig.setDeviceProperties(props: Record<string, any>)
// App version
AppFig.setAppVersion(version: string)
Examples:
// Set user properties
AppFig.setUserProperties({
subscription_tier: 'premium',
account_age_days: 45,
preferred_theme: 'dark'
});
// Set device properties
AppFig.setDeviceProperties({
browser_name: 'Chrome',
screen_width: 1920
});
// Set app version
AppFig.setAppVersion('2.1.0');
Auto-Detected Properties
These are automatically set by the SDK on initialization:
country "US", "JP", "GB" (from CDN response headers)
platform "macOS", "Windows", "Linux", "iOS", "Android"
language "en-US", "ja", "es-ES" (from browser)
timezone "America/Los_Angeles", "Asia/Tokyo" (from system)
os_version "10.15.7", "11.0", "14.2" (from user agent)
device_brand "Apple", "Microsoft", "Google"
device_model "Chrome 120 on macOS", "Firefox 121 on Windows"
app_version "1.0.0" (you set this with setAppVersion())
sdk_version "2.0.0" (AppFig SDK version)
Country Detection:
- Primary: Extracted from CDN response
Countryheader (Cloudflare Workers) - Fallback: Static endpoint
rules-dev.appfig.comwith 5-second timeout - No third-party services used (fully controlled by AppFig infrastructure)
Manual Refresh
await AppFig.refreshRules()
AppFig.stopAutoRefresh()
Examples:
// Manually refresh rules
await AppFig.refreshRules();
// Stop auto-refresh
AppFig.stopAutoRefresh();
Feature Reset (Recurring Triggers)
AppFig.resetFeature(featureName: string)
AppFig.resetAllFeatures()
Reset a feature's cached value and force re-evaluation. Useful for implementing recurring triggers like "show popup every 3 events".
Example:
// Check if feature is enabled
if (AppFig.check("level_complete_popup")) {
showPopup("You've completed 3 levels!");
// Reset so it triggers again after next 3 events
AppFig.resetFeature("level_complete_popup");
}
// With event logging
function onLevelComplete(level: number) {
AppFig.logEvent("level_complete", { level: level.toString() });
// Check for milestone reward
if (AppFig.check("milestone_reward")) {
showReward();
AppFig.resetFeature("milestone_reward");
}
}
Use Cases:
- Show popup every N events (e.g., every 3 level completions)
- Recurring promotions after X purchases
- Periodic reward unlocks
- Time-based feature re-triggers
See Feature Reset Guide for detailed examples.
Debugging
AppFig.getDebugInfo()
AppFig.getEventHistory()
Example:
const debug = AppFig.getDebugInfo();
console.log('Rules:', debug.rules);
console.log('Events:', debug.events);
console.log('User properties:', debug.userProperties);
console.log('Device properties:', debug.deviceProperties);
console.log('Cached results:', debug.cachedResults);
const events = AppFig.getEventHistory();
console.log(`Logged ${events.length} events`);
React Integration
Basic Setup
import { useEffect, useState } from 'react';
import AppFig from './AppFigReactSDK';
function App() {
const [isInitialized, setIsInitialized] = useState(false);
const [welcomeMessage, setWelcomeMessage] = useState('');
useEffect(() => {
async function init() {
await AppFig.init({
companyId: 'acme-games',
tenantId: 'my-app',
env: 'prod',
apiKey: 'sk_live_abc123'
});
setIsInitialized(true);
// Get initial feature values
const msg = AppFig.getConfig('welcome_message');
setWelcomeMessage(msg || 'Welcome!');
}
init();
}, []);
if (!isInitialized) {
return <div>Loading...</div>;
}
return (
<div>
<h1>{welcomeMessage}</h1>
</div>
);
}
Custom Hook
import { useState, useEffect } from 'react';
import AppFig from './AppFigReactSDK';
export function useFeature(featureName: string) {
const [value, setValue] = useState<any>(null);
useEffect(() => {
const val = AppFig.getConfig(featureName);
setValue(val);
}, [featureName]);
return value;
}
// Usage
function MyComponent() {
const showBanner = useFeature('premium_banner');
const maxRetries = useFeature('api_max_retries');
return (
<div>
{showBanner === 'on' && <PremiumBanner />}
<ApiClient maxRetries={parseInt(maxRetries || '3', 10)} />
</div>
);
}
Context Provider
import React, { createContext, useContext, useEffect, useState } from 'react';
import AppFig from './AppFigReactSDK';
const AppFigContext = createContext<{
isInitialized: boolean;
getFeature: (name: string) => any;
logEvent: (name: string, params?: any) => void;
}>({
isInitialized: false,
getFeature: () => null,
logEvent: () => {}
});
export function AppFigProvider({
children,
companyId,
tenantId,
env,
apiKey
}: {
children: React.ReactNode;
companyId: string;
tenantId: string;
env: 'dev' | 'prod';
apiKey: string;
}) {
const [isInitialized, setIsInitialized] = useState(false);
useEffect(() => {
async function init() {
await AppFig.init({ companyId, tenantId, env, apiKey });
setIsInitialized(true);
}
init();
}, [companyId, tenantId, env, apiKey]);
const value = {
isInitialized,
getFeature: (name: string) => AppFig.getConfig(name),
logEvent: (name: string, params?: any) => AppFig.logEvent(name, params)
};
return (
<AppFigContext.Provider value={value}>
{children}
</AppFigContext.Provider>
);
}
export function useAppFig() {
return useContext(AppFigContext);
}
// Usage
function App() {
return (
<AppFigProvider
companyId="acme-games"
tenantId="my-app"
env="prod"
apiKey="sk_live_abc123"
>
<MyComponent />
</AppFigProvider>
);
}
function MyComponent() {
const { isInitialized, getFeature, logEvent } = useAppFig();
if (!isInitialized) {
return <div>Loading...</div>;
}
const showBanner = getFeature('premium_banner');
return (
<div>
{showBanner === 'on' && <PremiumBanner />}
<button onClick={() => logEvent('button_clicked', { id: 'cta' })}>
Upgrade Now
</button>
</div>
);
}
Automatic Tracking
The SDK automatically tracks these events:
'first_open' // First time user visits (persisted in localStorage)
'session_start' // Page becomes visible
'session_end' // Page hidden or 10 min inactivity
'screen_view' // URL changes (single-page apps)
Screen View Tracking
Automatically tracks navigation in single-page apps:
// Automatically logged when URL changes
// Works with:
// - History API (pushState, replaceState)
// - Hash changes (#/page)
// - Browser back/forward buttons
// Each screen view includes:
AppFig.logEvent('screen_view', {
screen_name: 'dashboard', // From URL path or hash
previous_screen: 'home' // Previous screen
});
Debug Mode
Enable debug logging to see detailed SDK activity:
await AppFig.init({
companyId: 'acme-games',
tenantId: 'my-app',
env: 'prod',
apiKey: 'sk_live_abc123',
debugMode: true // ← Enable debug logs
});
// Console output:
// [AppFig] 📱 Detected platform: macOS
// [AppFig] 🌍 Detected language: en-US
// [AppFig] 🔧 Device properties set: country, platform, language
// [AppFig] ✅ Loaded rules from CDN - Feature count: 5
// [AppFig] 🔍 getConfig called for: welcome_message
// [AppFig] 🔍 Returning CACHED result for welcome_message: "Hello!"
Best Practices
1. Initialize Once
Initialize at app entry point:
// ✅ Good: Initialize in root component
function App() {
useEffect(() => {
AppFig.init({
companyId: 'acme-games',
tenantId: 'my-app',
env: 'prod',
apiKey: 'sk_live_abc123'
});
}, []);
// ...
}
// ❌ Bad: Initializing in multiple places
function Header() {
useEffect(() => {
AppFig.init({ ... }); // Don't repeat!
}, []);
}
2. Cache Feature Values in State
// ✅ Good: Check once, store in state
function Component() {
const [showBanner, setShowBanner] = useState(false);
useEffect(() => {
const value = AppFig.getConfig('show_banner');
setShowBanner(value === 'on');
}, []);
return showBanner ? <Banner /> : null;
}
// ❌ Bad: Checking on every render
function Component() {
const showBanner = AppFig.getConfig('show_banner') === 'on';
return showBanner ? <Banner /> : null;
}
3. Handle Null Values
// ✅ Good: Provide fallback
const maxRetries = parseInt(
AppFig.getConfig('max_retries') || '3',
10
);
// ❌ Bad: No fallback
const maxRetries = parseInt(AppFig.getConfig('max_retries'), 10);
// NaN if feature returns null!
4. Log Events Generously
function handlePurchase(item: string, price: number) {
// Log detailed events
AppFig.logEvent('purchase_started', {
item_id: item,
price: price.toString(),
currency: 'USD',
page: window.location.pathname
});
// ... process purchase ...
AppFig.logEvent('purchase_completed', {
item_id: item,
price: price.toString(),
payment_method: 'stripe'
});
}
TypeScript Types
import type {
AppFigRule,
AppFigInitParams,
AppFigEvent,
Condition
} from './AppFigReactSDK';
// Use types in your code
const params: AppFigInitParams = {
companyId: 'acme-games',
tenantId: 'my-app',
env: 'prod',
apiKey: 'sk_live_abc123',
debugMode: true
};
Performance Tips
Caching
Features are cached after first evaluation for optimal performance:
// First call: Evaluates rules
const msg1 = AppFig.getConfig('welcome_message');
// Second call: Returns cached value (nearly instant)
const msg2 = AppFig.getConfig('welcome_message');
Cache is invalidated when:
- New events are logged
- User/device properties change
- Rules are refreshed
Bundle Size
The SDK has a small footprint suitable for web applications, with minimal impact on your application's bundle size after minification and compression.
Troubleshooting
Module not found or import errors
Problem: Bundler can't find the SDK file
Solutions:
- Verify
AppFigReactSDK.jsis in the correct location - Check import path is correct (use relative path like
'./lib/appfig/AppFigReactSDK.js') - For Webpack/CRA: Ensure path starts with
./or../ - For Vite: Import path should work as-is
TypeScript errors: "Could not find a declaration file"
Problem: TypeScript shows type errors
Solutions:
- Verify
AppFigReactSDK.d.tsis in the same folder asAppFigReactSDK.js - If using a different location, add
/// <reference path="./path/to/AppFigReactSDK.d.ts" />at the top of your file - Or use
// @ts-ignoreabove the import if types aren't needed
Rules not loading
Problem: Failed to load rules from CDN
Solutions:
- Verify API key is correct
- Check browser console for network errors
- Ensure company ID and tenant ID are correct
- Verify environment ('dev' or 'prod') matches your dashboard setup
Features always return null
Problem: No rules match
Solutions:
- Verify feature name spelling (case-sensitive)
- Check rules are loaded:
AppFig.getDebugInfo().rules - Log relevant events/properties before checking feature
- Enable debug mode to see rule evaluation
Auto-refresh not working
Problem: Changes in dashboard not reflected
Solutions:
- Verify
autoUpdate: truein initialization - Wait for the refresh interval (one minute)
- Check browser console for refresh logs
- Call
AppFig.refreshRules()manually
Next Steps
- Rule Schema - All rule options
- Testing Guide - Test your features