### Run Unleash SDK Example Source: https://github.com/unleash/unleash-js-sdk/blob/main/examples/README.md Demonstrates how to install dependencies, build the project, and execute a local Unleash client example using environment variables for the API URL and client token. ```bash yarn install yarn build UNLEASH_URL='https:///api/frontend' \ UNLEASH_CLIENT_KEY='' \ node examples/simple_usage.js ``` -------------------------------- ### start() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Starts the background polling mechanism and initializes the client for feature flag evaluation. ```APIDOC ## Method: start() ### Description Starts the Unleash client, initializing the background polling mechanism for toggle updates and metrics reporting. This method is asynchronous. ### Method ASYNC ### Response #### Success Response (200) - **Promise** (void) - Resolves when the initial fetch is complete and the client is ready. ``` -------------------------------- ### Start Unleash Client and Handle Events Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Shows the initialization of the client, registration of event listeners for lifecycle management, and the async start method to begin polling for toggle updates. ```javascript import { UnleashClient } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); unleash.on('ready', () => { console.log('Client is ready, toggles are available'); }); unleash.on('error', (error) => { console.error('Client encountered an error:', error); }); await unleash.start(); const isEnabled = unleash.isEnabled('my-feature'); console.log('Feature enabled:', isEnabled); ``` -------------------------------- ### Initialize and Configure Unleash Client Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Demonstrates how to import, instantiate, and start the Unleash client with required configuration parameters such as URL, client key, and application name. ```javascript import { UnleashClient } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https:///api/frontend', clientKey: '', appName: 'my-webapp', }); // Start the background polling unleash.start(); ``` -------------------------------- ### Install Unleash Proxy Client Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md The installation command for the Unleash proxy client package via npm. ```bash npm install unleash-proxy-client ``` -------------------------------- ### Handle UnleashClient Lifecycle Events Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Demonstrates how to subscribe to various lifecycle events such as 'initialized', 'ready', 'update', and 'impression' using the TinyEmitter-based event system. Includes examples of adding, removing, and one-time event listeners. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', impressionDataAll: true }); unleash.on('initialized', () => console.log('Client initialized')); unleash.on('ready', () => console.log('Client ready')); unleash.on('update', () => console.log('Toggles updated')); unleash.on('error', (error) => console.error('Unleash error:', error)); unleash.on('impression', (event) => console.log('Impression:', event)); const updateHandler = () => console.log('Updated!'); unleash.on('update', updateHandler); unleash.off('update', updateHandler); unleash.once('ready', () => console.log('First ready event only')); await unleash.start(); ``` -------------------------------- ### Implement Custom Storage Providers Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Shows how to implement the IStorageProvider interface to persist toggle data. Examples include AsyncStorage for React Native, SharedPreferences, and IndexedDB for web applications. ```javascript const asyncStorageProvider = { save: async (name, data) => { await AsyncStorage.setItem(`unleash:${name}`, JSON.stringify(data)); }, get: async (name) => { const data = await AsyncStorage.getItem(`unleash:${name}`); return data ? JSON.parse(data) : undefined; } }; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'react-native-app', storageProvider: asyncStorageProvider }); ``` -------------------------------- ### Stop Unleash Client Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Illustrates how to stop the client's background processes and cleanup resources, including an example of handling graceful shutdowns in Node.js environments. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); await unleash.start(); const enabled = unleash.isEnabled('feature.demo'); unleash.stop(); process.on('SIGINT', () => { unleash.stop(); process.exit(0); }); ``` -------------------------------- ### Use Unleash JS SDK in Node.js Environment Source: https://context7.com/unleash/unleash-js-sdk/llms.txt This snippet shows how to integrate the Unleash JavaScript SDK within a Node.js application. It highlights the need for a fetch implementation (like node-fetch) and an alternative storage provider (InMemoryStorageProvider). Error handling and lifecycle events are also demonstrated, along with an example of Express.js middleware for updating user context. ```javascript import fetch from 'node-fetch'; import { UnleashClient, InMemoryStorageProvider } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'nodejs-service', storageProvider: new InMemoryStorageProvider(), fetch, refreshInterval: 15, metricsInterval: 60 }); // Error handling for server environments unleash.on('error', (error) => { console.error('[Unleash] Error:', error); // Consider fallback behavior }); unleash.on('ready', () => { console.log('[Unleash] Client ready'); }); // Start and wait for ready await unleash.start(); // Express.js middleware example import express from 'express'; const app = express(); app.use((req, res, next) => { // Set user context from request unleash.updateContext({ userId: req.user?.id, sessionId: req.sessionID, remoteAddress: req.ip, properties: { userAgent: req.headers['user-agent'] } }).then(next); }); app.get('/api/features', (req, res) => { const features = { newDashboard: unleash.isEnabled('new-dashboard'), betaAPI: unleash.isEnabled('beta-api'), variant: unleash.getVariant('experiment-123') }; res.json(features); }); // Graceful shutdown process.on('SIGTERM', () => { unleash.stop(); process.exit(0); }); ``` -------------------------------- ### Get All Cached Feature Toggles with getAllToggles() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Returns a copy of all feature toggles currently cached in the client using the `getAllToggles` method. This is useful for debugging or bulk operations. It returns an array of toggle objects, each containing name, enabled status, variant, and impression data configuration. Dependencies include UnleashClient initialization and the 'ready' event. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); unleash.on('ready', () => { // Get all toggles for debugging or analysis const allToggles = unleash.getAllToggles(); console.log('All toggles:', allToggles); // Output: [ // { name: 'feature-a', enabled: true, variant: {...}, impressionData: false }, // { name: 'feature-b', enabled: false, variant: {...}, impressionData: true } // ] // Find enabled toggles const enabledToggles = allToggles.filter(toggle => toggle.enabled); console.log('Enabled toggles:', enabledToggles.map(t => t.name)); // Check for toggles with impression data const impressionToggles = allToggles.filter(t => t.impressionData); console.log('Impression data toggles:', impressionToggles.length); }); await unleash.start(); ``` -------------------------------- ### Update Client Context with updateContext() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Replaces the mutable portion of the Unleash context and triggers a toggle refresh from the server using the `updateContext` method. The updated context is used for re-evaluating feature flags against user attributes. Static fields like appName and environment cannot be updated. Dependencies include UnleashClient initialization and starting the client. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', context: { userId: 'anonymous' } }); await unleash.start(); // User logs in - update context with user information await unleash.updateContext({ userId: 'user-12345', properties: { email: 'user@example.com', plan: 'enterprise', company: 'Acme Corp', role: 'admin' } }); // Toggles are now re-evaluated with new context const adminFeatures = unleash.isEnabled('admin-dashboard'); console.log('Admin dashboard enabled:', adminFeatures); // User changes subscription plan await unleash.updateContext({ userId: 'user-12345', properties: { plan: 'premium', company: 'Acme Corp' } }); ``` -------------------------------- ### Get Unleash Context in JavaScript Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Returns a copy of the current Unleash context object. This is useful for debugging or displaying the current evaluation context to users. The returned context is a copy, so modifying it does not affect the original Unleash context. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', environment: 'production', context: { userId: 'user-123', sessionId: 'sess-456', properties: { company: 'Acme', plan: 'enterprise' } } }); await unleash.start(); // Get current context const context = unleash.getContext(); console.log('Context:', JSON.stringify(context, null, 2)); // Safe to modify - returns a copy context.userId = 'modified'; const originalContext = unleash.getContext(); console.log('Original userId unchanged:', originalContext.userId === 'user-123'); ``` -------------------------------- ### Handle Client Initialization Events Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Shows how to listen for the 'ready' event to ensure the client has synchronized with the server before evaluating feature flags. ```javascript unleash.on('ready', () => { if (unleash.isEnabled('js.demo')) { console.log('js.demo is enabled'); } else { console.log('js.demo is disabled'); } }); ``` -------------------------------- ### Initialize UnleashClient Instance Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Demonstrates how to instantiate the UnleashClient with required configuration, including API URL, client keys, and optional settings like context, storage providers, and bootstrap data. ```javascript import { UnleashClient, InMemoryStorageProvider } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', context: { userId: 'user-123', sessionId: 'session-456', properties: { plan: 'premium', region: 'eu-west' } }, refreshInterval: 30, metricsInterval: 60, storageProvider: new InMemoryStorageProvider(), bootstrap: [{ name: 'feature.demo', enabled: true, variant: { name: 'blue', enabled: true }, impressionData: false }] }); ``` -------------------------------- ### Initialize and Use Unleash Client from CDN in HTML Source: https://context7.com/unleash/unleash-js-sdk/llms.txt This snippet shows how to include the Unleash SDK via a CDN in an HTML file and initialize the UnleashClient. It covers setting up configuration, updating user context, and handling feature flag states and variants upon client readiness and updates. Dependencies include the 'unleash-proxy-client' library loaded from a CDN. ```html
``` -------------------------------- ### UnleashClient Constructor Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Initializes a new instance of the UnleashClient with configuration options for connectivity, authentication, and behavior. ```APIDOC ## Constructor: new UnleashClient(options) ### Description Creates an instance of the Unleash client. This is the primary entry point for integrating Unleash into your JavaScript application. ### Parameters #### Request Body - **url** (string) - Required - The URL to the Unleash Frontend API or Edge. - **clientKey** (string) - Required - The client token used for authentication. - **appName** (string) - Required - The name of the application for metrics tracking. - **context** (object) - Optional - Initial context for feature evaluation (userId, sessionId, properties). - **refreshInterval** (number) - Optional - Polling interval in seconds (default: 30). - **bootstrap** (array) - Optional - Initial toggle data for offline-first scenarios. ### Request Example { "url": "https://app.unleash-hosted.com/demo/api/frontend", "clientKey": "your-frontend-token", "appName": "my-webapp" } ``` -------------------------------- ### Initialize and Configure Unleash Client Source: https://github.com/unleash/unleash-js-sdk/blob/main/src/test/index.html Demonstrates how to instantiate the UnleashClient with connection parameters and register event listeners for lifecycle management. The client monitors feature flag states and reports impressions via the configured proxy URL. ```javascript const client = new unleash.UnleashClient({ url: new URL('proxy', 'http://localhost:3000'), clientKey: 'a', appName: 'a', refreshInterval: 1, metricsInterval: 1, disableMetrics: false }); client.start(); client.on('initialized', () => console.log('initialized')); client.on('error', (error) => console.log('error', error)); client.on('ready', () => console.log('ready')); client.on('impression', () => console.log('impression')); client.on('update', () => console.log('update', client.isEnabled('a'))); ``` -------------------------------- ### Bootstrap Unleash Client with Initial Configuration Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Shows how to initialize the UnleashClient with a pre-defined set of feature toggles using the bootstrap attribute. This allows the SDK to function immediately without waiting for an initial API call. ```javascript import { UnleashClient } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: '', appName: 'nodejs-proxy', bootstrap: [{ "enabled": true, "name": "demoApp.step4", "variant": { "enabled": true, "name": "blue", "feature_enabled": true, } }], bootstrapOverride: false }); ``` -------------------------------- ### Initialize Unleash Client via CDN Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Demonstrates how to include the Unleash Proxy Client in an HTML document using a CDN script tag. It initializes the client with a configuration object, updates the user context, and listens for update events. ```html ``` -------------------------------- ### Check Client Readiness with Unleash JS SDK Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Explains how to use the `isReady` function to determine if the Unleash client has successfully initialized and feature toggles are available for evaluation. This is crucial for preventing feature evaluations before the client is ready, ensuring correct application behavior. It can be used with polling or conditional logic. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); // Check readiness synchronously console.log('Ready before start:', unleash.isReady()); // false unleash.start(); // Polling pattern for readiness const checkReady = setInterval(() => { if (unleash.isReady()) { clearInterval(checkReady); console.log('Client is ready!'); initializeApp(); } }, 100); // Alternative: conditional rendering in React function FeatureComponent() { if (!unleash.isReady()) { return ; } return unleash.isEnabled('my-feature') ? : ; } ``` -------------------------------- ### Implement custom storage providers Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Shows how to provide a custom storage implementation to persist feature toggles locally, useful for bootstrapping in React Native environments. ```typescript import SharedPreferences from 'react-native-shared-preferences'; import { UnleashClient } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://eu.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-key', appName: 'my-webapp', storageProvider: { save: (name: string, data: any) => SharedPreferences.setItem(name, data), get: (name: string) => SharedPreferences.getItem(name, (val) => val) }, }); ``` ```typescript import AsyncStorage from '@react-native-async-storage/async-storage'; import { UnleashClient } from 'unleash-proxy-client'; const PREFIX = 'unleash:repository'; const unleash = new UnleashClient({ url: 'https://eu.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-key', appName: 'my-webapp', storageProvider: { save: (name: string, data: any) => { const repo = JSON.stringify(data); const key = `${PREFIX}:${name}`; return AsyncStorage.setItem(key, repo); }, get: (name: string) => { const key = `${PREFIX}:${name}`; const data = await AsyncStorage.getItem(key); return data ? JSON.parse(data) : undefined; } }, }); ``` -------------------------------- ### updateToggles() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Manually triggers a fetch of feature toggles from the server. ```APIDOC ## updateToggles() ### Description Manually triggers a fetch of feature toggles from the server. Useful when automatic refresh is disabled or when you need to ensure toggles are up-to-date after a specific action. ### Method SDK Method ### Request Example ```javascript await unleash.updateToggles(); ``` ### Response - **Promise** - Resolves when the toggles have been successfully fetched and updated. ``` -------------------------------- ### Subscribe to Unleash events Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Demonstrates how to listen for feature toggle updates using the EventEmitter pattern. Listeners should be registered before calling unleash.start() to ensure no events are missed. ```javascript unleash.on('update', () => { const myToggle = unleash.isEnabled('js.demo'); //do something useful }); ``` -------------------------------- ### Define and Collect Custom Metrics with Unleash JS SDK Source: https://context7.com/unleash/unleash-js-sdk/llms.txt This snippet demonstrates how to define and collect custom metrics like counters and histograms using the Unleash JavaScript SDK. It covers defining metrics, incrementing counters, observing histogram values, and handling potential warnings from the metrics API. Ensure the Unleash client is initialized with valid configuration. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); await unleash.start(); // Define custom metrics unleash.impactMetrics.defineCounter('checkout_clicks', 'Number of checkout button clicks'); unleash.impactMetrics.defineCounter('errors_total', 'Total errors encountered'); unleash.impactMetrics.defineHistogram('response_time_seconds', 'API response times', [0.1, 0.5, 1, 2, 5]); unleash.impactMetrics.defineHistogram('page_load_seconds', 'Page load duration', [0.5, 1, 2, 5, 10]); // Increment counters document.getElementById('checkout').addEventListener('click', () => { unleash.impactMetrics.incrementCounter('checkout_clicks'); }); // Track errors window.addEventListener('error', () => { unleash.impactMetrics.incrementCounter('errors_total'); }); // Observe histogram values async function fetchData() { const start = performance.now(); try { const response = await fetch('/api/data'); const duration = (performance.now() - start) / 1000; unleash.impactMetrics.observeHistogram('response_time_seconds', duration); return response.json(); } catch (error) { unleash.impactMetrics.incrementCounter('errors_total'); throw error; } } // Measure page load time window.addEventListener('load', () => { const loadTime = performance.timing.loadEventEnd - performance.timing.navigationStart; unleash.impactMetrics.observeHistogram('page_load_seconds', loadTime / 1000); }); // Listen for warning events from metrics API unleash.impactMetrics.on('warn', (message) => { console.warn('Metrics warning:', message); }); ``` -------------------------------- ### stop() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Stops the client, clearing timers and halting metrics reporting. ```APIDOC ## Method: stop() ### Description Stops the Unleash client, clearing the background polling timer and stopping metrics reporting. Useful for cleanup during component unmounting or application shutdown. ### Method VOID ### Response #### Success Response (200) - **void** - The client has been successfully stopped. ``` -------------------------------- ### Manually Send Metrics with Unleash JS SDK Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Demonstrates how to manually trigger the sending of accumulated usage metrics to the Unleash server using the `sendMetrics` function. This is useful for ensuring metrics are sent before a page unloads or when automatic intervals are disabled. It requires an initialized `UnleashClient` instance. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', metricsInterval: 0 // Disable automatic metrics }); unleash.on('sent', (payload) => { console.log('Metrics sent:', payload.bucket.toggles); }); await unleash.start(); // Evaluate some features for (let i = 0; i < 100; i++) { unleash.isEnabled('feature-a'); unleash.getVariant('experiment-b'); } // Manually send accumulated metrics await unleash.sendMetrics(); // Output: Metrics sent: { 'feature-a': { yes: 50, no: 50, variants: {} }, 'experiment-b': { ... } } // Send metrics before page unload window.addEventListener('beforeunload', () => { unleash.sendMetrics(); }); ``` -------------------------------- ### getContext() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Retrieves a copy of the current Unleash context object. ```APIDOC ## getContext() ### Description Returns a copy of the current Unleash context object. Useful for debugging or displaying the current evaluation context. ### Method SDK Method ### Response - **Object** - A copy of the current context including appName, environment, and properties. ### Response Example { "appName": "my-webapp", "environment": "production", "userId": "user-123", "properties": { "plan": "enterprise" } } ``` -------------------------------- ### Configure Unleash for Node.js Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Configures the Unleash client for Node.js environments, requiring a custom fetch implementation and an explicit storage provider. ```javascript import fetch from 'node-fetch'; import { UnleashClient, InMemoryStorageProvider } from 'unleash-proxy-client'; const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: '', appName: 'nodejs-proxy', storageProvider: new InMemoryStorageProvider(), fetch, }); await unleash.start(); const isEnabled = unleash.isEnabled('proxy.demo'); console.log(isEnabled); ``` -------------------------------- ### Update and Set Context Fields in Unleash JS SDK Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Demonstrates how to replace the entire context using updateContext and how to modify a specific field using setContextField. These methods ensure that feature evaluation reflects the current user attributes. ```javascript unleash.updateContext({ userId: '1233' }); unleash.setContextField('userId', '4141'); ``` -------------------------------- ### Evaluate Feature Toggles and Variants Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Demonstrates checking the status of a feature toggle using isEnabled and retrieving specific feature variants using getVariant. ```javascript // Check if a feature is enabled unleash.isEnabled('js.demo'); // Get a feature variant const variant = unleash.getVariant('proxy.demo'); if (variant.name === 'blue') { // something with variant blue... } ``` -------------------------------- ### Manually Update Unleash Toggles in JavaScript Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Manually triggers a fetch of feature toggles from the server. This is useful when automatic refresh is disabled or when you need to ensure toggles are up-to-date after a specific action. Requires an initialized UnleashClient, potentially with refresh disabled. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', disableRefresh: true // Manual refresh only }); await unleash.start(); // Manually fetch toggles when needed document.getElementById('refresh-btn').addEventListener('click', async () => { console.log('Refreshing feature flags...'); await unleash.updateToggles(); console.log('Flags refreshed'); // Re-check features after refresh const newFeature = unleash.isEnabled('new-feature'); updateUI(newFeature); }); // Refresh before critical operations async function processPayment() { await unleash.updateToggles(); if (unleash.isEnabled('new-payment-flow')) { return newPaymentProcessor(); } return legacyPaymentProcessor(); } ``` -------------------------------- ### Retrieve Feature Variant Configuration with getVariant() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Retrieves the variant configuration for an enabled feature toggle using the `getVariant` method. It returns a variant object with name, enabled status, and optional payload. If the toggle is disabled or lacks variants, it returns a default disabled variant. Dependencies include UnleashClient initialization and the 'ready' event. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); unleash.on('ready', () => { // Get variant for A/B testing const variant = unleash.getVariant('checkout-button-experiment'); console.log('Variant:', variant); // Output: { name: 'blue', enabled: true, feature_enabled: true, payload: { type: 'string', value: '#0066cc' } } // Apply variant-specific styling switch (variant.name) { case 'blue': document.getElementById('checkout').style.backgroundColor = '#0066cc'; break; case 'green': document.getElementById('checkout').style.backgroundColor = '#00cc66'; break; case 'disabled': // Use default styling break; } // Handle variant payload if (variant.payload) { const payloadValue = variant.payload.value; if (variant.payload.type === 'json') { const config = JSON.parse(payloadValue); console.log('Variant config:', config); } } }); await unleash.start(); ``` -------------------------------- ### Set Unleash Context Field in JavaScript Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Sets a single field in the Unleash context without replacing the entire context object. Supports predefined fields like userId and custom properties. Triggers a toggle refresh after updating. Requires the UnleashClient to be initialized. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); await unleash.start(); // Set predefined context fields await unleash.setContextField('userId', 'user-67890'); await unleash.setContextField('sessionId', 'session-abc123'); // Set custom properties (stored in context.properties) await unleash.setContextField('subscriptionTier', 'gold'); await unleash.setContextField('region', 'us-east-1'); await unleash.setContextField('deviceType', 'mobile'); // Get current context to verify const context = unleash.getContext(); console.log('Current context:', context); ``` -------------------------------- ### setContextField(field, value) Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Updates a specific field in the Unleash context and triggers a toggle refresh. ```APIDOC ## setContextField(field, value) ### Description Sets a single field in the Unleash context without replacing the entire object. Supports predefined fields and custom properties. Triggers a toggle refresh after updating. ### Method SDK Method ### Parameters - **field** (string) - Required - The name of the context field (e.g., 'userId', 'sessionId', or custom property). - **value** (any) - Required - The value to assign to the field. ### Request Example ```javascript await unleash.setContextField('userId', 'user-67890'); await unleash.setContextField('subscriptionTier', 'gold'); ``` ### Response - **void** - Returns nothing; updates the internal client state. ``` -------------------------------- ### Check Feature Toggle Status with isEnabled() Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Checks if a feature toggle is enabled for the current context using the `isEnabled` method. It automatically counts metrics and emits impression events if configured. Dependencies include the UnleashClient initialization. It returns a boolean indicating the toggle's state. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp' }); unleash.on('ready', () => { // Check if a feature is enabled if (unleash.isEnabled('new-checkout-flow')) { // Show new checkout experience console.log('New checkout flow is enabled'); } else { // Show legacy checkout console.log('Using legacy checkout'); } // Multiple feature checks const darkMode = unleash.isEnabled('dark-mode'); const betaFeatures = unleash.isEnabled('beta-features'); const aiAssistant = unleash.isEnabled('ai-assistant'); console.log({ darkMode, betaFeatures, aiAssistant }); }); await unleash.start(); ``` -------------------------------- ### Stop the Unleash client Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Stops the SDK from checking for updates or sending metrics. The client can be restarted later if needed. ```javascript unleash.stop() ``` -------------------------------- ### Retrieve Last Error with Unleash JS SDK Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Details the usage of the `getError` function to retrieve the last error encountered by the Unleash client. This is essential for diagnosing connection problems or other issues that might prevent feature toggles from being fetched or evaluated correctly. The function returns `undefined` if the client is healthy. ```javascript const unleash = new UnleashClient({ url: 'https://invalid-url.example.com/api/frontend', clientKey: 'invalid-token', appName: 'my-webapp' }); unleash.on('error', (error) => { console.error('Error event:', error); }); await unleash.start(); // Check for errors after initialization const error = unleash.getError(); if (error) { console.error('Client error:', error); // Handle error state - e.g., show fallback UI // error might be: { type: 'HttpError', code: 401 } // or: { type: 'fetch-toggles', error: Error } } // Conditional behavior based on client health function getFeatureState(toggleName) { if (unleash.getError()) { console.warn('Using default value due to client error'); return false; // Safe default } return unleash.isEnabled(toggleName); } ``` -------------------------------- ### removeContextField(field) Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Removes a specific field from the Unleash context and triggers a toggle refresh. ```APIDOC ## removeContextField(field) ### Description Removes a single field from the Unleash context. Works with both predefined fields and custom properties. Triggers a toggle refresh after the field is removed. ### Method SDK Method ### Parameters - **field** (string) - Required - The name of the field to remove. ### Request Example ```javascript await unleash.removeContextField('userId'); ``` ### Response - **void** - Returns nothing; updates the internal client state. ``` -------------------------------- ### Remove Context Fields in Unleash JS SDK Source: https://github.com/unleash/unleash-js-sdk/blob/main/README.md Shows how to remove a specific property from the Unleash context using removeContextField without affecting other existing properties. ```javascript unleash.updateContext({ userId: '1233', sessionId: 'sessionNotAffected' }); unleash.removeContextField('userId'); ``` -------------------------------- ### Remove Unleash Context Field in JavaScript Source: https://context7.com/unleash/unleash-js-sdk/llms.txt Removes a single field from the Unleash context, working with both predefined fields and custom properties. Triggers a toggle refresh after the field is removed. Requires an initialized UnleashClient with a defined context. ```javascript const unleash = new UnleashClient({ url: 'https://app.unleash-hosted.com/demo/api/frontend', clientKey: 'your-frontend-token', appName: 'my-webapp', context: { userId: 'user-123', properties: { plan: 'premium', region: 'eu-west', betaTester: 'true' } } }); await unleash.start(); // User logs out - remove user identification await unleash.removeContextField('userId'); // Remove custom properties await unleash.removeContextField('betaTester'); // Verify context update const context = unleash.getContext(); console.log('Context after removal:', context); ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.