• Stars
    star
    212
  • Rank 186,122 (Top 4 %)
  • Language
    TypeScript
  • License
    Apache License 2.0
  • Created over 9 years ago
  • Updated 28 days ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Unleash client SDK for Node.js

Unleash Client SDK for Node.js

Unleash node SDK on npm npm downloads Build Status Code Climate Coverage Status

The official Unleash client SDK for Node.js.

Getting started

1. Install the unleash-client into your project

npm install unleash-client

or

yarn add unleash-client

(Or any other tool you like.)

2. Initialize 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.

const { initialize } = require('unleash-client');

const unleash = initialize({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: 'SOME-SECRET' },
});

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.

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 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:

unleash.on('synchronized', () => {
  // the SDK has synchronized with the server
  // and is ready to serve
});

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.

Constructing the Unleash client directly

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.

const { Unleash } = require('unleash-client');

const unleash = new Unleash({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: 'SOME-SECRET' },
});

unleash.on('ready', console.log.bind(console, 'ready'));

// optional error handling when using unleash directly
unleash.on('error', console.error);

Synchronous initialization

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.

const { startUnleash } = require('unleash-client');

const unleash = await startUnleash({
  url: 'https://YOUR-API-URL',
  appName: 'my-node-name',
  customHeaders: { Authorization: 'SOME-SECRET' },
});

// Unleash SDK has now fresh state from the unleash-api
const isEnabled = unleash.isEnabled('Demo');

3. Check features

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.

setInterval(() => {
  if (unleash.isEnabled('DemoToggle')) {
    console.log('Toggle enabled');
  } else {
    console.log('Toggle disabled');
  }
}, 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.

Providing an Unleash context

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:

const unleashContext = {
  userId: '123',
  sessionId: 'some-session-id',
  remoteAddress: '127.0.0.1',
  properties: {
    region: 'EMEA',
  },
};

const enabled = unleash.isEnabled('someToggle', unleashContext);

4. Stop unleash

To shut down the client (turn off the polling) you can simply call the destroy-method. This is typically not required.

const { destroy } = require('unleash-client');
destroy();

Built in activation strategies

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

Read more about activation strategies in the official docs.

Unleash context

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:

const unleashContext = {
  userId: '123',
  sessionId: 'some-session-id',
  remoteAddress: '127.0.0.1',
};
unleash.isEnabled('someToggle', unleashContext);

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's environment property. Automatically populated in the Unleash Context (optional). This does not set the SDK's Unleash 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 to 60000ms.
  • 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 return a Promise resolving as custom headers to be sent to unleash-server. When options are set, this will take precedence over customHeaders option.
  • 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 these options 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. E.g.: [{type: 'simple', value: 'proxy'}].

Custom strategies

1. implement the custom strategy:

const { Strategy, initialize } = require('unleash-client');
class ActiveForUserWithEmailStrategy extends Strategy {
  constructor() {
    super('ActiveForUserWithEmail');
  }

  isEnabled(parameters, context) {
    return parameters.emails.indexOf(context.email) !== -1;
  }
}

2. register your custom strategy:

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

Events

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:

const { initialize } = require('unleash-client');

const unleash = initialize({
  appName: 'my-app-name',
  url: 'http://unleash.herokuapp.com/api/',
  customHeaders: {
    Authorization: 'API token',
  },
});

// Some useful life-cycle events
unleash.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.
  // NB! 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 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

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted2.com/demo/api/',
  customHeaders: {
    Authorization: '943ca9171e2c884c545c5d82417a655fb77cec970cc3b78a8ff87f4406b495d0',
  },
  bootstrap: {
    data: [
      {
        enabled: false,
        name: 'BootstrapDemo',
        description: '',
        project: 'default',
        stale: false,
        type: 'release',
        variants: [],
        strategies: [{ name: 'default' }],
      },
    ],
  },
});

2. Bootstrap via a URL

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted.com/demo/api/',
  customHeaders: {
    Authorization: '943ca9171e2c884c545c5d82417a655fb77cec970cc3b78a8ff87f4406b495d0',
  },
  bootstrap: {
    url: 'http://localhost:3000/proxy/client/features',
    urlHeaders: {
      Authorization: 'bootstrap',
    },
  },
});

3. Bootstrap from a File

const client = initialize({
  appName: 'my-application',
  url: 'https://app.unleash-hosted.com/demo/api/',
  customHeaders: {
    Authorization: '943ca9171e2c884c545c5d82417a655fb77cec970cc3b78a8ff87f4406b495d0',
  },
  bootstrap: {
    filePath: '/tmp/some-bootstrap.json',
  },
});

Toggle definitions

Sometimes you might be interested in the raw feature toggle definitions.

const {
  initialize,
  getFeatureToggleDefinition,
  getFeatureToggleDefinitions,
} = require('unleash-client');

initialize({
  url: 'http://unleash.herokuapp.com/api/',
  customHeaders: {
    Authorization: 'API token',
  },
  appName: 'my-app-name',
  instanceId: 'my-unique-instance-id',
});

const featureToggleX = getFeatureToggleDefinition('app.ToggleX');
const featureToggles = 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 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

const { initialize, InMemStorageProvider } = require('unleash-client');

const client = initialize({
  appName: 'my-application',
  url: 'http://localhost:3000/api/',
  customHeaders: {
    Authorization: 'my-key',
  },
  storageProvider: new InMemStorageProvider(),
});

2. Custom Store Provider backed by redis

const { initialize, InMemStorageProvider } = require('unleash-client');

const { createClient } = require('redis');

class CustomRedisStore {
  async set(key, data) {
    const client = createClient();
    await client.connect();
    await client.set(key, JSON.stringify(data));
  }
  async get(key) {
    const client = createClient();
    await client.connect();
    const data = await client.get(key);
    return JSON.parse(data);
  }
}

const client = initialize({
  appName: 'my-application',
  url: 'http://localhost:3000/api/',
  customHeaders: {
    Authorization: 'my-key',
  },
  storageProvider: new CustomRedisStore(),
});

Custom repository

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.

More Repositories

1

unleash

Open-source feature management solution built for developers.
TypeScript
10,934
star
2

unleash-client-go

Unleash client SDK for Go
Go
135
star
3

unleash-client-java

Unleash client SDK for Java
Java
118
star
4

unleash-docker

Docker container for unleash
Shell
95
star
5

unleash-client-python

Unleash client SDK for Python πŸ’‘πŸ’‘πŸ’‘
Python
83
star
6

unleash-client-dotnet

Unleash client SDK for .NET
C#
79
star
7

unleash-client-ruby

Unleash client SDK for Ruby
Ruby
58
star
8

unleash-client-php

Unleash client SDK for PHP
PHP
55
star
9

unleash-proxy

Unleash Proxy is used to safely integrate frontend application with Unleash in a secure and scaleable way.
TypeScript
48
star
10

unleash-edge

Rust
45
star
11

unleash-proxy-client-js

A browser client that can be used together with the unleash-proxy.
TypeScript
45
star
12

proxy-client-react

TypeScript
42
star
13

helm-charts

Contains helm-charts for Unleash
Smarty
40
star
14

unleash-client-symfony

Symfony bundle implementing the Unleash server protocol
PHP
32
star
15

unleash-frontend

Unleash Admin UI
TypeScript
30
star
16

unleash-client-nextjs

Unleash SDK for Next.js
TypeScript
27
star
17

unleash-client-rust

Unleash client SDK for Rust language projects
Rust
23
star
18

unleash_proxy_client_flutter

Unleash is a open-source feature flag solution
Dart
15
star
19

yggdrasil

Rust
15
star
20

client-specification

A collection of test specifications to guide client implementations
JavaScript
12
star
21

unleash-proxy-client-swift

Swift
12
star
22

unleash-client-php-wip

PHP client for Unleash
PHP
11
star
23

unleash-examples

Concrete examples of using Unleash
JavaScript
11
star
24

next-unleash

Ease integration with next.js
JavaScript
10
star
25

proxy-client-vue

Vue interface for working with Unleash
TypeScript
8
star
26

unleash-android-proxy-sdk

Kotlin
7
star
27

unleash-docker-community

This is a collection of community maintained extensions to the Unleash Docker containers to make integrating SSO providers easier
Dockerfile
7
star
28

unleash-express

Unleash helper for Express.js
JavaScript
6
star
29

proxy-client-svelte

Svelte interface for working with Unleash
TypeScript
6
star
30

terraform-provider-unleash

Terraform provider for unleash, the Open-source feature management solution
Go
6
star
31

Flask-Unleash

Flask extension to make using Unleash that much easier! 🚦🚦🚦
Python
6
star
32

sdk-integration-tester

Runs integration tests against SDK test servers.
TypeScript
3
star
33

unleash-mini-ws

A small Java-based Workshop to help users get started using Unleash!
Java
2
star
34

unleash-sdk-examples

Example applications using Unleash
TypeScript
2
star
35

actix-template

Template repo for writing web-apps with Actix inside Unleash. See https://github.com/bricks-software/unleash-cloud-operator for an example which does both actix and k8s operator
Rust
2
star
36

unleash-server-api-go

Go client implementation of our admin server API
Go
2
star
37

unleash-react-proxy-sdk

A React SDK to be used together with the Unleash Proxy
2
star
38

unleash-android

Android library to connect to the Unleash frontend API
Kotlin
2
star
39

unleash-event-validator

TypeScript
1
star
40

unleash-spring-boot-starter

Java
1
star
41

actix-middleware-etag

ETag middleware for Actix-web >4
Rust
1
star
42

community-content

Community Content Program for users to be able to contribute to Unleash.
1
star
43

unleash-demo-app

This project is used as a demo app that is runtime-controlled (feature toggled) by Unleash.
TypeScript
1
star
44

unleash-weighter

Python
1
star
45

unleash-client-java-examples

Java
1
star
46

.github

Unleash ✨special✨ files
1
star
47

unleash-action

Unleash integration for GitHub workflows
TypeScript
1
star