Node.js SDK
This SDK supersedes the legacy Node.js SDK.
ConfigCat SDK for JavaScript on GitHub
Getting started
1. Install and import package
First install the NPM package:
npm i @configcat/sdk
Then import it into your application:
const configcat = require("@configcat/sdk/node");
or
import * as configcat from "@configcat/sdk/node";
For subpath imports to work in TypeScript when using ts-node,
you must set the moduleResolution
option to node16
or nodenext
in your tsconfig.json
. For TypeScript versions older than 4.7, where
these options are not available, you need to fall back to module resolution node
and importing from the main
entry point @configcat/sdk
.
2. Create the ConfigCat client with your SDK Key
const configCatClient = configcat.getClient('#YOUR-SDK-KEY#');
3. 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();
}
});
The ConfigCat SDK also offers a synchronous API for feature flag evaluation. Read more here.
4. 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.
Parameters | Description | Default |
---|---|---|
sdkKey | REQUIRED. SDK Key to access your feature flags and settings. Get it from ConfigCat Dashboard. | - |
pollingMode | Optional. The polling mode to use to fetch the config data from the ConfigCat CDN. More about polling modes. | PollingMode.AutoPoll |
options | Optional. 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 Parameter | Description | Default |
---|---|---|
configFetcher | Custom IConfigCatConfigFetcher instance for downloading a config. | NodeHttpConfigFetcher |
cache | Custom IConfigCatCache implementation for caching the downloaded config. | InMemoryConfigCache |
logger | Custom IConfigCatLogger implementation for tracing. | ConfigCatConsoleLogger (with WARN level) |
logFilter | Sets a custom log filter. More about log filtering. | undefined (none) |
baseUrl | Sets the CDN base url (forward proxy, dedicated subscription) from where the SDK will download the config JSON. | |
httpAgent | The http.Agent instance to use for non-secure HTTP communication. Can be used to route http://... requests made by the SDK through an HTTP, HTTPS or SOCKS proxy (see also this section). | |
httpsAgent | The https.Agent instance to use for secure HTTP communication. Can be used to route https://... requests made by the SDK through an HTTP, HTTPS or SOCKS proxy (see also this section). | |
requestTimeoutMs | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 |
flagOverrides | Local feature flag & setting overrides. More about feature flag overrides. | |
dataGovernance | Describes 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 |
defaultUser | Sets the default user. More about default user. | undefined (none) |
offline | Determines 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', function() {
const keys = this.configCatClient.snapshot().getAllKeys();
console.log(`Client is ready! Number of available feature flags: ${keys.length}`);
}),
},
);
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.