flags-sdk

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Flags SDK

Flags SDK

The Flags SDK (
flags
npm package) is a feature flags toolkit for Next.js and SvelteKit. It turns each feature flag into a callable function, works with any flag provider via adapters, and keeps pages static using the precompute pattern. Vercel Flags is the first-party provider, letting you manage flags from the Vercel dashboard or the
vercel flags
CLI.
Flags SDK(
flags
npm包)是一款面向Next.js和SvelteKit的功能标志工具包。它将每个功能标志转换为可调用函数,通过适配器兼容任意标志提供商,并利用预计算模式保持页面静态化。Vercel Flags是官方提供商,支持通过Vercel控制台或
vercel flags
CLI管理标志。

Core concepts

核心概念

Flags as code

标志即代码

Each flag is declared as a function. No string keys at call sites:
ts
import { flag } from 'flags/next';

export const exampleFlag = flag({
  key: 'example-flag',
  decide() { return false; },
});

const value = await exampleFlag();
每个标志都声明为一个函数,调用时无需使用字符串键:
ts
import { flag } from 'flags/next';

export const exampleFlag = flag({
  key: 'example-flag',
  decide() { return false; },
});

const value = await exampleFlag();

Server-side evaluation

服务端求值

Flags evaluate server-side to avoid layout shift, keep pages static, and maintain confidentiality. Combine routing middleware with the precompute pattern to serve static variants from CDN.
标志在服务端进行求值,避免布局偏移、保持页面静态并确保数据保密。结合路由中间件与预计算模式,可从CDN提供静态变体页面。

Adapter pattern

适配器模式

Adapters replace
decide
and
origin
on a flag declaration, connecting your flags to a provider. Vercel Flags (
@flags-sdk/vercel
) is the first-party adapter. Third-party adapters are available for Statsig, LaunchDarkly, PostHog, and others.
ts
import { flag } from 'flags/next';
import { vercelAdapter } from '@flags-sdk/vercel';

export const exampleFlag = flag({
  key: 'example-flag',
  adapter: vercelAdapter,
});
Version note: The SDK is published as
flags
(renamed from
@vercel/flags
; that old name still appears in changelog history).
flags
4.2.0+ accepts the adapter factory by reference (
adapter: vercelAdapter
) and resolves it once per declaration. Older versions require calling it (
adapter: vercelAdapter()
). The called form still works on new versions, so prefer the shorthand unless you're targeting
flags
< 4.2.0.
适配器可替换标志声明中的
decide
和
origin
方法,将标志连接到对应提供商。Vercel Flags(
@flags-sdk/vercel
)是官方适配器,同时支持Statsig、LaunchDarkly、PostHog等第三方适配器。
ts
import { flag } from 'flags/next';
import { vercelAdapter } from '@flags-sdk/vercel';

export const exampleFlag = flag({
  key: 'example-flag',
  adapter: vercelAdapter,
});
版本说明:该SDK以
flags
名义发布(原名为
@vercel/flags
,旧名称仍会出现在变更历史中)。
flags
4.2.0+版本支持直接引用适配器工厂(
adapter: vercelAdapter
),并会在每次声明时解析一次。旧版本需要调用适配器(
adapter: vercelAdapter()
)。调用形式在新版本中仍可正常工作,因此除非你需要兼容
flags
< 4.2.0版本,否则建议使用简写形式。

Agent workflow: Creating a new flag

Agent工作流:创建新标志

When a user asks you to create or add a feature flag, follow these steps in order. Do not leave CLI steps as "next steps" for the user — execute them yourself.
当用户要求你创建或添加功能标志时,请按以下步骤操作。不要将CLI步骤留给用户自行完成——请你直接执行这些步骤。

Before you start

准备工作

Check the project state to adapt commands and decide which steps you can skip:
  • Which lockfile is present (
    pnpm-lock.yaml
    ,
    package-lock.json
    ,
    yarn.lock
    ,
    bun.lockb
    )? → Adapt all package manager commands accordingly (
    pnpm add
    ,
    npm install
    ,
    yarn add
    ,
    bun add
    ).
  • Is
    flags
    in
    package.json
    ? → Skip install (step 1)
  • Does
    .vercel/
    directory exist? → Project is linked, skip
    vercel link
    in step 2
  • Does
    .env.local
    contain
    FLAGS=
    ? → Env vars already pulled, skip step 3
  • Does
    flags.ts
    (or
    lib/flags.ts
    ,
    src/flags.ts
    ) exist? → Add to it rather than creating from scratch (step 4)
  • Is
    @vercel/toolbar
    in
    package.json
    ? → Skip toolbar setup (step 6)
  • Does
    app/.well-known/vercel/flags/route.ts
    exist? → Flags Explorer already set up, skip step 7
检查项目状态,调整命令并确定可跳过的步骤:
  • 项目中存在哪种锁文件(
    pnpm-lock.yaml
    、
    package-lock.json
    、
    yarn.lock
    、
    bun.lockb
    )?→ 相应调整所有包管理器命令(
    pnpm add
    、
    npm install
    、
    yarn add
    、
    bun add
    )。
  • package.json
    中是否已包含
    flags
    ?→ 跳过安装步骤(步骤1)
  • 项目中是否存在
    .vercel/
    目录?→ 项目已关联Vercel,跳过步骤2中的
    vercel link
  • .env.local
    中是否包含
    FLAGS=
    ?→ 环境变量已拉取,跳过步骤3
  • 是否存在
    flags.ts
    (或
    lib/flags.ts
    、
    src/flags.ts
    )文件?→ 在现有文件中添加标志,而非从头创建(步骤4)
  • package.json
    中是否包含
    @vercel/toolbar
    ?→ 跳过工具栏设置(步骤6)
  • 是否存在
    app/.well-known/vercel/flags/route.ts
    ?→ Flags Explorer已配置完成,跳过步骤7

Steps

步骤

  1. Install packages (if not already in
    package.json
    ):
    bash
    pnpm i flags @flags-sdk/vercel
  2. Register the flag with Vercel: Run
    vercel flags add <flag-key> --kind boolean --description "<description>"
    .
    Prerequisite: The
    vercel flags
    commands require the Vercel CLI to be installed and authenticated. If the Vercel CLI is not installed, run
    pnpm i -g vercel
    . For authentication or linking issues, follow the
    vercel-cli
    skill if it's already available. If it isn't, suggest the user install it with
    npx skills add vercel/vercel@vercel-cli
    (don't auto-install it) and rely on
    vercel <command> --help
    in the meantime.
    Before running
    vercel flags add
    , verify the project is linked to Vercel. Check for a
    .vercel
    directory in the project root. If it doesn't exist, run
    vercel link
    first.
  3. Pull environment variables: Run
    vercel env pull
    to write
    FLAGS
    and
    FLAGS_SECRET
    to
    .env.local
    . Without these environment variables,
    vercelAdapter
    will not be able to evaluate flags. This step is mandatory after creating a flag.
  4. Declare the flag in code: Add it to
    flags.ts
    (or create the file if it doesn't exist) using
    vercelAdapter
    :
    ts
    import { flag } from 'flags/next';
    import { vercelAdapter } from '@flags-sdk/vercel';
    
    export const myFlag = flag({
      key: 'my-flag',
      adapter: vercelAdapter,
    });
  5. Use the flag: Call it in your page or component and conditionally render based on the result:
    tsx
    import { myFlag } from '../flags';
    
    export default async function Page() {
      const enabled = await myFlag();
      return <div>{enabled ? 'Feature on' : 'Feature off'}</div>;
    }
  6. Set up the Vercel Toolbar (if not already present):
    • Run
      pnpm i @vercel/toolbar
    • Wrap
      next.config.ts
      with the toolbar plugin
    • Render
      <VercelToolbar />
      in the root layout See references/nextjs.md — Toolbar Setup for the full code.
  7. Set up Flags Explorer (if not already present): Create
    app/.well-known/vercel/flags/route.ts
    — see the Flags Explorer setup section below.
  1. 安装包(若
    package.json
    中未包含):
    bash
    pnpm i flags @flags-sdk/vercel
  2. 在Vercel中注册标志:运行
    vercel flags add <flag-key> --kind boolean --description "<description>"
    。
    前提条件:
    vercel flags
    命令需要安装并认证Vercel CLI。若未安装Vercel CLI,运行
    pnpm i -g vercel
    。若遇到认证或关联问题,若
    vercel-cli
    技能已可用,请遵循该技能指引;若不可用,建议用户通过
    npx skills add vercel/vercel@vercel-cli
    安装(不要自动安装),同时可参考
    vercel <command> --help
    获取帮助。
    在运行
    vercel flags add
    之前,请确认项目已关联Vercel。检查项目根目录是否存在
    .vercel
    目录,若不存在,先运行
    vercel link
    。
  3. 拉取环境变量:运行
    vercel env pull
    将
    FLAGS
    和
    FLAGS_SECRET
    写入
    .env.local
    。没有这些环境变量,
    vercelAdapter
    将无法求值标志。创建标志后,此步骤必须执行。
  4. 在代码中声明标志:使用
    vercelAdapter
    将标志添加到
    flags.ts
    (若文件不存在则创建):
    ts
    import { flag } from 'flags/next';
    import { vercelAdapter } from '@flags-sdk/vercel';
    
    export const myFlag = flag({
      key: 'my-flag',
      adapter: vercelAdapter,
    });
  5. 使用标志:在页面或组件中调用标志,并根据结果条件渲染:
    tsx
    import { myFlag } from '../flags';
    
    export default async function Page() {
      const enabled = await myFlag();
      return <div>{enabled ? '功能已开启' : '功能已关闭'}</div>;
    }
  6. 设置Vercel工具栏(若尚未配置):
    • 运行
      pnpm i @vercel/toolbar
    • 用工具栏插件包裹
      next.config.ts
    • 在根布局中渲染
      <VercelToolbar />
      完整代码请参考references/nextjs.md — Toolbar Setup。
  7. 设置Flags Explorer(若尚未配置):创建
    app/.well-known/vercel/flags/route.ts
    ——请参考下方的Flags Explorer设置章节。

Vercel Flags

Vercel Flags

Vercel Flags is Vercel's feature flags platform. You create and manage flags from the Vercel dashboard or the
vercel flags
CLI, then connect them to your code with the
@flags-sdk/vercel
adapter. When you create a flag in Vercel, the
FLAGS
and
FLAGS_SECRET
environment variables are configured automatically.
To create a flag end-to-end, follow the Agent workflow above.
For the full Vercel provider reference — user targeting,
vercel flags
CLI subcommands, custom adapter configuration, and Flags Explorer setup — see references/providers.md.
Vercel Flags是Vercel的功能标志平台。你可以通过Vercel控制台或
vercel flags
CLI创建和管理标志,然后通过
@flags-sdk/vercel
适配器将其连接到代码中。在Vercel中创建标志时,
FLAGS
和
FLAGS_SECRET
环境变量会自动配置。
要完整创建一个标志,请遵循上述Agent工作流。
关于Vercel提供商的完整参考——用户定位、
vercel flags
CLI子命令、自定义适配器配置和Flags Explorer设置——请查看references/providers.md。

Declaring flags

声明标志

When using Vercel Flags, declare flags with
vercelAdapter
as shown in the Agent workflow. For other providers, see references/providers.md. Below are the general
flag()
patterns.
使用Vercel Flags时,请按照Agent工作流中的示例,通过
vercelAdapter
声明标志。其他提供商的使用方法请查看references/providers.md。以下是通用的
flag()
模式。

Basic flag

基础标志

ts
import { flag } from 'flags/next'; // or 'flags/sveltekit'

export const showBanner = flag<boolean>({
  key: 'show-banner',
  description: 'Show promotional banner',
  defaultValue: false,
  options: [
    { value: false, label: 'Hide' },
    { value: true, label: 'Show' },
  ],
  decide() { return false; },
});
ts
import { flag } from 'flags/next'; // 或 'flags/sveltekit'

export const showBanner = flag<boolean>({
  key: 'show-banner',
  description: '显示促销横幅',
  defaultValue: false,
  options: [
    { value: false, label: '隐藏' },
    { value: true, label: '显示' },
  ],
  decide() { return false; },
});

Flag with evaluation context

带求值上下文的标志

Use
identify
to establish who the request is for. The returned entities are passed to
decide
:
ts
import { dedupe, flag } from 'flags/next';
import type { ReadonlyRequestCookies } from 'flags';

interface Entities {
  user?: { id: string };
}

const identify = dedupe(
  ({ cookies }: { cookies: ReadonlyRequestCookies }): Entities => {
    const userId = cookies.get('user-id')?.value;
    return { user: userId ? { id: userId } : undefined };
  },
);

export const dashboardFlag = flag<boolean, Entities>({
  key: 'new-dashboard',
  identify,
  decide({ entities }) {
    if (!entities?.user) return false;
    return ['user1', 'user2'].includes(entities.user.id);
  },
});
使用
identify
确定请求对应的用户,返回的实体将传递给
decide
:
ts
import { dedupe, flag } from 'flags/next';
import type { ReadonlyRequestCookies } from 'flags';

interface Entities {
  user?: { id: string };
}

const identify = dedupe(
  ({ cookies }: { cookies: ReadonlyRequestCookies }): Entities => {
    const userId = cookies.get('user-id')?.value;
    return { user: userId ? { id: userId } : undefined };
  },
);

export const dashboardFlag = flag<boolean, Entities>({
  key: 'new-dashboard',
  identify,
  decide({ entities }) {
    if (!entities?.user) return false;
    return ['user1', 'user2'].includes(entities.user.id);
  },
});

Flag with another adapter

带其他适配器的标志

Adapters connect flags to third-party providers. Each adapter replaces
decide
and
origin
:
ts
import { flag } from 'flags/next';
import { statsigAdapter } from '@flags-sdk/statsig';

export const myGate = flag({
  key: 'my_gate',
  adapter: statsigAdapter.featureGate((gate) => gate.value),
  identify,
});
See references/providers.md for all supported adapters.
适配器可将标志连接到第三方提供商,每个适配器会替换
decide
和
origin
方法:
ts
import { flag } from 'flags/next';
import { statsigAdapter } from '@flags-sdk/statsig';

export const myGate = flag({
  key: 'my_gate',
  adapter: statsigAdapter.featureGate((gate) => gate.value),
  identify,
});
所有支持的适配器请查看references/providers.md。

Key parameters

关键参数

ParameterTypeDescription
key
string
Unique flag identifier
decide
function
Resolves the flag value
defaultValue
any
Fallback if
decide
returns undefined or throws
description
string
Shown in Flags Explorer
origin
string
URL to manage the flag in provider dashboard
options
{ label?: string, value: any }[]
Possible values, used for precompute + Flags Explorer
adapter
Adapter
Provider adapter implementing
decide
and
origin
identify
function
Returns evaluation context (entities) for
decide
参数类型描述
key
string
唯一标志标识符
decide
function
解析标志值的函数
defaultValue
any
当
decide
返回undefined或抛出错误时的回退值
description
string
在Flags Explorer中显示的描述
origin
string
提供商控制台中管理该标志的URL
options
{ label?: string, value: any }[]
标志的可选值,用于预计算和Flags Explorer
adapter
Adapter
实现
decide
和
origin
方法的提供商适配器
identify
function
为
decide
返回求值上下文(实体)的函数

Dedupe

Dedupe

Wrap shared functions (especially
identify
) in
dedupe
to run them once per request:
ts
import { dedupe } from 'flags/next';

const identify = dedupe(({ cookies }) => {
  return { user: { id: cookies.get('uid')?.value } };
});
Note:
dedupe
is not available in Pages Router.
将共享函数(尤其是
identify
)包裹在
dedupe
中,可确保每个请求仅执行一次:
ts
import { dedupe } from 'flags/next';

const identify = dedupe(({ cookies }) => {
  return { user: { id: cookies.get('uid')?.value } };
});
注意:
dedupe
在Pages Router中不可用。

Bulk evaluation

批量求值

To evaluate multiple flags at once, call
evaluate()
(from
flags/next
) instead of awaiting flags one at a time or using
Promise.all()
. To evaluate a single flag, just call it:
await myFlag()
.
ts
import { evaluate } from 'flags/next';
import { flagA, flagB } from '../flags';

// avoid: each await blocks the next, so the flags resolve sequentially
const a = await flagA();
const b = await flagB();

// avoid: parallel, but each flag is evaluated in isolation
const [a, b] = await Promise.all([flagA(), flagB()]);

// prefer: shares work across the batch
const [a, b] = await evaluate([flagA, flagB]);
evaluate()
is faster than both approaches. Awaiting flags one at a time makes total latency the sum of every flag's evaluation instead of the slowest single flag, while
Promise.all()
runs them in parallel but evaluates each in isolation.
evaluate()
pre-reads headers, cookies, and overrides once for the whole batch and lets adapters resolve a group in a single call, which reduces the number of parallel promises the runtime manages and leaves less room for the async work to be interrupted by other microtasks.
It accepts either an array (positional results) or an object (keyed results):
ts
const [a, b] = await evaluate([flagA, flagB]);
const { a, b } = await evaluate({ a: flagA, b: flagB });
Outside App Router (Pages Router
getServerSideProps
/API routes, or routing middleware), pass the request as the second argument:
await evaluate([flagA, flagB], request)
.
evaluate()
always evaluates flags at request time. It is not for reading precomputed (static) values — for those, use
getPrecomputed
(or call the flag with the code,
await myFlag(code, flagGroup)
).
Adapters can opt into batching by implementing the optional
bulkDecide
hook. The Vercel adapter (
@flags-sdk/vercel
) implements it — roughly a 10x reduction in evaluation time when resolving hundreds of flags. See references/providers.md — Custom Adapters for implementing
bulkDecide
, and references/api.md —
evaluate
for the full signature.
要同时求值多个标志,请调用
evaluate()
(来自
flags/next
),而非逐个等待标志或使用
Promise.all()
。若仅需求值单个标志,直接调用即可:
await myFlag()
。
ts
import { evaluate } from 'flags/next';
import { flagA, flagB } from '../flags';

// 不推荐:每个await会阻塞下一个,标志将按顺序解析
const a = await flagA();
const b = await flagB();

// 不推荐:并行执行,但每个标志独立求值
const [a, b] = await Promise.all([flagA(), flagB()]);

// 推荐:在批量操作中共享计算资源
const [a, b] = await evaluate([flagA, flagB]);
evaluate()
比上述两种方法更快。逐个等待标志会使总延迟等于所有标志求值时间的总和,而非最慢单个标志的求值时间;
Promise.all()
虽并行执行,但每个标志独立求值。
evaluate()
会为整个批量操作预读取一次请求头、Cookie和覆盖配置,并允许适配器通过单次调用解析一组标志,从而减少运行时管理的并行Promise数量,降低异步工作被其他微任务中断的概率。
它接受数组(按位置返回结果)或对象(按键返回结果)作为参数:
ts
const [a, b] = await evaluate([flagA, flagB]);
const { a, b } = await evaluate({ a: flagA, b: flagB });
在App Router之外(Pages Router的
getServerSideProps
/API路由,或路由中间件),需将请求作为第二个参数传入:
await evaluate([flagA, flagB], request)
。
evaluate()
始终在请求时求值标志,不适用于读取预计算(静态)值——若需读取预计算值,请使用
getPrecomputed
(或通过代码调用标志:
await myFlag(code, flagGroup)
)。
适配器可通过实现可选的
bulkDecide
钩子来支持批量求值。Vercel适配器(
@flags-sdk/vercel
)已实现该钩子——当解析数百个标志时,求值时间可减少约10倍。实现
bulkDecide
的方法请查看references/providers.md — Custom Adapters,
evaluate
的完整签名请查看references/api.md —
evaluate
。

Flags Explorer setup

Flags Explorer设置

Next.js (App Router)

Next.js(App Router)

ts
// app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint } from 'flags/next';
import { getProviderData } from '@flags-sdk/vercel';
import * as flags from '../../../../flags';

export const GET = createFlagsDiscoveryEndpoint(async () => {
  return getProviderData(flags);
});
ts
// app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint } from 'flags/next';
import { getProviderData } from '@flags-sdk/vercel';
import * as flags from '../../../../flags';

export const GET = createFlagsDiscoveryEndpoint(async () => {
  return getProviderData(flags);
});

With external provider data

结合外部提供商数据

When using a third-party provider alongside Vercel Flags, combine their data with
mergeProviderData
. Each provider adapter exports its own
getProviderData
— see the provider-specific examples in references/providers.md.
当同时使用第三方提供商和Vercel Flags时,可使用
mergeProviderData
合并它们的数据。每个提供商适配器都会导出自己的
getProviderData
——具体示例请查看references/providers.md中的提供商专属内容。

SvelteKit

SvelteKit

ts
// src/hooks.server.ts
import { createHandle } from 'flags/sveltekit';
import { FLAGS_SECRET } from '$env/static/private';
import * as flags from '$lib/flags';

export const handle = createHandle({ secret: FLAGS_SECRET, flags });
ts
// src/hooks.server.ts
import { createHandle } from 'flags/sveltekit';
import { FLAGS_SECRET } from '$env/static/private';
import * as flags from '$lib/flags';

export const handle = createHandle({ secret: FLAGS_SECRET, flags });

FLAGS_SECRET

FLAGS_SECRET

Required for precompute and Flags Explorer. Must be 32 random bytes, base64-encoded:
sh
node -e "console.log(crypto.randomBytes(32).toString('base64url'))"
Use a separate
FLAGS_SECRET
value for each environment (Development, Preview, Production), and mark the Preview and Production values as Sensitive. Run the generator once per environment to produce distinct values, then store each on Vercel:
sh
vercel env add FLAGS_SECRET production --sensitive --value <production-secret>
vercel env add FLAGS_SECRET preview --sensitive --value <preview-secret>
vercel env add FLAGS_SECRET development --value <development-secret>
Then run
vc env pull
to sync to local.
预计算和Flags Explorer需要该密钥。它必须是32字节的随机字符串,并经过base64编码:
sh
node -e "console.log(crypto.randomBytes(32).toString('base64url'))"
为每个环境(开发、预览、生产)使用独立的
FLAGS_SECRET
值,并将预览和生产环境的值标记为敏感数据。为每个环境运行一次生成器以生成不同的值,然后将其存储在Vercel中:
sh
vercel env add FLAGS_SECRET production --sensitive --value <production-secret>
vercel env add FLAGS_SECRET preview --sensitive --value <preview-secret>
vercel env add FLAGS_SECRET development --value <development-secret>
然后运行
vc env pull
同步到本地。

Precompute pattern

预计算模式

Use precompute to keep pages static while using feature flags. Middleware evaluates flags and encodes results into the URL via rewrite. The page reads precomputed values instead of re-evaluating.
High-level flow:
  1. Declare flags and group them in an array
  2. Call
    precompute(flagGroup)
    in middleware, get a
    code
    string
  3. Rewrite request to
    /${code}/original-path
  4. Page reads flag values from
    code
    :
    await myFlag(code, flagGroup)
For full implementation details, see framework-specific references:
  • Next.js: See references/nextjs.md — covers proxy middleware, precompute setup, ISR, generatePermutations, multiple groups
  • SvelteKit: See references/sveltekit.md — covers reroute hook, middleware, precompute setup, ISR, prerendering
使用预计算模式可在使用功能标志的同时保持页面静态化。中间件会求值标志并将结果编码到URL中,通过重定向实现。页面将读取预计算值,而非重新求值。
大致流程:
  1. 声明标志并将其分组为数组
  2. 在中间件中调用
    precompute(flagGroup)
    ,获取
    code
    字符串
  3. 将请求重定向到
    /${code}/original-path
  4. 页面从
    code
    中读取标志值:
    await myFlag(code, flagGroup)
完整实现细节请查看框架专属参考:
  • Next.js:查看references/nextjs.md——涵盖代理中间件、预计算设置、ISR、generatePermutations、多组标志等内容
  • SvelteKit:查看references/sveltekit.md——涵盖重定向钩子、中间件、预计算设置、ISR、预渲染等内容

Custom adapters

自定义适配器

Create an adapter factory that returns an object with
origin
and
decide
. For the full pattern (including default adapter and singleton client examples), see references/providers.md.
创建一个适配器工厂,返回包含
origin
和
decide
方法的对象。完整模式(包括默认适配器和单例客户端示例)请查看references/providers.md。

Encryption functions

加密函数

For keeping flag data confidential in the browser (used by Flags Explorer):
FunctionPurpose
encryptFlagValues
Encrypt resolved flag values
decryptFlagValues
Decrypt flag values
encryptFlagDefinitions
Encrypt flag definitions/metadata
decryptFlagDefinitions
Decrypt flag definitions
encryptOverrides
Encrypt toolbar overrides
decryptOverrides
Decrypt toolbar overrides
All use
FLAGS_SECRET
by default. Example:
tsx
import { encryptFlagValues } from 'flags';
import { FlagValues } from 'flags/react';

async function ConfidentialFlags({ values }) {
  const encrypted = await encryptFlagValues(values);
  return <FlagValues values={encrypted} />;
}
用于在浏览器中保护标志数据的机密性(Flags Explorer使用):
函数名称用途
encryptFlagValues
加密已解析的标志值
decryptFlagValues
解密标志值
encryptFlagDefinitions
加密标志定义/元数据
decryptFlagDefinitions
解密标志定义
encryptOverrides
加密工具栏覆盖配置
decryptOverrides
解密工具栏覆盖配置
所有函数默认使用
FLAGS_SECRET
作为密钥。示例:
tsx
import { encryptFlagValues } from 'flags';
import { FlagValues } from 'flags/react';

async function ConfidentialFlags({ values }) {
  const encrypted = await encryptFlagValues(values);
  return <FlagValues values={encrypted} />;
}

React components

React组件

tsx
import { FlagValues, FlagDefinitions } from 'flags/react';

// Renders script tag with flag values for Flags Explorer
<FlagValues values={{ myFlag: true }} />

// Renders script tag with flag definitions for Flags Explorer
<FlagDefinitions definitions={{ myFlag: { options: [...], description: '...' } }} />
tsx
import { FlagValues, FlagDefinitions } from 'flags/react';

// 渲染包含标志值的脚本标签,供Flags Explorer使用
<FlagValues values={{ myFlag: true }} />

// 渲染包含标志定义的脚本标签,供Flags Explorer使用
<FlagDefinitions definitions={{ myFlag: { options: [...], description: '...' } }} />

References

参考文档

Detailed framework and provider guides are in separate files to keep context lean:
  • references/nextjs.md: Next.js quickstart, toolbar, App Router, Pages Router, middleware/proxy, precompute, dedupe, dashboard pages, marketing pages, suspense fallbacks
  • references/sveltekit.md: SvelteKit quickstart, toolbar, hooks setup, precompute with reroute + middleware, dashboard pages, marketing pages
  • references/providers.md: All provider adapters — Vercel, Global Config, Statsig, LaunchDarkly, PostHog, GrowthBook, Hypertune, Flagsmith, Reflag, Split, Optimizely, OpenFeature, and custom adapters
  • references/api.md: Full API reference for
    flags
    ,
    flags/react
    ,
    flags/next
    , and
    flags/sveltekit
详细的框架和提供商指南位于单独的文件中,以保持内容简洁:
  • references/nextjs.md:Next.js快速入门、工具栏、App Router、Pages Router、中间件/代理、预计算、dedupe、仪表盘页面、营销页面、Suspense回退等内容
  • references/sveltekit.md:SvelteKit快速入门、工具栏、钩子设置、结合重定向+中间件的预计算、仪表盘页面、营销页面等内容
  • references/providers.md:所有提供商适配器——Vercel、全局配置、Statsig、LaunchDarkly、PostHog、GrowthBook、Hypertune、Flagsmith、Reflag、Split、Optimizely、OpenFeature及自定义适配器
  • references/api.md:
    flags
    、
    flags/react
    、
    flags/next
    和
    flags/sveltekit
    的完整API参考