Javascript (Web)

The Hyphen Toggle Provider for Javascript is an OpenFeature provider implementation that enables seamless feature flag evaluation. This section covers setup, usage, and configuration specific to the JavaScript implementation.

Installation

Install the provider and the OpenFeature server SDK:

npm install @openfeature/web-sdk @hyphen/openfeature-web-provider

Setup and Initialization

To begin using the Hyphen Provider, follow these steps:

  1. Import the required modules.
  2. Configure the provider with your publicKey and application options.
  3. Register the provider with OpenFeature.
import { OpenFeature } from '@openfeature/web-sdk';  
import { HyphenProvider, type HyphenProviderOptions } from '@hyphen/openfeature-web-provider';

const publicKey = "your-public-key-here";

const options: HyphenProviderOptions = {  
  application: 'your-application-name',  
  environment: 'production',  
};

await OpenFeature.setProviderAndWait(new HyphenProvider(publicKey, options));

Context

Use OpenFeature.setContext to configure the required context for feature targeting evaluations, incorporating user or application context.

const context: HyphenEvaluationContext = {  
  targetingKey: 'user-123',  
  ipAddress: '203.0.113.42',  
  customAttributes: {  
    subscriptionLevel: 'premium',  
    region: 'us-east',  
  },  
  user: {  
    id: 'user-123',  
    email: 'john.doe@example.com',  
    name: 'John Doe',  
    customAttributes: {  
      role: 'admin',  
    },  
  },  
};

OpenFeature.setContext(context);

Feature Evaluation

Use the OpenFeature.getClient() to evaluate feature flags in your application.

const client = OpenFeature.getClient();
const isEnabled = client.getBooleanDetails('your-flag-key', false);
console.log('isEnabled', isEnabled) // true or false

Configuration

Options

OptionTypeDescription
applicationstringThe application id or alternate ID.
environmentstringThe environment in which your application is running (e.g., production, staging).
enableToggleUsagebooleanEnable or disable the logging of toggle usage (telemetry).

Context

Provide an EvaluationContext to pass contextual data for feature evaluation.

Context Fields

FieldTypeDescription
targetingKeystringThe key used for caching the evaluation response.
ipAddressstringThe IP address of the user making the request.
customAttributesRecord<string, any>Custom attributes for additional contextual information.
userobjectAn object containing user-specific information for the evaluation.
user.idstringThe unique identifier of the user.
user.emailstringThe email address of the user.
user.namestringThe name of the user.
user.customAttributesRecord<string, any>Custom attributes specific to the user.