Security News
Research
Data Theft Repackaged: A Case Study in Malicious Wrapper Packages on npm
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
unleash-client
Advanced tools
The unleash-client npm package is a feature toggle system that allows you to control the release of features in your application. It helps you manage feature flags, enabling or disabling features without deploying new code.
Initialize Unleash Client
This code initializes the Unleash client with the necessary configuration, including the URL of the Unleash server, the application name, and the instance ID.
const { UnleashClient } = require('unleash-client');
const unleash = new UnleashClient({
url: 'http://unleash.herokuapp.com/api/',
appName: 'my-app',
instanceId: 'my-instance-id',
});
unleash.start();
Check if a feature is enabled
This code checks if a specific feature toggle (in this case, 'someFeature') is enabled and logs the result.
const isEnabled = unleash.isEnabled('someFeature');
console.log(`Feature is enabled: ${isEnabled}`);
Register custom strategies
This code demonstrates how to register a custom strategy with the Unleash client. Custom strategies allow you to define your own logic for enabling or disabling features.
unleash.on('ready', () => {
unleash.registerStrategy(new CustomStrategy());
});
class CustomStrategy {
constructor() {
this.name = 'custom';
}
isEnabled(parameters, context) {
// Custom logic to determine if the feature is enabled
return true;
}
}
LaunchDarkly is a feature management platform that provides feature flags as a service. It offers more advanced targeting and segmentation capabilities compared to Unleash, but it is a paid service.
Flagr is an open-source feature flagging and A/B testing service. It provides a web UI for managing flags and supports various targeting rules. It is similar to Unleash in terms of being open-source but offers a different set of features and a different user interface.
fflip is a lightweight feature flagging library for Node.js. It is simpler and more lightweight compared to Unleash, making it suitable for smaller projects or those with simpler feature flagging needs.
The official Unleash client SDK for Node.js.
npm install unleash-client
or
yarn 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.
import { initialize } from 'unleash-client';
const unleash = initialize({
url: 'https://YOUR-API-URL',
appName: 'my-node-name',
customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
});
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:
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.
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.
import { Unleash } from 'unleash-client';
const unleash = new Unleash({
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 directly
unleash.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.
import { startUnleash } from 'unleash-client';
const unleash = await startUnleash({
url: 'https://YOUR-API-URL',
appName: 'my-node-name',
customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
});
// Unleash SDK has now fresh state from the unleash-api
const 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.
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.
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.
const variant = unleash.getVariant('demo-variant');
if (variant.name === 'blue') {
// do something with the blue variant...
}
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);
To shut down the client (turn off the polling) you can simply call the destroy-method. This is typically not required.
import { destroy } from 'unleash-client';
destroy();
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:
const unleashContext = {
userId: '123',
sessionId: 'some-session-id',
remoteAddress: '127.0.0.1',
};
unleash.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'}]
.import { initialize, Strategy } from 'unleash-client';
class ActiveForUserWithEmailStrategy extends Strategy {
constructor() {
super('ActiveForUserWithEmail');
}
isEnabled(parameters, context) {
return parameters.emails.indexOf(context.email) !== -1;
}
}
initialize({
url: 'http://unleash.herokuapp.com',
customHeaders: {
Authorization: 'API token',
},
strategies: [new ActiveForUserWithEmailStrategy()],
});
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:
import { initialize } from '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})`));
(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: '<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
const client = 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
const client = 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',
});
const featureToggleX = getFeatureToggleDefinition('app.ToggleX');
const 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
import { initialize, InMemStorageProvider } from 'unleash-client';
const client = initialize({
appName: 'my-application',
url: 'http://localhost:3000/api/',
customHeaders: { Authorization: '<YOUR_API_TOKEN>' },
storageProvider: new InMemStorageProvider(),
});
2. Custom Store Provider backed by redis
import { initialize, InMemStorageProvider } from 'unleash-client';
import { createClient } from '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(),
});
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.
FAQs
Unleash Client for Node
The npm package unleash-client receives a total of 182,230 weekly downloads. As such, unleash-client popularity was classified as popular.
We found that unleash-client demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago.Ā It has 3 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
Research
The Socket Research Team breaks down a malicious wrapper package that uses obfuscation to harvest credentials and exfiltrate sensitive data.
Research
Security News
Attackers used a malicious npm package typosquatting a popular ESLint plugin to steal sensitive data, execute commands, and exploit developer systems.
Security News
The Ultralytics' PyPI Package was compromised four times in one weekend through GitHub Actions cache poisoning and failure to rotate previously compromised API tokens.