JavaScript SDK Reference
For JavaScript SSR (Server-Side Rendered) applications we recommend using ConfigCat JS-SSR SDK
ConfigCat JavaScript SDK on GitHubGetting started
1. Install and import package
via NPM:
npm i configcat-js
import * as configcat from "configcat-js";
via CDN:
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/[email protected]/dist/configcat.min.js"></script>
2. Create the ConfigCat client with your SDK Key:
var configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
3. Get your setting value
The Promise (async/await) way:
configCatClient.getValueAsync("isMyAwesomeFeatureEnabled", false)
.then((value) => {
if(value) {
do_the_new_thing();
} else {
do_the_old_thing();
}
});
or the Callback way:
configCatClient.getValue("isMyAwesomeFeatureEnabled", false, (value) => {
if(value) {
do_the_new_thing();
} else {
do_the_old_thing();
}
});
4. Dispose ConfigCat client
You can safely dispose()
the client instance and release all associated resources on application exit.
configCatClient.dispose();
Working Demo on CodePen
See the Pen ConfigCat Feature Flag Demo on CodePen.
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.
createClient(sdkKey, options)
returns a client with default options.
Properties | Description | Default |
---|---|---|
sdkKey | REQUIRED. SDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard. | - |
options | Optional. More about the options parameter. | - |
createClientWithAutoPoll()
, createClientWithLazyLoad()
, createClientWithManualPoll()
Creating the client is different for each polling mode.
See below for details.
We strongly recommend you to use the ConfigCat Client as a Singleton object in your application. If you want to use multiple SDK Keys in the same application, create only one ConfigCat Client per SDK Key.
Anatomy of getValue()
Parameters | Description |
---|---|
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
defaultValue | REQUIRED. This value will be returned in case of an error. |
callback | REQUIRED. Called with the actual setting value. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
configCatClient.getValue(
"keyOfMySetting", // Setting Key
false, // Default value
function(value) { console.log(value) }, // Callback function
{ identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92" } // Optional User Object
);
Anatomy of getValueAsync()
Returns a Promise with the value.
Parameters | Description |
---|---|
key | REQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting. |
defaultValue | REQUIRED. This value will be returned in case of an error. |
user | Optional, User Object. Essential when using Targeting. Read more about Targeting. |
const value = await configCatClient.getValueAsync(
"keyOfMySetting", // Setting Key
false, // Default value
{ identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92" } // Optional User Object
);
or
configCatClient.getValueAsync(
"keyOfMySetting", // Setting Key
false, // Default value
{ identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92" }) // Optional User Object
.then((value) => { console.log(value) });
User Object
The User Object is essential if you'd like to use ConfigCat's Targeting feature. For simple targeting:
var userObject = {
identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92"
};
or
var userObject = {
identifier : "[email protected]"
};
Parameters | Description |
---|---|
identifier | REQUIRED. Unique identifier of a user in your application. Can be any string value, even an email address. |
email | Optional parameter for easier targeting rule definitions. |
country | Optional parameter for easier targeting rule definitions. |
custom | Optional dictionary for custom attributes of a user for advanced targeting rule definitions. e.g. User role, Subscription type. |
For advanced targeting:
var userObject = {
identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92",
email : "[email protected]",
country : "United Kingdom",
custom : {
"SubscriptionType": "Pro",
"UserRole": "Admin"
}
};
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 internal cache then all getValue()
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.
createClientWithAutoPoll(sdkKey, options)
Option Parameter | Description | Default |
---|---|---|
pollIntervalSeconds | Polling interval. Range: 1 - Number.MAX_SAFE_INTEGER | 60 |
configChanged | Callback to get notified about changes. | - |
logger | Custom logger. See below for details. | Console logger |
requestTimeoutMs | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 |
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 |
maxInitWaitTimeSeconds | Maximum waiting time between the client initialization and the first config acquisition in seconds. | 5 |
flagOverrides | Local feature flag & setting overrides. More about feature flag overrides. | - |
Use the pollIntervalSeconds
option parameter to change the polling interval.
configcat.createClientWithAutoPoll("#YOUR-SDK-KEY#", { pollIntervalSeconds: 95 });
Adding a callback to configChanged
option parameter will get you notified about changes.
configcat.createClientWithAutoPoll("#YOUR-SDK-KEY#", { configChanged: function() {
console.log("Your config has been changed!");
}});
Lazy loading
When calling getValue()
the ConfigCat SDK downloads the latest setting values if they are not present or expired in the cache. In this case the callback
will be called after the cache is updated.
createClientWithLazyLoad(sdkKey, options)
Option Parameter | Description | Default |
---|---|---|
cacheTimeToLiveSeconds | Cache TTL. Range: 1 - Number.MAX_SAFE_INTEGER | 60 |
logger | Custom logger. See below for details. | Console logger |
requestTimeoutMs | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 |
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 |
flagOverrides | Local feature flag & setting overrides. More about feature flag overrides. | - |
Use cacheTimeToLiveSeconds
option parameter to set cache lifetime.
configcat.createClientWithLazyLoad("#YOUR-SDK-KEY#", { cacheTimeToLiveSeconds: 600 });
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 forceRefresh()
or forceRefreshAsync()
is your application's responsibility.
createClientWithManualPoll(sdkKey, options)
Option Parameter | Description | Default |
---|---|---|
logger | Custom logger. See below for details. | Console logger |
requestTimeoutMs | The amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache. | 30000 |
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 |
flagOverrides | Local feature flag & setting overrides. More about feature flag overrides. | - |
const configCatClient = configcat.createClientWithManualPoll("#YOUR-SDK-KEY#");
configCatClient.forceRefresh(() =>{
configCatClient.getValue("key", "my default value", (value)=>{
console.log(value);
});
});
getValue()
returnsdefaultValue
if the cache is empty. CallforceRefresh()
orforceRefreshAsync()
to update the cache.
const configCatClient = configcat.createClientWithManualPoll("#YOUR-SDK-KEY#");
configCatClient.getValue("key", "my default value", (value)=>{
console.log(value) // console: "my default value"
});
configCatClient.forceRefresh(() =>{
configCatClient.getValue("key", "my default value", (value)=>{
console.log(value); // console: "value from server"
});
});
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/Offline mode (
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.createClientWithAutoPoll('#YOUR-SDK-KEY#', {
flagOverrides: configcat.createFlagOverridesFromMap({
enabledFeature: true,
disabledFeature: false,
intSetting: 5,
doubleSetting: 3.14,
stringSetting: "test"
},
configcat.OverrideBehaviour.LocalOnly
)
});
Logging
Setting log levels
const logger = configcat.createConsoleLogger(3); // Setting log level to 3 (= Info)
const configCatClient = configcat.createClientWithAutoPoll('#YOUR-SDK-KEY#',
{ logger: logger }
);
Available log levels:
Level | Name | Description |
---|---|---|
-1 | Off | Nothing gets logged. |
1 | Error | Only error level events are logged. |
2 | Warn | Errors and Warnings are logged. |
3 | Info | Errors, Warnings and feature flag evaluation is logged. |
4 | Debug | All of the above plus debug info is logged. |
You can use LogLevel
enum type from configcat-common
package:
import { LogLevel } from 'configcat-common';
const logger = configcat.createConsoleLogger(LogLevel.Info);
Info level logging helps to inspect the feature flag evaluation process:
ConfigCat - INFO - Evaluate 'isPOCFeatureEnabled'
User : {"identifier":"#SOME-USER-ID#","email":"[email protected]"}
Evaluating rule: '[email protected]' CONTAINS '@something.com' => no match
Evaluating rule: '[email protected]' CONTAINS '@example.com' => MATCH
Returning value : true
getAllKeys()
, getAllKeysAsync()
You can query the keys from your configuration in the SDK with the getAllKeys()
or getAllKeysAsync()
method.
const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
configCatClient.getAllKeys(function(keys) {
console.log(keys);
});
const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
const keys = await configCatClient.getAllKeysAsync();
console.log(keys);
getAllValues()
, getAllValuesAsync()
Evaluates and returns the values of all feature flags and settings. Passing a User Object is optional.
const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
configCatClient.getAllValues(function(settingValues) {
settingValues.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
});
// invoke with user object
const userObject = { identifier : "[email protected]" };
configCatClient.getAllValues(function(settingValues) {
settingValues.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
}, userObject);
const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
const settingValues = await configCatClient.getAllValuesAsync();
settingValues.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
// invoke with user object
const userObject = { identifier : "[email protected]" };
const settingValuesTargeting = await configCatClient.getAllValuesAsync(userObject);
settingValuesTargeting.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
Using custom cache implementation
Config's data stored in a cache, it is efficiency increases in retrieval of data and performance of the client. If you would like to use your cache solution (for example your system uses external or distributed cache) you can implement those function and set to cache
parameters in the setting.
function myCustomCache() { }
myCustomCache.prototype.get = function(key) {
// `key` [string] - a unique cachekey
// insert here your cache read logic
}
myCustomCache.prototype.set = function(key, item) {
// `key` [string] - a unique cachekey
// `item` [object] - configcat's cache config item
// insert here your cache write logic
}
// set the `myCustomCache` when create a client instance
const configCatClient = configcat.createClientWithAutoPoll('PKDVCLf-Hq-h-kCzMp-L7Q/HhOWfwVtZ0mb30i9wi17GQ',
{
cache: new myCustomCache()
});
Sensitive information handling
The frontend/mobile SDKs are running in your users' browsers/devices. The SDK is downloading a config.json file from ConfigCat's CDN servers. The URL path for this config.json file contains your SDK key, so the SDK key and the content of your config.json file (feature flag keys, feature flag values, targeting rules, % rules) can be visible to your users.
This SDK key is read-only, it only allows downloading your config.json file, but nobody can make any changes with it in your ConfigCat account.
Suppose you don't want your SDK key or the content of your config.json file visible to your users. In that case, we recommend you use the SDK only in your backend applications and call a backend endpoint in your frontend/mobile application to evaluate the feature flags for a specific application customer.
Also, we recommend using confidential targeting comparators in the targeting rules of those feature flags that are used in the frontend/mobile SDKs.
Browser compatibility
This SDK should be compatible with all modern browsers.
The SDK is tested against the following browsers:
- Chrome (stable, latest, beta)
- Chromium (64.0.3282.0, 72.0.3626.0, 80.0.3987.0)
- Firefox (latest, latest-beta, 84.0).
These tests are running on each pull request, before each deploy, and on a daily basis. You can view a sample run here.