Gathering detailed insights and metrics for unleash-client
Gathering detailed insights and metrics for unleash-client
Gathering detailed insights and metrics for unleash-client
Gathering detailed insights and metrics for unleash-client
npm install unleash-client
Module System
Min. Node Version
Typescript Support
Node Version
NPM Version
213 Stars
902 Commits
73 Forks
23 Watching
74 Branches
58 Contributors
Updated on 21 Nov 2024
TypeScript (99.85%)
JavaScript (0.12%)
Shell (0.04%)
Cumulative downloads
Total Downloads
Last day
-1.8%
50,572
Compared to previous day
Last week
5.3%
243,834
Compared to previous week
Last month
10.8%
1,040,591
Compared to previous month
Last year
26.7%
10,659,835
Compared to previous year
34
The official Unleash client SDK for Node.js.
1npm install unleash-client
or
1yarn add unleash-client
(Or any other tool you like.)
unleash-client
Once installed, you must initialize the SDK in your application. By default, Unleash initialization is asynchronous, but if you need it to be synchronous, you can block until the SDK has synchronized with the server.
Note that until the SDK has synchronized with the API, all features will evaluate to false
unless
you a bootstrapped configuration.
💡 Tip: All code samples in this section will initialize the SDK and try to connect to the Unleash instance you point it to. You will need an Unleash instance and a server-side API token for the connection to be successful.
We recommend that you initialize the Unleash client SDK as early as possible in your application. The SDK will set up an in-memory repository and poll for updates from the Unleash server at regular intervals.
1import { initialize } from 'unleash-client'; 2 3const unleash = initialize({ 4 url: 'https://YOUR-API-URL', 5 appName: 'my-node-name', 6 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 7});
The initialize
function will configure a global Unleash instance. If you call this method
multiple times, the global instance will be changed. You will not create multiple instances.
Because the SDK takes care of talking to the server in the background, it can be difficult to know
exactly when it has connected and is ready to evaluate toggles. If you want to run some code when
the SDK becomes ready, you can listen for the 'synchronized'
event:
1unleash.on('synchronized', () => { 2 // the SDK has synchronized with the server 3 // and is ready to serve 4});
Refer to the events reference later in this document for more information on events and an exhaustive list of all the events the SDK can emit.
The initialize
function will configure and create a global Unleash instance. When a global
instance exists, calling this method has no effect. Call the destroy
function to remove the
globally configured instance.
You can also construct the Unleash instance yourself instead of via the initialize
method.
When using the Unleash client directly, you should not create new Unleash instances on every request. Most applications are expected to only have a single Unleash instance (singleton). Each Unleash instance will maintain a connection to the Unleash API, which may result in flooding the Unleash API.
1import { Unleash } from 'unleash-client'; 2 3const unleash = new Unleash({ 4 url: 'https://YOUR-API-URL', 5 appName: 'my-node-name', 6 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 7}); 8 9unleash.on('ready', console.log.bind(console, 'ready')); 10 11// optional error handling when using unleash directly 12unleash.on('error', console.error);
You can also use the startUnleash
function and await
to wait for the SDK to have fully
synchronized with the Unleash API. This guarantees that the SDK is not operating on local and
potentially stale feature toggle configuration.
1import { startUnleash } from 'unleash-client'; 2 3const unleash = await startUnleash({ 4 url: 'https://YOUR-API-URL', 5 appName: 'my-node-name', 6 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 7}); 8 9// Unleash SDK has now fresh state from the unleash-api 10const isEnabled = unleash.isEnabled('Demo');
With the SDK initialized, you can use it to check the states of your feature toggles in your application.
The primary way to check feature toggle status is to use the isEnabled
method on the SDK. It takes
the name of the feature and returns true
or false
based on whether the feature is enabled or
not.
1setInterval(() => { 2 if (unleash.isEnabled('DemoToggle')) { 3 console.log('Toggle enabled'); 4 } else { 5 console.log('Toggle disabled'); 6 } 7}, 1000);
👀 Note: In this example, we've wrapped the isEnabled
call inside a setInterval
function. In
the event that all your app does is to start the SDK and check a feature status, this is will keep a
node app running until the SDK has synchronized with the Unleash API. It is not required in
normal apps.
You can use the getVariant
method to retrieve the variant of a feature flag. If the flag is disabled or
doesn't have any variants, the method returns the
disabled variant.
1const variant = unleash.getVariant('demo-variant'); 2 3if (variant.name === 'blue') { 4 // do something with the blue variant... 5}
Calling the isEnabled
method with just a feature name will work in simple use cases, but in many
cases you'll also want to provide an
Unleash context. The SDK uses the Unleash
context to evaluate any
activation strategy with
strategy constraints, and also to
evaluate some of the built-in strategies.
The isEnabled
accepts an Unleash context object as a second argument:
1const unleashContext = { 2 userId: '123', 3 sessionId: 'some-session-id', 4 remoteAddress: '127.0.0.1', 5 properties: { 6 region: 'EMEA', 7 }, 8}; 9 10const enabled = unleash.isEnabled('someToggle', unleashContext);
To shut down the client (turn off the polling) you can simply call the destroy-method. This is typically not required.
1import { destroy } from 'unleash-client'; 2destroy();
The client comes supports all built-in activation strategies provided by Unleash.
Read more about activation strategies in the official docs.
In order to use some of the common activation strategies you must provide an
Unleash context. This client SDK allows you
to send in the unleash context as part of the isEnabled
call:
1const unleashContext = { 2 userId: '123', 3 sessionId: 'some-session-id', 4 remoteAddress: '127.0.0.1', 5}; 6unleash.isEnabled('someToggle', unleashContext);
The initialize method takes the following arguments:
environment
property. Automatically
populated in the Unleash Context (optional). This does not set the SDK's
Unleash environment.customHeaders
option.rejectUnauthorized
- be careful with these
options as they may compromise your application security.[{type: 'simple', value: 'proxy'}]
.1import { initialize, Strategy } from 'unleash-client'; 2class ActiveForUserWithEmailStrategy extends Strategy { 3 constructor() { 4 super('ActiveForUserWithEmail'); 5 } 6 7 isEnabled(parameters, context) { 8 return parameters.emails.indexOf(context.email) !== -1; 9 } 10}
1initialize({ 2 url: 'http://unleash.herokuapp.com', 3 customHeaders: { 4 Authorization: 'API token', 5 }, 6 strategies: [new ActiveForUserWithEmailStrategy()], 7});
The unleash instance object implements the EventEmitter class and emits the following events:
event | payload | description |
---|---|---|
ready | - | is emitted once the fs-cache is ready. if no cache file exists it will still be emitted. The client is ready to use, but might not have synchronized with the Unleash API yet. This means the SDK still can operate on stale configurations. |
synchronized | - | is emitted when the SDK has successfully synchronized with the Unleash API, or when it has been bootstrapped, and has all the latest feature toggle configuration available. |
registered | - | is emitted after the app has been registered at the api server |
sent | object data | key/value pair of delivered metrics |
count | string name, boolean enabled | is emitted when a feature is evaluated |
warn | string msg | is emitted on a warning |
error | Error err | is emitted on a error |
unchanged | - | is emitted each time the client gets new toggle state from server, but nothing has changed |
changed | object data | is emitted each time the client gets new toggle state from server and changes has been made |
impression | object data | is emitted for every user impression (isEnabled / getVariant) |
Example usage:
1import { initialize } from 'unleash-client'; 2 3const unleash = initialize({ 4 appName: 'my-app-name', 5 url: 'http://unleash.herokuapp.com/api/', 6 customHeaders: { 7 Authorization: 'API token', 8 }, 9}); 10 11// Some useful life-cycle events 12unleash.on('ready', console.log); 13unleash.on('synchronized', console.log); 14unleash.on('error', console.error); 15unleash.on('warn', console.warn); 16 17unleash.once('registered', () => { 18 // Do something after the client has registered with the server api. 19 // NB! It might not have received updated feature toggles yet. 20}); 21 22unleash.once('changed', () => { 23 console.log(`Demo is enabled: ${unleash.isEnabled('Demo')}`); 24}); 25 26unleash.on('count', (name, enabled) => console.log(`isEnabled(${name})`));
(Available from v3.11.x)
The Node.js SDK supports a bootstrap parameter, allowing you to load the initial feature toggle
configuration from somewhere else than the Unleash API. The bootstrap data
can be provided as an
argument directly to the SDK, as a filePath
to load or as a url
to fetch the content from.
Bootstrap is a convenient way to increase resilience, where the SDK can still load fresh toggle
configuration from the bootstrap location, even if the Unleash API should be unavailable at startup.
1. Bootstrap with data passed as an argument
1const client = initialize({ 2 appName: 'my-application', 3 url: 'https://app.unleash-hosted2.com/demo/api/', 4 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 5 bootstrap: { 6 data: [ 7 { 8 enabled: false, 9 name: 'BootstrapDemo', 10 description: '', 11 project: 'default', 12 stale: false, 13 type: 'release', 14 variants: [], 15 strategies: [{ name: 'default' }], 16 }, 17 ], 18 }, 19});
2. Bootstrap via a URL
1const client = initialize({ 2 appName: 'my-application', 3 url: 'https://app.unleash-hosted.com/demo/api/', 4 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 5 bootstrap: { 6 url: 'http://localhost:3000/proxy/client/features', 7 urlHeaders: { 8 Authorization: 'bootstrap', 9 }, 10 }, 11});
3. Bootstrap from a File
1const client = initialize({ 2 appName: 'my-application', 3 url: 'https://app.unleash-hosted.com/demo/api/', 4 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 5 bootstrap: { 6 filePath: '/tmp/some-bootstrap.json', 7 }, 8});
Sometimes you might be interested in the raw feature toggle definitions.
1import { 2 initialize, 3 getFeatureToggleDefinition, 4 getFeatureToggleDefinitions, 5} from 'unleash-client'; 6 7initialize({ 8 url: 'http://unleash.herokuapp.com/api/', 9 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 10 appName: 'my-app-name', 11 instanceId: 'my-unique-instance-id', 12}); 13 14const featureToggleX = getFeatureToggleDefinition('app.ToggleX'); 15const featureToggles = getFeatureToggleDefinitions();
(Available from v3.11.x)
By default this SDK will use a store provider that writes a backup of the feature toggle configuration to a file on disk. This happens every time it receives updated configuration from the Unleash API. You can swap out the store provider with either the provided in-memory store provider or a custom store provider implemented by you.
1. Use InMemStorageProvider
1import { initialize, InMemStorageProvider } from 'unleash-client'; 2 3const client = initialize({ 4 appName: 'my-application', 5 url: 'http://localhost:3000/api/', 6 customHeaders: { Authorization: '<YOUR_API_TOKEN>' }, 7 storageProvider: new InMemStorageProvider(), 8});
2. Custom Store Provider backed by redis
1import { initialize, InMemStorageProvider } from 'unleash-client'; 2 3import { createClient } from 'redis'; 4 5class CustomRedisStore { 6 async set(key, data) { 7 const client = createClient(); 8 await client.connect(); 9 await client.set(key, JSON.stringify(data)); 10 } 11 async get(key) { 12 const client = createClient(); 13 await client.connect(); 14 const data = await client.get(key); 15 return JSON.parse(data); 16 } 17} 18 19const client = initialize({ 20 appName: 'my-application', 21 url: 'http://localhost:3000/api/', 22 customHeaders: { 23 Authorization: 'my-key', 24 }, 25 storageProvider: new CustomRedisStore(), 26});
You can manage the underlying data layer yourself if you want to. This enables you to use unleash offline, from a browser environment or implement your own caching layer. See example.
Unleash depends on a ready
event of the repository you pass in. Be sure that you emit the event
after you've initialized unleash.
You can connect to the Unleash API through the corporate proxy by setting one of the environment
variables: HTTP_PROXY
or HTTPS_PROXY
This feature flag SDK is designed according to our design philosophy. You can read more about that here.
No vulnerabilities found.
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
Reason
Found 14/24 approved changesets -- score normalized to 5
Reason
5 commit(s) and 1 issue activity found in the last 90 days -- score normalized to 5
Reason
6 existing vulnerabilities detected
Details
Reason
detected GitHub workflow tokens with excessive permissions
Details
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
project is not fuzzed
Details
Reason
security policy file not detected
Details
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
Score
Last Scanned on 2024-11-25
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn More