@flipt-io/flipt-client-js

中文文档
0.7.0发布于 2026/11/08MITTypeScriptESM + CJS近 30 天下载 40.8万

Flipt Client Evaluation SDK for Web and Node.js

原始使用文档
文档目录24 节
  1. Installation
  2. Usage
  3. Importing Types
  4. Initialization Arguments
  5. Authentication
  6. Error Strategies
  7. Snapshotting
  8. Custom Fetcher
  9. Hooks
  10. State Management
  11. Auto-Refresh (Node.js Only)
  12. Streaming (Server-Sent Events)
  13. State Update Listeners
  14. ETag Support
  15. Slim Module
  16. Using the @flipt-io/flipt-client-js/slim Module
  17. Additional Notes
  18. Development
  19. WASM
  20. Prerequisites
  21. Build
  22. Test
  23. Contributing
  24. License

Flipt Client JS

flipt-client-js

The flipt-client-js library contains the JavaScript/TypeScript client for Flipt client-side evaluation in Web and Node.js environments. It supports:

  • Node.js
  • Browsers
  • Edge Functions (Vercel Edge, Cloudflare Workers, etc.)
  • Web Workers

Installation

[!NOTE] The Node.js build requires Node.js 20 or later.

npm install @flipt-io/flipt-client-js

Usage

import { FliptClient } from '@flipt-io/flipt-client-js';

const client = await FliptClient.init({
  namespace: 'default',
  url: 'http://localhost:8080',
  authentication: {
    clientToken: 'secret'
  }
});

const variant = client.evaluateVariant({
  flagKey: 'flag1',
  entityId: 'someentity',
  context: {
    fizz: 'buzz'
  }
});

console.log(variant);

Importing Types

All types are available from the main package export:

import type { Flag, ClientOptions, EvaluationRequest } from '@flipt-io/flipt-client-js';

Alternatively, you can import types from the dedicated /types subpath:

import type { Flag, ClientOptions, EvaluationRequest } from '@flipt-io/flipt-client-js/types';

Initialization Arguments

The FliptClient constructor accepts the following optional arguments:

  • options: An instance of the ClientOptions type that supports several options for the client. The structure is:
    • environment: The environment to use when evaluating flags (Flipt v2). If not provided, the client will default to the default environment.
    • namespace: The namespace to fetch flag state from. If not provided, the client will default to the default namespace.
    • url: The URL of the upstream Flipt instance. If not provided, the client will default to http://localhost:8080.
    • updateInterval: Node.js Only The interval (in seconds) in which to fetch new flag state. If not provided, the client will default to 120 seconds.
    • fetchMode: How the client receives flag state updates: FetchMode.Polling (default) or FetchMode.Streaming. See Streaming.
    • logger: An optional logger (debug, info, warn, error) for diagnostics such as streaming events. Logging is disabled by default.
    • authentication: The authentication strategy to use when communicating with the upstream Flipt instance. If not provided, the client will default to no authentication. See the Authentication section for more information.
    • reference: The reference to use when fetching flag state. If not provided, reference will not be used.
    • snapshot: A base64-encoded snapshot returned by client.getSnapshot(). When provided with errorStrategy: ErrorStrategy.Fallback, the client can initialize while offline and refresh from Flipt when the network becomes available.
    • fetcher: An implementation of a fetcher interface to use when requesting flag state. If not provided, a default fetcher using the browser's fetch API will be used.
    • errorStrategy: The error strategy to use when fetching flag state. If not provided, the client will default to fail. See the Error Strategies section for more information.
    • hook: A hook implementation for before and after evaluation callbacks. See the Hooks section for more information.
    • onStateUpdate: A function with no arguments that is called after the client applies changed flag state. See State Update Listeners.

Authentication

The FliptClient supports the following authentication strategies:

Error Strategies

The client errorStrategy option supports the following error strategies:

  • fail: The client will throw an error if the flag state cannot be fetched. This is the default behavior.
  • fallback: The client will maintain the last known good state and use that state for evaluation in case of an error.

Snapshotting

The client supports manual snapshotting of flag state. This is useful when an app may start before Flipt is reachable. The SDK does not write to local storage for you because browser, Node.js, edge, and worker environments store data differently.

Use getSnapshot() to export the current state, store it wherever your app prefers, and pass it back as snapshot on the next startup.

import { ErrorStrategy, FliptClient } from '@flipt-io/flipt-client-js';

const snapshot = localStorage.getItem('fliptSnapshot') ?? undefined;

const client = await FliptClient.init({
  namespace: 'default',
  url: 'https://your-flipt-instance.com',
  snapshot,
  errorStrategy: ErrorStrategy.Fallback
});

localStorage.setItem('fliptSnapshot', client.getSnapshot());

If Flipt is reachable during initialization, fresh server state replaces the provided snapshot. If Flipt is unreachable and ErrorStrategy.Fallback is set, the client evaluates using the provided snapshot.

Custom Fetcher

The FliptClient supports custom fetchers. This allows you to fetch flag state from a custom source or override HTTP headers.

The fetcher can be passed in as an argument to the FliptClient initializer function.

const client = await FliptClient.init({
  namespace: 'default',
  url: 'http://localhost:8080',
  authentication: {
    clientToken
  },
  fetcher: customFetcher
});

The fetcher is a function that takes an optional IFetcherOpts argument and returns a Promise that resolves to a Response object.

Hooks

The FliptClient supports hooks that allow you to execute custom code before and after flag evaluation. This is useful for logging, metrics collection, or other observability patterns.

Hook Interface

To use hooks, implement the Hook interface.

Example: Logging Hook

import { FliptClient } from '@flipt-io/flipt-client-js';

class LoggingHook {
  before(data: { flagKey: string }) {
    console.log(`Evaluating flag: ${data.flagKey}`);
  }

  after(data: {
    flagKey: string;
    flagType: string;
    value: string;
    reason: string;
    segmentKeys: string[];
  }) {
    console.log(
      `Flag ${data.flagKey} evaluated: type=${data.flagType}, value=${data.value}, reason=${data.reason}`
    );
  }
}

const client = await FliptClient.init({
  namespace: 'default',
  url: 'http://localhost:8080',
  hook: new LoggingHook()
});

const result = client.evaluateVariant({
  flagKey: 'my-flag',
  entityId: 'user-123',
  context: { environment: 'production' }
});

console.log(result);

The hooks are called for all evaluation methods:

  • evaluateVariant: Called once per evaluation
  • evaluateBoolean: Called once per evaluation
  • evaluateBatch: Called once before for each request, and once after for each successful response

Note: Hooks are optional. If no hook is provided, evaluations proceed normally without any callbacks.

State Management

The FliptClient class pulls flag state from the Flipt instance at the url provided in the options object on instantiation.

To update the flag state, you can call the refresh method on the FliptClient class.

[!NOTE] The refresh method returns a boolean indicating whether the flag state changed.

// Refresh the flag state
let changed = await client.refresh();

if (changed) {
  // Do something
}

Auto-Refresh (Node.js Only)

The FliptClient class supports auto-refreshing flag state.

To enable auto-refreshing, you can pass the updateInterval option to the FliptClient initializer function. Under the hood this uses a timer to fetch new flag state at a regular interval.

[!NOTE] The updateInterval option is only supported in Node.js environments.

const client = await FliptClient.init({
  namespace: 'default',
  url: 'http://localhost:8080',
  updateInterval: 30 // refresh every 30 seconds
});

Make sure to call the close method on the FliptClient class once you are done using it to stop the timer (or close the stream) and clean up resources.

client.close();

Streaming (Server-Sent Events)

Instead of polling, the client can receive flag state updates in real time over Server-Sent Events. The client refetches the flag state whenever the server signals a change, and again each time the stream reconnects so no updates are missed.

import { FliptClient, FetchMode } from '@flipt-io/flipt-client-js';

const client = await FliptClient.init({
  url: 'http://localhost:8080',
  fetchMode: FetchMode.Streaming,
  logger: console // optional
});

[!NOTE]

  • In streaming mode updateInterval is ignored and no polling timer is started.
  • Browser: the native EventSource cannot send custom headers, so authentication is not applied to the stream. Use cookie-based auth or a Flipt server that does not require authentication for the stream endpoint.
  • Node.js: streaming uses the eventsource package. Authentication headers are sent with the stream request.
  • EventSource reconnects automatically after transient errors. If the connection is closed permanently, the client logs an error (via logger) and keeps serving the last known flag state.

Call close() when you are done with the client to close the stream.

State Update Listeners

The client can tell you when flag state changes, so you can re-read the flags you care about. Listeners are called for changes applied by auto-refresh, streaming, or a manual refresh().

Register a listener when you create the client:

const client = await FliptClient.init({
  url: 'http://localhost:8080',
  fetchMode: FetchMode.Streaming,
  onStateUpdate: refreshFlags
});

Or add and remove listeners while the client is running:

const unsubscribe = client.addStateUpdateListener(refreshFlags);

// Later, to stop listening:
unsubscribe();

How listeners behave:

  • Only real changes. A listener is called after the client applies flag state that differs from the current state. Unchanged fetches and repeated streaming messages do not call it, and refresh() returns false for them.
  • Not called for initial state. The state loaded by init doesn't trigger a listener. Read the flags you need once when you register.
  • Errors don't trigger it. A failed fetch does not call listeners.
  • In order, synchronously. Listeners run in the order they were added, right after the new state is applied. A listener may evaluate flags, add or remove listeners, or call close().
  • Exceptions are logged. An exception thrown by one listener is logged with logger.error and does not stop the others.
  • Nothing after close(). No listener is called after close().

ETag Support

The default fetcher uses ETag HTTP headers to reduce the number of requests to the Flipt instance. This is useful in scenarios where the flag state is not frequently updated and you want to reduce the load on the server.

To disable ETag support, you can implement a custom fetcher that does not use ETags.

Slim Module

The slim module is designed for advanced or non-standard environments where you need full control over how the WASM binary is loaded. Unlike the default client, which tries to load the WASM file automatically, the slim client requires you to explicitly provide the WASM file (as a URL, buffer, etc.).

Why use the slim module?

  • Edge/Serverless/Custom Environments: Some platforms (like Cloudflare Workers, Vercel Edge, or certain Node.js setups) restrict how files are loaded or bundled. The slim client lets you load the WASM file in a way that works for your environment.
  • Full Control: You decide how and when the WASM file is loaded—fetch from a CDN, load from disk, or use a custom loader.
  • Compatibility: The slim client removes all assumptions about WASM loading, making it compatible with any environment where you can provide the WASM binary.
  • Bundle Size: The slim build may exclude some code related to WASM loading, making it lighter and more tree-shakable for certain use cases.

If you are using a standard browser app with a bundler, the default client is usually easier. For edge, serverless, or custom setups, the slim client is the right tool.

Using the @flipt-io/flipt-client-js/slim Module

The slim build of the FliptClient is designed for environments where you want to provide your own WASM binary, such as modern browsers (with a bundler) or Node.js.

Browser Usage (with a Bundler like Vite, Webpack, etc.)

  1. Import and initialize the client:

    import { FliptClient } from '@flipt-io/flipt-client-js/slim';
    import wasmUrl from '@flipt-io/flipt-client-js/engine.wasm';
    
    async function main() {
      const client = await FliptClient.init(
        {
          namespace: 'default',
          url: 'http://localhost:8080'
        },
        { wasm: wasmUrl }
      );
    
      // Use the client as normal
      const result = client.evaluateBoolean({
        flagKey: 'my-flag',
        entityId: 'user-123',
        context: { country: 'US' }
      });
    
      console.log(result);
    }
    
    main();
    
  2. Ensure your bundler is configured to handle .wasm files.

    • For Vite, this works out of the box.
    • For Webpack, you may need to add a rule for .wasm files.

Node.js Usage

  1. Import and initialize the client:

    import { FliptClient } from '@flipt-io/flipt-client-js/slim';
    import { readFileSync } from 'fs';
    import path from 'path';
    import { fileURLToPath } from 'url';
    
    // Resolve the path to the WASM file
    const __filename = fileURLToPath(import.meta.url);
    const __dirname = path.dirname(__filename);
    const wasmPath = path.join(
      __dirname,
      '../node_modules/@flipt-io/flipt-client-js/engine.wasm'
    );
    const wasmBuffer = readFileSync(wasmPath);
    
    async function main() {
      const client = await FliptClient.init(
        {
          namespace: 'default',
          url: 'http://localhost:8080'
        },
        { wasm: wasmBuffer }
      );
    
      // Use the client as normal
      const result = client.evaluateBoolean({
        flagKey: 'my-flag',
        entityId: 'user-123',
        context: { country: 'US' }
      });
    
      console.log(result);
    }
    
    main();
    
    • Note: In Node.js, you must load the WASM file as a buffer using fs.readFileSync.
  2. Run your script with a loader that supports ESM and top-level await, such as ts-node or tsx:

    npx tsx src/index.ts
    

Additional Notes

  • The slim build requires you to provide the WASM binary via the wasm option.
  • For browser usage, pass the URL to the WASM file (using your bundler's asset handling).
  • For Node.js, pass the WASM file as a buffer.
  • Make sure your environment supports top-level await or wrap your code in an async function.

Development

WASM

This library uses a WebAssembly (WASM) layer to interact with the Flipt server. It is written in Rust and exposes a JavaScript API using the wasm-bindgen and wasm-pack tools. We wrap the built WASM layer in a JavaScript API to make it easier to use in a web environment.

Prerequisites

Build

npm run build

Test

npm install
npm test

Contributing

Contributions are welcome! Please feel free to open an issue or submit a Pull Request.

License

This project is licensed under the MIT License.

版本与发布记录

@flipt-io/flipt-client-js 共发布 21 个版本,首次发布于 2025/03/29;过去 12 个月发布了 7 个版本。

版本发布日期距今
0.7.0latest2026/11/087 天前
0.6.02026/10/041 个月前
0.5.12026/08/292 个月前
0.5.02026/06/184 个月前
0.4.22026/04/236 个月前
0.4.12026/03/297 个月前

关于 @flipt-io/flipt-client-js 的常见问题

@flipt-io/flipt-client-js 是什么?

Flipt Client Evaluation SDK for Web and Node.js

如何安装 @flipt-io/flipt-client-js?

在项目目录运行 npm install @flipt-io/flipt-client-js,或使用 pnpm add / yarn add / bun add。

@flipt-io/flipt-client-js 支持 TypeScript 吗?

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

@flipt-io/flipt-client-js 支持 ESM 还是 CommonJS?

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

@flipt-io/flipt-client-js 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >=20。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@flipt-io/flipt-client-js 可以商用吗?

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

@flipt-io/flipt-client-js 的下载量有多少?

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

@flipt-io/flipt-client-js 还在维护吗?

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