Skip to main content
Version: Config V2

Node.js SDK Reference

Star on GitHub Node CI codecov Known Vulnerabilities License Node.JS

info

For JavaScript SSR (Server-Side Rendered) applications we recommend using ConfigCat JS-SSR SDK.

ConfigCat Node.js SDK on GitHub

Getting started

1. Install ConfigCat SDK

via NPM

npm i configcat-node

2. Import package

const configcat = require('configcat-node');

3. Create the ConfigCat client with your SDK Key

const configCatClient = configcat.getClient('#YOUR-SDK-KEY#');

4. Get your setting value

The async/await way:

const value = await configCatClient.getValueAsync(
'isMyAwesomeFeatureEnabled',
false,
);

if (value) {
do_the_new_thing();
} else {
do_the_old_thing();
}

(Please note that top-level await in modules is available only if your project is set up to use the ECMAScript module system. Otherwise you will need to use Promises or wrap your code in an async function as shown here.)

The Promise way:

configCatClient
.getValueAsync('isMyAwesomeFeatureEnabled', false)
.then((value) => {
if (value) {
do_the_new_thing();
} else {
do_the_old_thing();
}
});

5. Dispose the ConfigCat client

You can safely dispose all clients at once or individually and release all associated resources on application exit.

configcat.disposeAllClients(); // disposes all clients
// -or-
configCatClient.dispose(); // disposes a specific client

Creating the ConfigCat Client

ConfigCat Client is responsible for:

  • managing the communication between your application and ConfigCat servers.
  • caching your setting values and feature flags.
  • serving values quickly in a failsafe way.

configcat.getClient('<sdkKey>') returns a client with default options.

The getClient function has optional parameters, which can be used to adjust the behavior of the client.

ParametersDescriptionDefault
sdkKeyREQUIRED. SDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard.-
pollingModeOptional. The polling mode to use to acquire the setting values from the ConfigCat servers. More about polling modes.PollingMode.AutoPoll
optionsOptional. The options object. See the table below.-

The available options depends on the chosen polling mode. However, there are some common options which can be set in the case of every polling mode:

Option ParameterDescriptionDefault
loggerCustom IConfigCatLogger implementation for tracing.ConfigCatConsoleLogger (with WARN level)
requestTimeoutMsThe amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache.30000
baseUrlSets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON.
proxyProxy settings. More about the proxy settings.
dataGovernanceDescribes the location of your feature flag and setting data within the ConfigCat CDN. This parameter needs to be in sync with your Data Governance preferences. More about Data Governance. Available options: DataGovernance.Global, DataGovernance.EuOnly.DataGovernance.Global
cacheCustom IConfigCatCache implementation for caching the downloaded config.InMemoryConfigCache
flagOverridesLocal feature flag & setting overrides. More about feature flag overrides.-
defaultUserSets the default user. More about default user.undefined (none)
offlineDetermines whether the client should be initialized to offline mode. More about offline mode.false

Options also include a property named setupHook, which you can use to subscribe to the hooks (events) at the time of initialization. More about hooks.

For example:

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
setupHooks: (hooks) =>
hooks.on('clientReady', () => console.log('Client is ready!')),
},
);
info

You can acquire singleton client instances for your SDK keys using the configcat.getClient(sdkKey: "<sdkKey>") factory function. (However, please keep in mind that subsequent calls to getClient() with the same SDK Key return a shared client instance, which was set up by the first call.)

You can close all open clients at once using the configcat.disposeAllClients() function or do it individually using the configCatClient.dispose() method.

Anatomy of getValueAsync()

Returns a Promise with the value.

ParametersDescription
keyREQUIRED. The key of a specific setting or feature flag. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
const value = await configCatClient.getValueAsync(
'keyOfMyFeatureFlag', // Setting Key
false, // Default value
new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object
);

or

configCatClient
.getValueAsync(
'keyOfMyFeatureFlag', // Setting Key
false, // Default value
new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object
)
.then((value) => {
console.log(value);
});
caution

It is important to provide an argument for the defaultValue parameter that matches the type of the feature flag or setting you are evaluating. Please refer to the following table for the corresponding types.

Setting type mapping

Setting Kindtypeof defaultValue
On/Off Toggleboolean
Textstring
Whole Numbernumber
Decimal Numbernumber

In addition to the types mentioned above, you also have the option to provide null or undefined for the defaultValue parameter regardless of the setting kind. However, if you do so, the return type of the getValue method will be

  • boolean | string | number | null when defaultValue is null or
  • boolean | string | number | undefined when defaultValue is undefined.

This is because in these cases the exact return type cannot be determined at compile-time as the TypeScript compiler has no information about the setting type.

It's important to note that providing any other type for the defaultValue parameter will result in a TypeError.

If you specify an allowed type but it mismatches the setting kind, an error message will be logged and defaultValue will be returned.

Anatomy of getValueDetailsAsync()

getValueDetailsAsync() is similar to getValueAsync() but instead of returning the evaluated value only, it provides more detailed information about the evaluation result.

ParametersDescription
keyREQUIRED. The key of a specific setting or feature flag. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
userOptional, User Object. Essential when using Targeting. Read more about Targeting.
const details = await configCatClient.getValueDetailsAsync(
'keyOfMyFeatureFlag', // Setting Key
false, // Default value
new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object
);

or

configCatClient
.getValueDetailsAsync(
'keyOfMyFeatureFlag', // Setting Key
false, // Default value
new configcat.User('#UNIQUE-USER-IDENTIFIER#'), // Optional User Object
)
.then((details) => {
console.log(details);
});
caution

It is important to provide an argument for the defaultValue parameter that matches the type of the feature flag or setting you are evaluating. Please refer to this table for the corresponding types.

The details result contains the following information:

FieldTypeDescription
keystringThe key of the evaluated feature flag or setting.
valueboolean / string / numberThe evaluated value of the feature flag or setting.
userUserThe User Object used for the evaluation.
isDefaultValuebooleanTrue when the default value passed to getValueDetailsAsync() is returned due to an error.
errorMessagestringIn case of an error, this property contains the error message.
errorExceptionanyIn case of an error, this property contains the related exception object (if any).
matchedTargetingRuleITargetingRuleThe Targeting Rule (if any) that matched during the evaluation and was used to return the evaluated value.
matchedPercentageOptionIPercentageOptionThe Percentage Option (if any) that was used to select the evaluated value.
fetchTimeDateThe last download time (UTC) of the current config.

User Object

The User Object is essential if you'd like to use ConfigCat's Targeting feature.

For simple targeting:

let userObject = new configcat.User('#UNIQUE-USER-IDENTIFIER#');
let userObject = new configcat.User('[email protected]');
ParametersDescription
identifierREQUIRED. Unique identifier of a user in your application. Can be any string value, even an email address.
emailOptional parameter for easier Targeting Rule definitions.
countryOptional parameter for easier Targeting Rule definitions.
customOptional dictionary for custom attributes of a user for advanced Targeting Rule definitions. E.g. User role, Subscription type.

For advanced targeting:

let userObject = new configcat.User(
/* identifier: */ '#UNIQUE-USER-IDENTIFIER#',
/* email: */ '[email protected]',
/* country: */ 'United Kingdom',
/* custom: */ {
SubscriptionType: 'Pro',
UserRole: 'Admin',
},
);

The custom dictionary also allows attribute values other than string values:

let userObject = new configcat.User('#UNIQUE-USER-IDENTIFIER#');
userObject.custom = {
Rating: 4.5,
RegisteredAt: new Date('2023-11-22T12:34:56.000Z'),
Roles: ['Role1', 'Role2'],
};

User Object Attribute Types

All comparators support string values as User Object attribute (in some cases they need to be provided in a specific format though, see below), but some of them also support other types of values. It depends on the comparator how the values will be handled. The following rules apply:

Text-based comparators (EQUALS, IS ONE OF, etc.)

  • accept string values,
  • all other values are automatically converted to string (a warning will be logged but evaluation will continue as normal).

SemVer-based comparators (IS ONE OF, <, >=, etc.)

  • accept string values containing a properly formatted, valid semver value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Number-based comparators (=, <, >=, etc.)

  • accept number values,
  • accept string values containing a properly formatted, valid number value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Date time-based comparators (BEFORE / AFTER)

  • accept Date values, which are automatically converted to a second-based Unix timestamp,
  • accept number values representing a second-based Unix timestamp,
  • accept string values containing a properly formatted, valid number value,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

String array-based comparators (ARRAY CONTAINS ANY OF / ARRAY NOT CONTAINS ANY OF)

  • accept arrays of string,
  • accept string values containing a valid JSON string which can be deserialized to an array of string,
  • all other values are considered invalid (a warning will be logged and the currently evaluated Targeting Rule will be skipped).

Default user

It's possible to set a default User Object that will be used on feature flag and setting evaluation. It can be useful when your application has a single user only or rarely switches users.

You can set the default User Object either on SDK initialization:

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
defaultUser: new configcat.User('[email protected]'),
},
);

...or using the setDefaultUser() method of the configCatClient object:

configCatClient.setDefaultUser(new configcat.User('[email protected]'));

Whenever the evaluation methods like getValueAsync(), getValueDetailsAsync(), etc. are called without an explicit user parameter, the SDK will automatically use the default user as a User Object.

const user = new configcat.User('[email protected]');
configCatClient.setDefaultUser(user);

// The default user will be used in the evaluation process.
const value = await configCatClient.getValueAsync('keyOfMyFeatureFlag', false);

When a user parameter is passed to the evaluation methods, it takes precedence over the default user.

const user = new configcat.User('[email protected]');
configCatClient.setDefaultUser(user);

const otherUser = new configcat.User('[email protected]');

// otherUser will be used in the evaluation process.
const value = await configCatClient.getValueAsync(
'keyOfMyFeatureFlag',
false,
otherUser,
);

You can also remove the default user by doing the following:

configCatClient.clearDefaultUser();

Polling Modes

The ConfigCat SDK supports 3 different polling mechanisms to acquire the setting values from ConfigCat. After latest setting values are downloaded, they are stored in the local cache, then all getValueAsync() calls are served from there. With the following polling modes, you can customize the SDK to best fit to your application's lifecycle. More about polling modes.

Auto polling (default)

The ConfigCat SDK downloads the latest values and stores them automatically every 60 seconds.

Use the pollIntervalSeconds option parameter to change the polling interval.

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
pollIntervalSeconds: 95,
},
);

Available options (in addition to the common ones):

Option ParameterDescriptionDefault
pollIntervalSecondsPolling interval in seconds.60s
maxInitWaitTimeSecondsMaximum waiting time between the client initialization and the first config acquisition in seconds.5s

Lazy loading

When calling getValueAsync(), the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case getValueAsync() will return the setting value after the cache is updated.

Use cacheTimeToLiveSeconds option parameter to set cache lifetime.

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.LazyLoad,
{
cacheTimeToLiveSeconds: 600,
},
);

Available options (in addition to the common ones):

Option ParameterDescriptionDefault
cacheTimeToLiveSecondsCache TTL in seconds.60s

Manual polling

Manual polling gives you full control over when the config JSON (with the setting values) is downloaded. ConfigCat SDK will not update them automatically. Calling forceRefreshAsync() is your application's responsibility.

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.ManualPoll,
);

await configCatClient.forceRefreshAsync();
let value = await configCatClient.getValueAsync(
'keyOfMyTextSetting',
'my default value',
);
console.log(value);

getValueAsync() returns defaultValue if the cache is empty. Call forceRefreshAsync() to update the cache.

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.ManualPoll,
);

let value = await configCatClient.getValueAsync(
'keyOfMyTextSetting',
'my default value',
);
console.log(value); // console: "my default value"

await configCatClient.forceRefreshAsync();
value = await configCatClient.getValueAsync(
'keyOfMyTextSetting',
'my default value',
);
console.log(value);

Hooks

The SDK provides several hooks (events), by means of which you can get notified of its actions. You can subscribe to the following events emitted by the client:

  • clientReady: This event is emitted when the SDK reaches the ready state. If the SDK is set up to use lazy loading or manual polling, it's considered ready right after syncing up with the config cache. If auto polling is used, the ready state is reached when the SDK has a valid config JSON loaded into memory either from cache or from HTTP. If the config couldn't be loaded neither from cache nor from HTTP, the clientReady event fires when the auto polling's MaxInitWaitTime has passed.
  • configChanged: This event is emitted first when the SDK loads a valid config JSON into memory from cache, then each time afterwards when a config JSON with changed content is downloaded via HTTP.
  • flagEvaluated: This event is emitted each time when the SDK evaluates a feature flag or setting. The event provides the same evaluation details that you would get from getValueDetailsAsync().
  • clientError: This event is emitted when an error occurs within the ConfigCat SDK.

You can subscribe to these events either on initialization:

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.ManualPoll,
{
setupHooks: (hooks) =>
hooks.on('flagEvaluated', () => {
/* handle the event */
}),
},
);

...or directly on the ConfigCatClient instance:

configCatClient.on('flagEvaluated', () => {
/* handle the event */
});

Online / Offline mode

In cases where you want to prevent the SDK from making HTTP calls, you can switch it to offline mode:

configCatClient.setOffline();

In offline mode, the SDK won't initiate HTTP requests and will work only from its cache.

To switch the SDK back to online mode, do the following:

configCatClient.setOnline();

Using the configCatClient.isOffline property you can check whether the SDK is in offline mode.

Flag Overrides

With flag overrides you can overwrite the feature flags & settings downloaded from the ConfigCat CDN with local values. Moreover, you can specify how the overrides should apply over the downloaded values. The following 3 behaviours are supported:

  • Local only (OverrideBehaviour.LocalOnly): When evaluating values, the SDK will not use feature flags & settings from the ConfigCat CDN, but it will use all feature flags & settings that are loaded from local-override sources.

  • Local over remote (OverrideBehaviour.LocalOverRemote): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the local-override version will take precedence.

  • Remote over local (OverrideBehaviour.RemoteOverLocal): When evaluating values, the SDK will use all feature flags & settings that are downloaded from the ConfigCat CDN, plus all feature flags & settings that are loaded from local-override sources. If a feature flag or a setting is defined both in the downloaded and the local-override source then the downloaded version will take precedence.

You can set up the SDK to load your feature flag & setting overrides from a { [name: string]: any } map.

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
flagOverrides: configcat.createFlagOverridesFromMap(
{
enabledFeature: true,
disabledFeature: false,
intSetting: 5,
doubleSetting: 3.14,
stringSetting: 'test',
},
configcat.OverrideBehaviour.LocalOnly,
),
},
);

Logging

Setting log levels

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
logger: configcat.createConsoleLogger(configcat.LogLevel.Info), // Setting log level to Info
},
);

Available log levels:

LevelDescription
OffNothing gets logged.
ErrorOnly error level events are logged.
WarnDefault. Errors and Warnings are logged.
InfoErrors, Warnings and feature flag evaluation is logged.
DebugAll of the above plus debug info is logged.

Info level logging helps to inspect the feature flag evaluation process:

ConfigCat - INFO - [5000] Evaluating 'isPOCFeatureEnabled' for User '{"Identifier":"#SOME-USER-ID#","Email":"[email protected]"}'
Evaluating targeting rules and applying the first match if any:
- IF User.Email CONTAINS ANY OF ['@something.com'] THEN 'false' => no match
- IF User.Email CONTAINS ANY OF ['@example.com'] THEN 'true' => MATCH, applying rule
Returning 'true'.

Custom logger implementation

The SDK provides a simple logger implementation that logs to the debugging console (configcat.createConsoleLogger(...)) but it also allows you to inject any custom implementation of IConfigCatLogger.

class MyCustomLogger implements IConfigCatLogger {
/**
* Writes an event into the log.
* @param level Event severity level.
* @param eventId Event identifier.
* @param message Message.
* @param exception The exception object related to the message (if any).
*/
log(
level: LogLevel,
eventId: LogEventId,
message: LogMessage,
exception?: any,
): void {
// insert your custom log logic
}
}

or

function MyCustomLogger() {}

MyCustomLogger.prototype.log = function (level, eventId, message, exception) {
// insert your custom log logic
};

then

// set the `MyCustomLogger` implementation on creating the client instance

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
logger: new MyCustomLogger(),
},
);

getAllKeysAsync()

You can query the keys from your configuration in the SDK with the getAllKeysAsync() method.

const configCatClient = configcat.getClient('#YOUR-SDK-KEY#');

const keys = await configCatClient.getAllKeysAsync();
console.log(keys);

getAllValuesAsync()

Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.

const configCatClient = configcat.getClient('#YOUR-SDK-KEY#');

let settingValues = await configCatClient.getAllValuesAsync();
settingValues.forEach((i) =>
console.log(i.settingKey + ' -> ' + i.settingValue),
);

// invoke with User Object
const userObject = new configcat.User('[email protected]');

settingValues = await configCatClient.getAllValuesAsync(userObject);
settingValues.forEach((i) =>
console.log(i.settingKey + ' -> ' + i.settingValue),
);

getAllValueDetailsAsync()

Evaluates and returns the values along with evaluation details of all feature flags and settings. Passing a User Object is optional.

const configCatClient = configcat.getClient('#YOUR-SDK-KEY#');

let settingValues = await configCatClient.getAllValueDetailsAsync();
settingValues.forEach((details) => console.log(details));

// invoke with User Object
const userObject = new configcat.User('[email protected]');

settingValues = await configCatClient.getAllValueDetailsAsync(userObject);
settingValues.forEach((details) => console.log(details));

Snapshots and synchronous feature flag evaluation

On JavaScript platforms, the ConfigCat client provides only asynchronous methods for evaluating feature flags and settings because these operations may involve network communication (e.g. downloading config data from the ConfigCat CDN servers), which is necessarily an asynchronous operation in JavaScript.

However, there may be use cases where synchronous evaluation is preferable, thus, since v10.1.0, the Node.js SDK provides a way to synchronously evaluate feature flags and settings via snapshots.

Using the snapshot() method, you can capture the current state of the ConfigCat client (including the latest downloaded config data) and you can use the resulting snapshot object to synchronously evaluate feature flags and settings based on the captured state:

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.ManualPoll,
);

// Make sure that the latest config data is available locally.
await configCatClient.forceRefreshAsync();

const snapshot = configCatClient.snapshot();

const user = new configcat.User('#UNIQUE-USER-IDENTIFIER#');
for (const key of snapshot.getAllKeys()) {
const value = snapshot.getValue(key, null, user);
console.log(`${key}: ${value}`);
}
caution

Please note that when you create and utilize a snapshot, it won't refresh your local cache once the cached config data expires. Additionally, when working with shared caching, creating a snapshot also doesn't trigger a sync with the external cache, since the snapshot only captures the config instance stored in the client's memory. Therefore, it's recommended to use snapshots in conjunction with the Auto Polling mode, where the SDK automatically updates the local cache in the background. For other polling modes, you'll need to manually initiate a cache refresh by invoking forceRefreshAsync.

In Auto Poll mode, you can use the waitForReady method to wait for the latest config data to become available locally:

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
);

// Make sure that the latest config data is available locally.
await configCatClient.waitForReady();

const snapshot = configCatClient.snapshot();

Using ConfigCat behind a proxy

Provide your own proxy server settings (proxy server/port) by adding a proxy option parameter when creating the ConfigCat client.

const options = { pollIntervalSeconds: 2, proxy: 'http://192.168.1.1:8080' };

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
options,
);

Using custom cache implementation

The ConfigCat SDK stores the downloaded config data in a local cache to minimize network traffic and enhance client performance. If you prefer to use your own cache solution, such as an external or distributed cache in your system, you can implement the IConfigCatCache interface and set the cache property in the options passed to getClient. This allows you to seamlessly integrate ConfigCat with your existing caching infrastructure.

class MyCustomCache implements IConfigCatCache {
set(key: string, value: string): Promise<void> | void {
// insert your cache write logic here
}

get(
key: string,
): Promise<string | null | undefined> | string | null | undefined {
// insert your cache read logic here
}
}

or

function MyCustomCache() {}

MyCustomCache.prototype.set = function (key, value) {
// insert your cache write logic here
};
MyCustomCache.prototype.get = function (key) {
// insert your cache read logic here
};

then

// set the `MyCustomCache` implementation on creating the client instance

const configCatClient = configcat.getClient(
'#YOUR-SDK-KEY#',
configcat.PollingMode.AutoPoll,
{
cache: new MyCustomCache(),
},
);

In some cases (eg: fs) you may have to use promisify to create promises from callback-style functions.

See implementation of Redis cache.

info

The Node.js SDK supports shared caching. You can read more about this feature and the required minimum SDK versions here.

Sample Application

Guides

See the guides on how to use ConfigCat's Node SDK with the following libraries and frameworks:

Look under the hood