JavaScript (SSR)

Star on GitHub Build Status codecov Known Vulnerabilities

For Server-Side Rendered JavaScript frameworks like NuxtJS

Getting started

1. Install and import package

via NPM:

npm i configcat-js-ssr
import * as configcat from "configcat-js-ssr";

2. Create the ConfigCatClient with your SDK Key:

const 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();
}
});

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.

PropertiesDescriptionDefault
sdkKeyREQUIRED. SDK Key to access your feature flags and configurations. Get it from ConfigCat Dashboard.-
optionsOptional. More about the options parameter.-

createClientWithAutoPoll(), createClientWithLazyLoad(), createClientWithManualPoll()
Creating the client is different for each polling mode. See below for details.

caution

We strongly recommend using the ConfigCat Client as a Singleton object in your application.

Anatomy of getValue()

ParametersDescription
keyREQUIRED. Setting-specific key. Set on ConfigCat Dashboard for each setting.
defaultValueREQUIRED. This value will be returned in case of an error.
callbackREQUIRED. Called with the actual setting value.
userOptional, 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
);

getValueAsync()

Returns a Promise with the value.

ParametersDescription
keyREQUIRED. Setting-specific key. 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(
"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 : "john@example.com"
};
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:

var userObject = {
identifier : "435170f4-8a8b-4b67-a723-505ac7cdea92",
email : "john@example.com",
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.

Auto polling (default)

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

createClientWithAutoPoll(sdkKey, options)

Option ParameterDescriptionDefault
pollIntervalSecondsPolling interval. Range: 1 - Number.MAX_SAFE_INTEGER60
configChangedCallback to get notified about changes.-
loggerCustom logger. See below for details.Console logger
requestTimeoutMsThe amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache.30000
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: Global, EuOnly.Global
maxInitWaitTimeSecondsMaximum waiting time between the client initialization and the first config acquisition in seconds.5

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 ParameterDescriptionDefault
cacheTimeToLiveSecondsCache TTL. Range: 1 - Number.MAX_SAFE_INTEGER60
loggerCustom logger. See below for details.Console logger
requestTimeoutMsThe amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache.30000
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: Global, EuOnly.Global

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 ParameterDescriptionDefault
loggerCustom logger. See below for details.Console logger
requestTimeoutMsThe amount of milliseconds the SDK waits for a response from the ConfigCat servers before returning values from the cache.30000
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: Global, EuOnly.Global
const configCatClient = configcat.createClientWithManualPoll("#YOUR-SDK-KEY#");
configCatClient.forceRefresh(() =>{
configCatClient.getValue("key", "my default value", (value)=>{
console.log(value);
});
});

getValue() returns defaultValue if the cache is empty. Call forceRefresh() or forceRefreshAsync() 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"
});
});

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

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

ConfigCat - INFO - Evaluate 'isPOCFeatureEnabled'
User : {"identifier":"#SOME-USER-ID#","email":"configcat@example.com"}
Evaluating rule: 'configcat@example.com' CONTAINS '@something.com' => no match
Evaluating rule: 'configcat@example.com' CONTAINS '@example.com' => MATCH
Returning value : true

getAllKeys()

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

const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
configCatClient.getAllKeys(function(keys) {
console.log(keys);
});

getAllKeysAsync()

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

const configCatClient = configcat.createClient("#YOUR-SDK-KEY#");
const keys = await configCatClient.getAllKeysAsync();
console.log(keys);

getAllValues()

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 : "john@example.com"
};
configCatClient.getAllValues(function(settingValues) {
settingValues.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
}, userObject);

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#");
const settingValues = await configCatClient.getAllValuesAsync();
settingValues.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));
// invoke with user object
const userObject = {
identifier : "john@example.com"
};
const settingValuesTargeting = await configCatClient.getAllValuesAsync(userObject);
settingValuesTargeting.forEach(i => console.log(i.settingKey + ' -> ' + i.settingValue));

Sample Applications

Look under the hood