@cloudflare/flagship

中文文档
0.7.0发布于 2026/11/04Apache-2.0TypeScriptESM + CJS构建来源已验证近 30 天下载 35.8万

OpenFeature provider for Flagship feature flags

原始使用文档
文档目录14 节
  1. Install
  2. Quick start — server
  3. Quick start — Cloudflare Workers
  4. Quick start — HTTP
  5. Structured evaluation context
  6. Caching
  7. Local evaluation
  8. Quick start — browser
  9. Features
  10. Packages
  11. Documentation
  12. Development
  13. Contributing
  14. License

@cloudflare/flagship

npm version npm downloads license

OpenFeature-compliant provider SDK for Flagship, Cloudflare's globally distributed, low-latency feature flag platform.

Server-side (Node.js, Cloudflare Workers) and client-side (browser) support via isolated sub-path exports. Tree-shakeable — importing @cloudflare/flagship/server never loads @openfeature/web-sdk and vice versa.

Install

Server-side (Node.js, Cloudflare Workers):

npm install @cloudflare/flagship @openfeature/server-sdk

Client-side (browser):

npm install @cloudflare/flagship @openfeature/web-sdk

Quick start — server

import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';

await OpenFeature.setProviderAndWait(
  new FlagshipServerProvider({ appId: 'your-app-id', accountId: 'your-account-id', authToken: 'your-token' }),
);

const client = OpenFeature.getClient();
const enabled = await client.getBooleanValue('dark-mode', false, { userId: 'user-123' });

Quick start — Cloudflare Workers

The recommended approach for Cloudflare Workers. Uses a wrangler binding — no HTTP overhead, no auth tokens needed.

Configure in wrangler.json:

{
  "flagship": [{ "binding": "FLAGS", "app_id": "<your-app-id>" }]
}
import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';
import type { FlagshipBinding } from '@cloudflare/flagship/server';

export default {
  async fetch(request: Request, env: { FLAGS: FlagshipBinding }): Promise<Response> {
    await OpenFeature.setProviderAndWait(new FlagshipServerProvider({ binding: env.FLAGS }));

    const client = OpenFeature.getClient();
    const darkMode = await client.getBooleanValue('dark-mode', false, {
      targetingKey: new URL(request.url).searchParams.get('userId') ?? 'anonymous',
    });

    return Response.json({ darkMode });
  },
};

Quick start — HTTP

For Workers without a Flagship binding, or non-Workers server environments:

import { OpenFeature } from '@openfeature/server-sdk';
import { FlagshipServerProvider } from '@cloudflare/flagship/server';

let initialized = false;

export default {
  async fetch(request: Request): Promise<Response> {
    if (!initialized) {
      await OpenFeature.setProviderAndWait(
        new FlagshipServerProvider({ appId: 'your-app-id', accountId: 'your-account-id', authToken: 'your-token' }),
      );
      initialized = true;
    }

    const client = OpenFeature.getClient();
    const darkMode = await client.getBooleanValue('dark-mode', false, {
      userId: new URL(request.url).searchParams.get('userId') ?? 'anonymous',
    });

    return Response.json({ darkMode });
  },
};

Structured evaluation context

Binding and HTTP modes support nested objects, arrays, and null in evaluation context. Dates are recursively converted to ISO-8601 strings.

const checkout = await client.getStringValue('checkout-flow', 'control', {
  targetingKey: 'user-123',
  profile: { account: { plan: 'enterprise' } },
  tags: ['beta', 'internal'],
});

Primitive-only HTTP context keeps using GET query parameters. Structured context, including null, uses the JSON POST endpoint; in browsers this adds a CORS preflight request. Only strings, numbers, booleans, null, dates, arrays, and plain objects are supported. Anything else, including cyclic values, resolves with INVALID_CONTEXT without making a binding or HTTP call.

Caching

The server provider can cache evaluations to avoid a network round-trip (HTTP mode) or binding call (binding mode) for repeated flag/context pairs. Caching is off by default and enabled by setting cacheTtl:

new FlagshipServerProvider({
  appId: 'your-app-id',
  accountId: 'your-account-id',
  cacheTtl: 30_000, // ms — enables caching; values may be up to this stale
  cacheMaxSize: 1000, // max cached entries, LRU-evicted (default: 1000)
});

Each entry is keyed by flag key, type, and the full evaluation context, so distinct contexts never share a value. Cache hits resolve with reason: 'CACHED'. Disabled flags and errors are never cached. Because freshness is TTL-based, a flag change in Flagship takes effect after the entry expires.

Local evaluation

Server providers can download flag definitions once and evaluate flags in-process with no network call per evaluation. Definitions refresh lazily in the background (stale-while-revalidate on evaluate).

await OpenFeature.setProviderAndWait(
  new FlagshipServerProvider({
    appId: 'your-app-id',
    accountId: 'your-account-id', // required — used as the rollout hash seed
    authToken: 'your-read-token', // needs app **read** permission, not evaluate
    localEvaluation: true,
    refreshInterval: 30_000, // ms between background refreshes (default 30s)
  }),
);

Notes:

  • Incompatible with binding mode and with cacheTtl (there is nothing to cache).
  • accountId is always required in local mode, including when endpoint is used.
  • With endpoint, the URL path must end in /evaluate so /definitions can be derived.
  • Local evaluations do not appear in server-side analytics.
  • See examples/server-local.ts.

Quick start — browser

import { OpenFeature } from '@openfeature/web-sdk';
import { FlagshipClientProvider } from '@cloudflare/flagship/web';

await OpenFeature.setProviderAndWait(
  new FlagshipClientProvider({
    appId: 'your-app-id',
    accountId: 'your-account-id',
    authToken: 'your-token',
  }),
);

await OpenFeature.setContext({ userId: 'user-123', plan: 'premium' });

const client = OpenFeature.getClient();
const darkMode = client.getBooleanValue('dark-mode', false);

Features

FeatureDescription
OpenFeature compliantImplements the CNCF OpenFeature specification
Workers bindingNative wrangler binding support — zero HTTP overhead, no auth tokens
Server + clientAsync per-request (server) and sync cache-based (browser) providers
Server providersFlagshipServerProvider works via HTTP, local evaluation, or wrangler binding
Local evaluationIn-process evaluation from downloaded definitions (localEvaluation: true)
All flag typesBoolean, string, number, and object (JSON)
AuthenticationauthToken option adds Authorization: Bearer to every request (HTTP only)
Logginglogging option surfaces fetch errors and cache misses (off by default)
Response cachingOpt-in per-context TTL + LRU cache via cacheTtl (off by default)
Retries + timeoutsConfigurable retry logic with AbortController-based timeouts (HTTP only)
Custom transportInject fetch per client or per call — no global mutation (HTTP only)
CancellationCaller AbortSignal aborts the in-flight request, never retried (HTTP only)
HooksBuilt-in LoggingHook and TelemetryHook
Tree-shakeableServer and client bundles are fully isolated
TypeScriptStrict types throughout

Packages

ExportDescriptionPeer dependency
@cloudflare/flagshipCore client, types, errorsNone
@cloudflare/flagship/serverFlagshipServerProvider + hooks@openfeature/server-sdk
@cloudflare/flagship/webFlagshipClientProvider@openfeature/web-sdk

Documentation

Development

pnpm install         # install dependencies
pnpm run dev         # watch mode
pnpm run test        # run tests
pnpm run build       # build for distribution

Contributing

Contributions are welcome. Please open an issue first to discuss what you'd like to change. See the repository for more details.

License

Apache-2.0

版本与发布记录

@cloudflare/flagship 共发布 14 个版本,首次发布于 2026/03/30;过去 12 个月发布了 14 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.7.0latest2026/11/045 天前
0.6.02026/10/051 个月前
0.5.02026/08/102 个月前
0.4.22026/06/294 个月前
0.4.12026/06/294 个月前
0.4.02026/06/244 个月前

关于 @cloudflare/flagship 的常见问题

@cloudflare/flagship 是什么?

OpenFeature provider for Flagship feature flags

如何安装 @cloudflare/flagship?

在项目目录运行 npm install @cloudflare/flagship,或使用 pnpm add / yarn add / bun add。

@cloudflare/flagship 支持 TypeScript 吗?

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

@cloudflare/flagship 支持 ESM 还是 CommonJS?

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

@cloudflare/flagship 可以商用吗?

@cloudflare/flagship 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@cloudflare/flagship 的下载量有多少?

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

@cloudflare/flagship 还在维护吗?

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