@featbit/node-server-sdk

中文文档
1.4.1发布于 2026/11/03MITTypeScriptESM + CJS近 30 天下载 5.7万
原始使用文档
文档目录17 节
  1. Introduction
  2. Data synchronization
  3. Get Started
  4. Installation
  5. Prerequisite
  6. Quick Start
  7. Examples
  8. SDK
  9. FbClientNode
  10. Evaluating flags
  11. Logger
  12. Offline Mode
  13. Disable Events Collection
  14. Experiments (A/B/n Testing)
  15. Supported Node.js versions
  16. Getting support
  17. See Also

FeatBit Server-Side SDK for Node.js

Introduction

This is the Node.js Server-Side SDK for the 100% open-source feature flags management platform FeatBit.

The FeatBit Server-Side SDK for Node.js is designed primarily for use in multi-user systems such as web servers and applications. It is not intended for use in desktop and embedded systems applications.

Data synchronization

We use WebSocket or Polling to make the local data synchronized with the server, and then store them in memory by default. Whenever there is any change to a feature flag or its related data, this change will be pushed to the SDK, the average synchronization time is less than 100ms. Be aware the WebSocket/Polling connection may be interrupted due to internet outage, but it will be resumed automatically once the problem is gone.

Get Started

Installation

The latest stable version is available on npm.

npm install --save @featbit/node-server-sdk

Prerequisite

Before using the SDK, you need to obtain the environment secret (the sdkKey) and SDK URLs.

Follow the documentation below to retrieve these values

Quick Start

The following code demonstrates the basic usage of @featbit/node-server-sdk.

import { FbClientBuilder, UserBuilder } from "@featbit/node-server-sdk";

// setup SDK options
const fbClient = new FbClientBuilder()
    .sdkKey("your_sdk_key")
    .streamingUri('ws://localhost:5100')
    .eventsUri("http://localhost:5100")
    .build();

(async () => {
  // wait for the SDK to be initialized
  try {
    await fbClient.waitForInitialization();
  } catch(err) {
    // failed to initialize the SDK
    console.log(err);
  }

  // flag to be evaluated
  const flagKey = "game-runner";
  
  // create a user
  const user = new UserBuilder('a-unique-key-of-user')
    .name('bob')
    .custom('sex', 'female')
    .custom('age', 18)
    .build();

  // evaluate a feature flag for a given user
  const boolVariation = await fbClient.boolVariation(flagKey, user, false);
  console.log(`flag '${flagKey}' returns ${boolVariation} for user ${user.Key}`);

  // evaluate a boolean flag for a given user with evaluation detail
  const boolVariationDetail = await fbClient.boolVariationDetail(flagKey, user, false);
  console.log(`flag '${flagKey}' returns ${boolVariationDetail.value} for user ${user.Key}` +
  `Reason Kind: ${boolVariationDetail.kind}, Reason Description: ${boolVariationDetail.reason}`);

  // make sure the events are flushed before exit
  await fbClient.close();
})();

Examples

SDK

FbClientNode

The FbClientNode is the heart of the SDK which provides access to FeatBit server. Applications should instantiate a single instance for the lifetime of the application.

FbClientBuilder is used to construct a FbClientNode instance. The builder exposes methods to configure the SDK, and finally to create the FbClientNode instance.

FbClient Using Streaming

import { FbClientBuilder } from "@featbit/node-server-sdk";

const fbClient = new FbClientBuilder()
    .sdkKey("your_sdk_key")
    .streamingUri('ws://localhost:5100')
    .eventsUri("http://localhost:5100")
    .build();

FbClient Using Polling

import { FbClientBuilder, DateSyncMode } from "@featbit/node-server-sdk";

const fbClient = new FbClientBuilder()
    .sdkKey("your_sdk_key")
    .dataSyncMode(DateSyncMode.POLLING)
    .pollingUri('http://localhost:5100')
    .eventsUri("http://localhost:5100")
    .pollingInterval(10000)
    .build();

IUser

IUser defines the attributes of a user for whom you are evaluating feature flags. IUser has two built-in attributes: key and name. The only mandatory attribute of a IUser is the key, which must uniquely identify each user.

Besides these built-in properties, you can define any additional attributes associated with the user using custom(string key, string value) method on UserBuilder. Both built-in attributes and custom attributes can be referenced in targeting rules, and are included in analytics data.

If a user attribute is missing or null, conditions on that attribute do not match, including negated operators such as NotEqual and NotOneOf. An existing empty-string value is compared normally. Evaluation continues with subsequent rules and then the flag's default rule if none match.

UserBuilder is used to construct a IUser instance. The builder exposes methods to configure the IUser, and finally to create the IUser instance.

import { UserBuilder } from "@featbit/node-server-sdk";

const bob = new UserBuilder("unique_key_for_bob")
    .name("Bob")
    .custom('age', 18)
    .custom('country', 'FR')
    .build();

Alternatively, you can create a user object directly without using UserBuilder:

import { IUser } from "@featbit/node-server-sdk";

const bob: IUser = {
    key: "unique_key_for_bob",
    name: "Bob",
    customizedProperties: [
        { name: "age", value: "18" },
        { name: "country", value: "FR" },
    ],
};

Evaluating flags

By using the feature flag data it has already received, the SDK locally calculates the value of a feature flag for a given user.

There is a variation method that returns a flag value, and a variationDetail method that returns an object describing how the value was determined for each type.

  • boolVariation/boolVariationDetail
  • stringVariation/stringVariationDetail
  • numberVariation/numberVariationDetail
  • jsonVariation/jsonVariationDetail

Variation calls take the feature flag key, a IUser, and a default value. If any error makes it impossible to evaluate the flag (for instance, the feature flag key does not match any existing flag), default value is returned.

// flag to be evaluated
const flagKey = "game-runner";

// create a user
const user = new UserBuilder('a-unique-key-of-user')
    .name('bob')
    .custom('sex', 'female')
    .custom('age', 18)
    .build();

// evaluate a feature flag for a given user
const boolVariation = await fbClient.boolVariation(flagKey, user, false);
console.log(`flag '${flagKey}' returns ${boolVariation} for user ${user.Key}`);

// evaluate a boolean flag for a given user with evaluation detail
const boolVariationDetail = await fbClient.boolVariationDetail(flagKey, user, false);
console.log(`flag '${flagKey}' returns ${boolVariationDetail.value} for user ${user.Key}` +
    `Reason Kind: ${boolVariationDetail.kind}, Reason Description: ${boolVariationDetail.reason}`);

Logger

The default logger uses none as log level which means it will output nothing. If the default logger does not fit your needs, you have two options.

Use a different log level

const fbClient = new FbClientBuilder()
    .logLevel('debug')
    ...
    .build();

// or
const options = {
  ...
  logLevel: 'debug'
}

const fbClient = new FbClientBuilder(options).build();

Define your own logger

Your logger must implement the ILogger interface, we provided a BasicLogger, you can use it like this:

const logger = new BasicLogger({
    level: 'debug',
    destination: console.log
});

const fbClient = new FbClientBuilder()
    .logger(logger)
    ...
    .build();

// or
const options = {
  ...
  logger: logger
}

const fbClient = new FbClientBuilder(options).build();

Be aware that the logger option has a higher priority than logLevel. If you pass both options, logLevel would be ignored.

Offline Mode

In some situations, you might want to stop making remote calls to FeatBit. Here is how:

import { FbClientBuilder } from "@featbit/node-server-sdk";

const fbClient = new FbClientBuilder()
    .offline(true)
    .build();

NOTE: Populating data from a JSON string is only supported in offline mode.

The format of the data in flags and segments is defined by FeatBit and is subject to change. Rather than trying to construct these objects yourself, it's simpler to request existing flags directly from the FeatBit server in JSON format and use this output as the starting point for your file. Here's how:

# replace http://localhost:5100 with your evaluation server url
curl -H "Authorization: <your-env-secret>" http://localhost:5100/api/public/sdk/server/latest-all > featbit-bootstrap.json

Then use that file to initialize FbClient:

import { FbClientBuilder } from "@featbit/node-server-sdk";
import fs from 'fs';

let data: string = '';
try {
  data = fs.readFileSync('path_to_the_json_file', 'utf8');
} catch (err) {
  console.error(err);
}

const fbClient = new FbClientBuilder()
    .offline(false)
    .useJsonBootstrapProvider(data)
    .build();

Disable Events Collection

By default, the SDK automatically sends events (flag evaluation events and metric events for A/B testing) to the FeatBit server, unless the SDK is in offline mode.

If you prefer to disable this event collection while the SDK is in online mode, you can configure this behavior using the disableEvents option.

import { FbClientBuilder } from "@featbit/node-server-sdk";

const fbClient = new FbClientBuilder()
        .disableEvents(true)
        .build();

Flag evaluation event collection is also controlled by the per-flag insightsEnabled setting received from the FeatBit server:

  • false: disables evaluation event collection for that flag without changing its evaluation result.
  • true or absent: allows evaluation event collection, provided SDK-wide event collection is enabled.

disableEvents must be false (the default) and the SDK must be online for per-flag insights to collect evaluation events. Setting insightsEnabled to true does not override disableEvents or offline mode. The insightsEnabled setting does not affect custom metric events sent through track(); those remain subject to SDK-wide event collection settings.

Experiments (A/B/n Testing)

We support automatic experiments for pageviews and clicks, you just need to set your experiment on our SaaS platform, then you should be able to see the result in near real time after the experiment is started.

In case you need more control over the experiment data sent to our server, we offer a method to send custom event.

fbClient.track(user, eventName, numericValue);

numericValue is not mandatory, the default value is 1.0.

Make sure track is called after the related feature flag is called, otherwise the custom event won't be included into the experiment result.

Supported Node.js versions

This version of the SDK should work for the recent versions of Node.js, if you see any issues with a specific version, please create an issue.

Getting support

  • If you have a specific question about using this sdk, we encourage you to ask it in our slack.
  • If you encounter a bug or would like to request a feature, submit an issue.

See Also

版本与发布记录

@featbit/node-server-sdk 共发布 10 个版本,首次发布于 2024/01/08;过去 12 个月发布了 4 个版本。

版本发布日期距今
1.4.1latest2026/11/0310 天前
1.4.02026/10/3114 天前
1.3.22026/10/091 个月前
1.3.12026/08/172 个月前
1.3.02025/11/071 年前
1.2.22025/10/141.1 年前

关于 @featbit/node-server-sdk 的常见问题

@featbit/node-server-sdk 是什么?

https://github.com/featbit/featbit-node-server-sdk

如何安装 @featbit/node-server-sdk?

在项目目录运行 npm install @featbit/node-server-sdk,或使用 pnpm add / yarn add / bun add。

@featbit/node-server-sdk 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@featbit/node-server-sdk 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@featbit/node-server-sdk 可以商用吗?

@featbit/node-server-sdk 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@featbit/node-server-sdk 的下载量有多少?

根据 npm 官方下载统计,@featbit/node-server-sdk 在 2026/10/15 – 2026/11/13 这 30 天内被下载 56,510 次,日均约 1,884 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@featbit/node-server-sdk 还在维护吗?

最新版本 1.4.1 发布于 2026/11/03(10 天前);至今共发布 10 个版本,其中过去 12 个月发布了 4 个;首次发布于 2024/01/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。