Skip to main content

Server Side SDKs

tip

Server Side SDKs can run in 2 different modes: Local Evaluation and Remote Evaluation. We recommend reading up about the differences first before integrating the SDKS into your applications.

SDK Overview

Add the Flagsmith package

npm install flagsmith-nodejs

Initialise the SDK

tip

Server-side SDKs must be initialised with Server-side Environment keys. These can be created in the Environment settings area and should be considered secret.

import { Flagsmith } from 'flagsmith-nodejs';

const flagsmith = new Flagsmith({
environmentKey: 'FLAGSMITH_SERVER_SIDE_ENVIRONMENT_KEY',
});

Get Flags for an Environment

const flags = await flagsmith.getEnvironmentFlags();
const showButton = flags.isFeatureEnabled('secret_button');
const buttonData = flags.getFeatureValue('secret_button');

Get Flags for an Identity

const identifier = 'delboy@trotterstraders.co.uk';
const traitList = { car_type: 'robin_reliant' };

const flags = await flagsmith.getIdentityFlags(identifier, traitList);
var showButton = flags.isFeatureEnabled('secret_button');
var buttonData = flags.getFeatureValue('secret_button');

When running in Remote Evaluation mode

  • When requesting Flags for an Identity, all the Traits defined in the SDK will automatically be persisted against the Identity within the Flagsmith API.
  • Traits passed to the SDK will be added to all the other previously persisted Traits associated with that Identity.
  • This full set of Traits are then used to evaluate the Flag values for the Identity.
  • This all happens in a single request/response.

When running in Local Evaluation mode

  • Only the Traits provided to the SDK at runtime will be used. Local Evaluation mode, by design, does not make any network requests to the Flagsmith API when evaluating Flags for an Identity.
    • When running in Local Evaluation Mode, the SDK requests the Environment Document from the Flagsmith API. This contains all the information required to make Flag Evaluations, but it does not contain any Trait data.

Managing Default Flags

Default Flags are configured by passing in a function that is called when a Flag cannot be found or if the network request to the API fails when retrieving flags.

const flagsmith = new Flagsmith({
environmentKey,
enableLocalEvaluation: true,
defaultFlagHandler: (str) => {
return { enabled: false, isDefault: true, value: { colour: '#ababab' } };
},
});

Using an Offline Handler

info

Offline handlers are still in active development. We are building them for all our SDKs; those that are production ready are listed below.

Progress on the remaining SDKs can be seen here.

Flagsmith SDKs can be configured to include an offline handler which has 2 functions:

  1. It can be used alongside Offline Mode to evaluate flags in environments with no network access
  2. It can be used as a means of defining the behaviour for evaluating default flags, when something goes wrong with the regular evaluation process. To do this, simply set the offline handler initialisation parameter without enabling offline mode.

To use it as a default handler, we recommend using the flagsmith CLI to generate the Environment Document and use our LocalFileHandler class, but you can also create your own offline handlers, by extending the base class.

Use LocalFileHandler to read an environment file generated by the Flagsmith CLI:

import { Flagsmith, LocalFileHandler } from 'flagsmith-nodejs';

const flagsmith = new Flagsmith({
offlineMode: true,
offlineHandler: new LocalFileHandler('./flagsmith.json'),
});

To create your own offline handler, implement the BaseOfflineHandler interface. It must return an EnvironmentModel object:

import type { BaseOfflineHandler, EnvironmentModel } from 'flagsmith-nodejs';

class CustomOfflineHandler implements BaseOfflineHandler {
getEnvironment(): EnvironmentModel {
// ...
}
}

Network Behaviour

The Server Side SDKS share the same network behaviour across the different languages:

Remote Evaluation Mode Network Behaviour

  • A blocking network request is made every time you make a call to get an Environment Flags. In Python, for example, flagsmith.get_environment_flags() will trigger this request.
  • A blocking network request is made every time you make a call to get an Identities Flags. In Python, for example, flagsmith.get_identity_flags(identifier=identifier, traits=traits) will trigger this request.

Local Evaluation Mode Network Behaviour

info

When using Local Evaluation, it's important to read up on the Pros, Cons and Caveats.

To use Local Evaluation mode, you must use a Server Side key.

  • When the SDK is initialised, it will make an asynchronous network request to retrieve details about the Environment.
  • Every 60 seconds (by default), it will repeat this aysnchronous request to ensure that the Environment information it has is up to date.

To achieve Local Evaluation, in most languages, the SDK spawns a separate thread (or equivalent) to poll the API for changes to the Environment. In certain languages, you may be required to terminate this thread before cleaning up the instance of the Flagsmith client. Languages in which this is necessary are provided below.

flagsmith.close();

Offline Mode

To run the SDK in a fully offline mode, you can set the client to offline mode. This will prevent the SDK from making any calls to the Flagsmith API. To use offline mode, you must also provide an offline handler. See Configuring the SDK for more details on initialising the SDK in offline mode.

Configuring the SDK

You can modify the behaviour of the SDK during initialisation. Full configuration options are shown below.

import { Flagsmith } from 'flagsmith-nodejs';
import type { EnvironmentModel } from 'flagsmith-nodejs';

const flagsmith = new Flagsmith({
/*
Your API Token.
Note that this is either the `Environment API` key or the `Server Side SDK Token`
depending on if you are using Local or Remote Evaluation
Required.
*/
environmentKey: 'FLAGSMITH_SERVER_SIDE_ENVIRONMENT_KEY',

/*
Override the default Flagsmith API URL if you are self-hosting.
Optional.
Defaults to https://edge.api.flagsmith.com/api/v1/
*/
apiUrl: 'https://api.yourselfhostedflagsmith.com/api/v1/',

/*
Adds caching support
Optional
See https://docs.flagsmith.com/clients/server-side#caching
*/
cache: {
get: (key: string) => Promise.resolve(),
set: (k: string, v: Flags) => Promise.resolve(),
},

/*
Custom http headers can be added to the http client
Optional
*/
customHeaders: { aHeader: 'aValue' },

/*
Controls whether Flag Analytics data is sent to the Flagsmith API
See https://docs.flagsmith.com/advanced-use/flag-analytics
Optional
Defaults to false
*/
enableAnalytics: true,

/*
Controls which mode to run in; local or remote evaluation.
See the `SDKs Overview Page` for more info
Optional.
Defaults to false.
*/
enableLocalEvaluation: true,

/*
Set environment refresh rate with polling manager.
Only needed when local evaluation is true.
Optional.
Defaults to 60 seconds
*/
environmentRefreshIntervalSeconds: 60,

/*
The network timeout in seconds.
Optional.
Defaults to 10 seconds
*/
requestTimeoutSeconds: 30,

/*
You can specify default Flag values on initialisation.
Optional
*/
defaultFlagHandler: (featureName: string) => {
return { enabled: false, isDefault: true, value: null };
},

/*
A callback for whenever the environment model is updated or there is an error retrieving it.
This is only used in local evaluation mode.
Optional
*/
onEnvironmentChange: (error: Error | null, result: EnvironmentModel) => {},
});

Caching

Some SDKs support caching flags retrieved from the Flagsmith API, or calculated from your environment definition if using Local Evaluation.

The cache option in the Flagsmith constructor accepts a cache implementation. This cache must implement the FlagsmithCache interface.

For example, this cache implementation uses Redis as a backing store:

import { Flagsmith } from 'flagsmith-nodejs';
import type { BaseOfflineHandler, EnvironmentModel, Flags, FlagsmithCache } from 'flagsmith-nodejs';
import * as redis from 'redis';

const redisClient = redis.createClient({
url: 'localhost:6379',
});

const redisFlagsmithCache = {
async get(key: string): Promise<Flags | undefined> {
const cachedValue = await redisClient.get(key);
return Promise.resolve(cachedValue && JSON.parse(cachedValue));
},
async set(key: string, value: Flags): Promise<void> {
await redisClient.set(key, JSON.stringify(value), { EX: 60 });
return Promise.resolve();
},
} satisfies FlagsmithCache;

const flagsmith = new Flagsmith({
environmentKey: 'ser...',
cache: redisFlagsmithCache,
});

Logging

The following SDKs have code and functionality related to logging.

Logging is disabled by default. If you would like to enable it then call .enableLogging() on the client builder:

FlagsmithClient flagsmithClient = FlagsmithClient.newBuilder()
// other configuration as shown above
.enableLogging()
.build();

Flagsmith uses SLF4J and we only implement its API. If your project does not already have SLF4J, then include an implementation, i.e.:

<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>${slf4j.version}</version>
</dependency>

Contribute to the SDKs

All our SDKs are Open Source.