- Notifications
You must be signed in to change notification settings - Fork71
Unleash client SDK for Node.js
License
Unleash/unleash-node-sdk
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Unleash is a private, secure, and scalablefeature management platformbuilt to reduce the risk of releasing new features and accelerate software development. Thisserver-side Node.js SDK is designed to help you integrate with Unleash and evaluate feature flagsinside your application.
You can use this client withUnleash Enterprise orUnleash Open Source.
npm install unleash-client
or
yarn add unleash-client
(Or any other tool you like.)
Once installed, you must initialize the SDK in your application. By default, Unleash initializationis asynchronous, but if you need it to be synchronous, you canblock until the SDK has synchronized with the server.
Note that until the SDK has synchronized with the API, all features will evaluate tofalse unlessyou have abootstrapped configuration.
💡Tip: All code samples in this section will initialize the SDK and try to connect to theUnleash instance you point it to. You will need an Unleash instance and aserver-side API tokenfor the connection to be successful.
We recommend that you initialize the Unleash client SDKas early as possible in yourapplication. The SDK will set up an in-memory repository and poll for updates from the Unleashserver at regular intervals.
import{initialize}from'unleash-client';constunleash=initialize({url:'https://YOUR-API-URL',appName:'my-node-name',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},});
Theinitialize function will configure aglobal Unleash instance. If you call this methodmultiple times, the global instance will be changed. You willnot create multiple instances.
Because the SDK takes care of talking to the server in the background, it can be difficult to knowexactly when it has connected and is ready to evaluate toggles. If you want to run some code whenthe SDK becomes ready, you can listen for the'synchronized' event:
unleash.on('synchronized',()=>{// the SDK has synchronized with the server// and is ready to serve});
Refer to theevents reference later in this document for more information on events andan exhaustive list of all the events the SDK can emit.
Theinitialize function will configure and create aglobal Unleash instance. When a globalinstance exists, calling this method has no effect. Call thedestroy function to remove theglobally configured instance.
You can also construct the Unleash instance yourself instead of via theinitialize method.
When using the Unleash client directly, youshould not create new Unleash instances on everyrequest. Most applications are expected to only have a single Unleash instance (singleton). EachUnleash instance will maintain a connection to the Unleash API, which may result in flooding theUnleash API.
import{Unleash}from'unleash-client';constunleash=newUnleash({url:'https://YOUR-API-URL',appName:'my-node-name',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},});unleash.on('ready',console.log.bind(console,'ready'));// optional error handling when using unleash directlyunleash.on('error',console.error);
You can also use thestartUnleash function andawait to wait for the SDK to have fullysynchronized with the Unleash API. This guarantees that the SDK is not operating on local andpotentially stale feature toggle configuration.
import{startUnleash}from'unleash-client';constunleash=awaitstartUnleash({url:'https://YOUR-API-URL',appName:'my-node-name',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},});// The Unleash SDK now has a fresh state from the Unleash APIconstisEnabled=unleash.isEnabled('Demo');
With the SDK initialized, you can use it to check the states of your feature toggles in yourapplication.
The primary way to check feature toggle status is to use theisEnabled method on the SDK. It takesthe name of the feature and returnstrue orfalse based on whether the feature is enabled ornot.
setInterval(()=>{if(unleash.isEnabled('DemoToggle')){console.log('Toggle enabled');}else{console.log('Toggle disabled');}},1000);
👀Note: In this example, we've wrapped theisEnabled call inside asetInterval function. Inthe event that all your app does is start the SDK and check a feature status, this setup ensuresthat the node app keeps running until the SDK has synchronized with the Unleash API. It isnotrequired in normal apps.
You can use thegetVariant method to retrieve the variant of a feature flag. If the flag isdisabled or doesn't have any variants, the method returns thedisabled variant.
constvariant=unleash.getVariant('demo-variant');if(variant.name==='blue'){// do something with the blue variant...}
Calling theisEnabled method with just a feature name will work in simple use cases, but in manycases you'll also want to provide anUnleash context. The SDK uses the Unleashcontext to evaluate anyactivation strategy withstrategy constraints, and also toevaluate some of the built-in strategies.
TheisEnabled accepts an Unleash context object as a second argument:
constunleashContext={userId:'123',sessionId:'some-session-id',remoteAddress:'127.0.0.1',properties:{region:'EMEA',},};constenabled=unleash.isEnabled('someToggle',unleashContext);
To shut down the client (turn off the polling) you can simply call thedestroy method. This istypically not required.
import{destroy}from'unleash-client';destroy();
The client supports all built-in activation strategies provided by Unleash.
Read more aboutactivation strategies in the official docs.
In order to use some of the common activation strategies you must provide anUnleash context. This client SDK allows youto send in the unleash context as part of theisEnabled call:
constunleashContext={userId:'123',sessionId:'some-session-id',remoteAddress:'127.0.0.1',};unleash.isEnabled('someToggle',unleashContext);
You can use TypeScript module augmentation to provide type safety for your feature toggle names.This ensures that only specific feature names can be used withisEnabled and related methods,catching typos at compile time.
import{initialize}from'unleash-client';declare module'unleash-client'{interfaceUnleashTypes{flagNames:'aaa'|'bbb';}}constclient=initialize({});client.isEnabled('aaa');client.isEnabled('bbb');client.isEnabled('ccc');// Error
The initialize method takes the following arguments:
- url - The url to fetch toggles from (required).
- appName - The application name / codebase name (required).
- environment - The value to put in the Unleash context's
environmentproperty. Automaticallypopulated in the Unleash Context (optional). This doesnot set the SDK'sUnleash environment. - instanceId - A unique identifier, should/could be somewhat unique.
- refreshInterval - The poll interval to check for updates. Defaults to 15000ms.
- metricsInterval - How often the client should send metrics to Unleash API. Defaults to60000ms.
- strategies - Custom activation strategies to be used.
- disableMetrics - Disable metrics.
- customHeaders - Provide a map(object) of custom headers to be sent to the unleash-server.
- customHeadersFunction - Provide a function that returns a Promise resolving as custom headersto be sent to unleash-server. When options are set, this will take precedence over
customHeadersoption. - timeout - Specify a timeout in milliseconds for outgoing HTTP requests. Defaults to 10000ms.
- repository - Provide a custom repository implementation to manage the underlying data.
- httpOptions - Provide custom HTTP options such as
rejectUnauthorized- be careful with theseoptions as they may compromise your application security. - namePrefix - Only fetch feature toggles with the provided name prefix.
- tags - Only fetch feature toggles tagged with the list of tags, such as:
[{type: 'simple', value: 'proxy'}].
import{initialize,Strategy}from'unleash-client';classActiveForUserWithEmailStrategyextendsStrategy{constructor(){super('ActiveForUserWithEmail');}isEnabled(parameters,context){returnparameters.emails.indexOf(context.email)!==-1;}}
initialize({url:'http://unleash.herokuapp.com',customHeaders:{Authorization:'API token',},strategies:[newActiveForUserWithEmailStrategy()],});
The unleash instance object implements the EventEmitter class andemits 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 an 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 have been made |
| impression | object data | is emitted for every user impression (isEnabled / getVariant) |
Example usage:
import{initialize}from'unleash-client';constunleash=initialize({appName:'my-app-name',url:'http://unleash.herokuapp.com/api/',customHeaders:{Authorization:'API token',},});// Some useful life-cycle eventsunleash.on('ready',console.log);unleash.on('synchronized',console.log);unleash.on('error',console.error);unleash.on('warn',console.warn);unleash.once('registered',()=>{// Do something after the client has registered with the server API.// Note: it might not have received updated feature toggles yet.});unleash.once('changed',()=>{console.log(`Demo is enabled:${unleash.isEnabled('Demo')}`);});unleash.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 toggleconfiguration from somewhere else than the Unleash API. The bootstrapdata can be provided as anargument directly to the SDK, as afilePath to load, or as aurl to fetch the content from.Bootstrap is a convenient way to increase resilience, where the SDK can still load fresh toggleconfiguration from the bootstrap location, even if the Unleash API should be unavailable at startup.
constclient=initialize({appName:'my-application',url:'https://app.unleash-hosted2.com/demo/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},bootstrap:{data:[{enabled:false,name:'BootstrapDemo',description:'',project:'default',stale:false,type:'release',variants:[],strategies:[{name:'default'}],},],},});
constclient=initialize({appName:'my-application',url:'https://app.unleash-hosted.com/demo/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},bootstrap:{url:'http://localhost:3000/proxy/client/features',urlHeaders:{Authorization:'bootstrap',},},});
constclient=initialize({appName:'my-application',url:'https://app.unleash-hosted.com/demo/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},bootstrap:{filePath:'/tmp/some-bootstrap.json',},});
Sometimes you might be interested in the raw feature toggle definitions.
import{initialize,getFeatureToggleDefinition,getFeatureToggleDefinitions,}from'unleash-client';initialize({url:'http://unleash.herokuapp.com/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},appName:'my-app-name',instanceId:'my-unique-instance-id',});constfeatureToggleX=getFeatureToggleDefinition('app.ToggleX');constfeatureToggles=getFeatureToggleDefinitions();
(Available from v3.11.x)
By default, this SDK will use a store provider that writes a backup of the feature toggleconfiguration to afile on disk. This happens every time it receives updated configuration fromthe Unleash API. You can swap out the store provider with either the provided in-memory storeprovider or a custom store provider implemented by you.
import{initialize,InMemStorageProvider}from'unleash-client';constclient=initialize({appName:'my-application',url:'http://localhost:3000/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},storageProvider:newInMemStorageProvider(),});
import{initialize,InMemStorageProvider}from'unleash-client';import{createClient}from'redis';classCustomRedisStore{asyncset(key,data){constclient=createClient();awaitclient.connect();awaitclient.set(key,JSON.stringify(data));}asyncget(key){constclient=createClient();awaitclient.connect();constdata=awaitclient.get(key);returnJSON.parse(data);}}constclient=initialize({appName:'my-application',url:'http://localhost:3000/api/',customHeaders:{Authorization:'my-key',},storageProvider:newCustomRedisStore(),});
You can manage the underlying data layer yourself if you want to. This enables you to use Unleashoffline, from a browser environment, or by implement your own caching layer. Seeexample.
Unleash depends on aready event of the repository you pass in. Be sure that you emit the eventafter you've initialized Unleash.
You can connect to the Unleash API through the corporate proxy by setting one of the environmentvariables:HTTP_PROXY orHTTPS_PROXY.
This feature flag SDK is designed according to our design philosophy. You canread more about that here.
About
Unleash client SDK for Node.js
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.