Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Unleash client SDK for Node.js

License

NotificationsYou must be signed in to change notification settings

Unleash/unleash-node-sdk

Repository files navigation

Unleash node SDK on npmnpm downloadsBuild StatusCode ClimateCoverage Status

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.

Getting started

1. Install the Unleash client in your project

npm install unleash-client

or

yarn add unleash-client

(Or any other tool you like.)

2. Initializeunleash-client

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.

How do I know when it's ready?

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.

Constructing the Unleash client directly

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);

Synchronous initialization

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');

3. Check features

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.

Check variants

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...}

Providing an Unleash context

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);

4. Stop unleash

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();

Built-in activation strategies

The client supports all built-in activation strategies provided by Unleash.

Read more aboutactivation strategies in the official docs.

Unleash context

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);

TypeScript: Custom Feature Toggle Names

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

Advanced usage

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'senvironment property. 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 overcustomHeadersoption.
  • 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 asrejectUnauthorized - 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'}].

Custom strategies

1. Implement the custom strategy

import{initialize,Strategy}from'unleash-client';classActiveForUserWithEmailStrategyextendsStrategy{constructor(){super('ActiveForUserWithEmail');}isEnabled(parameters,context){returnparameters.emails.indexOf(context.email)!==-1;}}

2. Register your custom strategy

initialize({url:'http://unleash.herokuapp.com',customHeaders:{Authorization:'API token',},strategies:[newActiveForUserWithEmailStrategy()],});

Events

The unleash instance object implements the EventEmitter class andemits the following events:

eventpayloaddescription
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
sentobject datakey/value pair of delivered metrics
countstring name,boolean enabledis emitted when a feature is evaluated
warnstring msgis emitted on a warning
errorError erris emitted on an error
unchanged-is emitted each time the client gets new toggle state from server, but nothing has changed
changedobject datais emitted each time the client gets new toggle state from server and changes have been made
impressionobject datais 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})`));

Bootstrap

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.

1. Bootstrap with data passed as an argument

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'}],},],},});

2. Bootstrap via a URL

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',},},});

3. Bootstrap from a file

constclient=initialize({appName:'my-application',url:'https://app.unleash-hosted.com/demo/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},bootstrap:{filePath:'/tmp/some-bootstrap.json',},});

Toggle definitions

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();

Custom store provider

(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.

1. UseInMemStorageProvider

import{initialize,InMemStorageProvider}from'unleash-client';constclient=initialize({appName:'my-application',url:'http://localhost:3000/api/',customHeaders:{Authorization:'<YOUR_API_TOKEN>'},storageProvider:newInMemStorageProvider(),});

2. Custom store provider backed by Redis

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(),});

Custom repository

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.

Usage with HTTP and HTTPS proxies

You can connect to the Unleash API through the corporate proxy by setting one of the environmentvariables:HTTP_PROXY orHTTPS_PROXY.

Design philosophy

This feature flag SDK is designed according to our design philosophy. You canread more about that here.


[8]ページ先頭

©2009-2025 Movatter.jp