Skip to content

JavaScript SDK

The @featureboard/js-sdk is a FeatureBoard SDK for browser based web applications.

Prerequisites

Before using @featureboard/js-sdk you will need to have a valid environmentApiKey. To locate the Environment API Key, simply go to the “Product Settings” section and copy the key for your environment.

Installation

The FeatureBoard JavaScript SDK is available on NPM.

Terminal window
npm add @featureboard/js-sdk
# Or
yarn add @featureboard/js-sdk
# Or
pnpm add @featureboard/js-sdk

Setup

To integrate feature toggles you need to create and configure the browser client for FeatureBoard. The browser client is created for a specific environment and the environment api key you can find by navigating to the “Product Settings” section. Furthermore, you have to provide a list of audience keys for the current user or application context. Audiences can be updated subsequent to the creation of the browser client. In such cases, the instance will be re-initialised.

import { createBrowserClient } from '@featureboard/js-sdk'
const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
updateStrategy: 'polling',
audiences: ['audience-key'],
initialValues: undefined,
api: undefined,
})

Input Parameters

  • environmentApiKey- Specifies the environment api key for the environment.
  • updateStrategy- Configure preferred update strategy. The default strategy is polling at 30-second interval.
  • audiences- Specifies a list of audience keys the browser client will be initialised with.
  • initialValues- Provides the option to set initial effective feature values.
  • api- Provides the option to connect to a self-hosted instance of FeatureBoard.

Return Properties

Returns a BrowserClient object.

  • client - The FeatureBoard client.
  • initialised - Returns true once the FeatureBoard SDK has a valid set of feature values.
  • waitForInitialised() - Waits for the browser client to be initialised. If initialisation fails an error is thrown.
  • subscribeToInitialisedChange() - Subscribes to initialised changes, will call back with initialised boolean value. Recommended to be used in conjunction with updateAudiences.
  • updateAudiences() - Update audiences and sets initialised to false until new effective feature values are loaded.
  • updateFeatures() - Manually trigger the feature state store to update.
  • close() - Close the subscription to the FeatureBoard service.

Configuration Options

Choose Update Strategy

You have the options to set what update strategy to use by configure the updateStrategy input parameter. FeatureBoard JS-SDK supports following update strategies:

  • polling
  • manual updating

Default update strategy is polling at 30-second interval.

Polling

To use polling update strategy you can configure updateStrategy to 'polling' and the client will poll at the default 30-second interval. To change the interval, you need to set intervalMs in PollingOption.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
// Set update strategy to polling at 10-second interval
updateStrategy: { kind: 'polling', options: { intervalMs: 10000 } },
audiences: [''],
})
Manual

Should you wish to have more direct control over when features are updated, you configure 'updateStrategy' to 'manual'. To trigger the update process you utilise the updateFeature function.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
// Set update strategy to manual
updateStrategy: 'manual',
audiences: [''],
})
// Triggers an update of the feature state store
browserClient.updateFeatures()

Configure Initial Values

You can provide the browser client with initial effective feature values. This will allow you to use the SDK even if FeatureBoard would be unavailable or without waiting for initialisation to complete.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
audiences: ['admin', 'plan-large'],
initialValues: [
{
featureKey: 'write-permission'
value: true
},{
featureKey: 'limit-users'
value: 25
},
]
})

Note: Changing audiences by calling updateAudiences, will reset the internal feature state store.

Self Hosted Instance

By configuring the api input parameter you can connect to a shelf hosted instance of FeatureBoard.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
audiences: [''],
api: {
http: 'https://my-featureboard-endpoint'
ws: 'wss://my-websocket-featureboard-endpoint'
},
})

Wait For Initialised

Before you begin using the FeatureBoard client, it is important to ensure that the client has been initialised with feature values. You achieve this by awaiting the waitForInitialised function.

In the event that there’s a connection issue with FeatureBoard, the browser client will make retry attempts before raising an error. To handle this error, you can wrap the waitForInitialised function in a try-catch block. This way, you can handle any potential issues that might arise during the initialisation process.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
audiences: ['admin', 'plan-large'],
})
// Wait for the browser client to initialise
try {
await browserClient.waitForInitialised()
} catch (err: any) {
// An error occurred during initialisation
throw err
}
// Ready to use FeatureBoard client
const client = browserClient.client
// Close connection to FeatureBoard
browserClient.close()

There is an exception: if you have initialised the browser client with initial feature values, you can continue using the FeatureBoard client while the values are being updated.

Update Audiences

You can update the audiences in the browser client by using updateAudiences function with a new set of audience keys. This will trigger a reset of the internal feature state store and request a update of effective feature values from FeatureBoard. The initialised state will be set to true once the feature values for the new audience keys have been loaded.

We recommend to use subscribeToInitialisedChanged and waitForInitialised in conjunction with updateAudiences.

const browserClient = createBrowserClient({
environmentApiKey: 'my-environment-api-key',
audiences: [''],
})
// Subscribe to initialised changed
const unsubscribe = browserClient.subscribeToInitialisedChanged((initialised: boolean) => {
if (initialised) {
// client is initialised
} else {
// client is initialising
}
})
// Update audiences and wait for the feature store to update
try {
browserClient.updateAudiences(['admin', 'plan-large'])
await browserClient.waitForInitialised()
} catch (err: any) {
// An error occurred
throw err
}

Usages

To retrieve feature values, you will utilise the FeatureBoardClient obtained through the BrowserClient. You have two option for obtaining the feature value: you can request the current value by invoking getFeatureValue, or you can subscribe to receive the current value and subsequent updates.

Note: When using getFeatureValue or subscribeToFeatureValue, you must specify a default value. This value serves as a fallback when the feature is unavailable in the current environment.

Get Feature Value

The getFeatureValue function returns the feature value for a given feature. The default value is used as a fallback in cases where the feature is unavailable in the current environment.

// Get feature value
const featureValue = client.getFeatureValue('my-feature-key', defaultValue)

Subscribe to Feature Value

Upon subscribing to a feature value, an immediate callback will be triggered, providing the current feature value. To terminate the subscription, initiate the function returned during the subscription process.

// Subscribe to feature value changes
const unsubscribe = browserClient.client.subscribeToFeatureValue(
'my-feature-key',
defaultValue,
(value) => {
// Will be called with the initial value and subsequent updates
},
)
// Unsubscribe to feature value
unsubscribe()

Note: You must specify a default value, this value is used when the feature is unavailable in the current environment.

Effective Feature Values

The getEffectiveValues function retrieves both the audiences and a copy of the features stored within the internal state store.

// Get feature value
const { audiences, effectiveValues } = client.getEffectiveValues()

TypeScript

To get type safety on your features you can use Declaration Merging to define the features.

This can be done manually e.g.

import '@featureboard/js-sdk'
declare module '@featureboard/js-sdk' {
interface Features {
'my-boolean-feature-key': boolean
'my-option-feature-key': string
'my-number-feature-key': number
'my-string-feature-key': string
}
}

Or automatically via the cli tool

By running npx @featureboard/cli login, then npx @featureboard/cli code-gen --template typescript --output ./ to generate a features.ts file in the output path or update an existing one.

OR if you do not want to specify all your features the features you can just add:

declare module '@featureboard/js-sdk' {
interface Features extends Record<string, string | number | boolean> {}
}

Debugging

To enable debug logging, set the DEBUG environment variable to featureboard-sdk,featureboard-sdk:*.

Available scopes are:

  • featureboard-sdk
  • featureboard-sdk:http-client
  • featureboard-sdk:state-store
  • featureboard-sdk:updates
  • featureboard-sdk:updates:manual
  • featureboard-sdk:updates:polling

Manual Client

The JavaScript SDK enables you to create a manual client to use the FeatureBoard SDK without talking to the service. This can be useful for unit testing, getting started with FeatureBoard, local development and also if you no longer need the service to remove your reliance on the service without having to remove the SDK.

import { createManualClient } from '@featureboard/js-sdk'
const featureBoardClient = createManualClient({
audiences: ['my-audiences'],
values: {
'my-feature-key': false,
},
})