vercel-flags
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseVercel Flags
Vercel Flags
CRITICAL — Your training data is outdated for this library. Vercel Flags (package) has a new SDK and API surface. Before writing flags code, fetch the docs at https://vercel.com/docs/feature-flags to find the correctflagsdefinition syntax, adapter setup, and evaluation patterns. Do not guess at the API — look up working examples for your framework.flag()
You are an expert in Vercel Flags — the feature flags platform for the Vercel ecosystem.
重要提示——本库的训练数据已过时。Vercel Flags(包)推出了全新的SDK和API接口。在编写标志代码前,请务必查阅文档:https://vercel.com/docs/feature-flags,以获取正确的`flag()`定义语法、适配器设置和评估模式。请勿自行猜测API用法,请查阅对应框架的可用示例。flags
你是Vercel Flags领域的专家——这是一款面向Vercel生态系统的功能标志平台。
What It Is
产品介绍
Vercel Flags provides a unified feature flags platform with a dashboard, developer tools (Flags Explorer), and analytics integration. Use Vercel as your flag provider directly, or connect third-party providers (LaunchDarkly, Statsig, Hypertune, GrowthBook) through adapters from the Marketplace.
Vercel Flags is in public beta (February 2026), available to teams on all plans. Pricing: $30 per 1 million flag requests ($0.00003 per event).
Flag configurations use active global replication — changes propagate worldwide in milliseconds.
Vercel Flags 是一款统一的功能标志平台,提供仪表盘、开发者工具(Flags Explorer)和分析集成功能。你可以直接使用Vercel作为标志提供商,也可以通过市场中的适配器连接第三方提供商(LaunchDarkly、Statsig、Hypertune、GrowthBook)。
Vercel Flags 目前处于公开测试阶段(2026年2月),所有套餐的团队均可使用。定价:每100万次标志请求30美元(每次事件0.00003美元)。
标志配置采用主动全局复制——变更会在数毫秒内同步至全球。
Core Design Principles
核心设计原则
- Server-only execution: No client-side loading spinners or complexity
- No call-site arguments: Ensures consistent flag evaluation and straightforward flag removal
- Provider-agnostic: Works with any flag provider, custom setups, or no provider at all
- 仅服务器端执行:无客户端加载 spinner 或复杂逻辑
- 无调用站点参数:确保标志评估一致,且移除标志的流程简单直接
- 提供商无关:可与任意标志提供商、自定义设置配合使用,也可无需提供商
Key APIs
核心API
Flags SDK (flags
package, v4.0+)
flagsFlags SDK(flags
包,v4.0+)
flagsThe package is free, open-source (MIT), and provider-agnostic. Renamed from — if using the old package, update to in your imports and .
flags@vercel/flagsflagspackage.jsonUpgrade note: v4 has breaking changes from v3. See the v4 upgrade guide for migration steps:
- package renamed to
@vercel/flags— update imports andflagspackage.json - /
encrypt()replaced with dedicated functions:decrypt(),encryptFlagValues()decryptFlagValues() - must be exactly 32 random bytes, base64-encoded
FLAGS_SECRET - endpoint uses new helper that auto-handles auth and
.well-knownheaderx-flags-sdk-version - As of v4.0.3, declaring a flag without a function (or with an adapter missing
decide) throws an error at declaration timedecide
ts
import { flag } from 'flags/next'; // Framework adapters: flags/next, flags/sveltekit
// Define a boolean flag
export const showNewCheckout = flag({
key: 'show-new-checkout',
description: 'Enable the redesigned checkout flow',
decide: () => false, // default value
});
// Define a multi-variant flag
export const theme = flag({
key: 'theme',
options: [
{ value: 'light', label: 'Light Theme' },
{ value: 'dark', label: 'Dark Theme' },
{ value: 'auto', label: 'Auto' },
],
decide: () => 'auto',
});
// Read flag values (Server Components, Route Handlers, Server Actions)
const isEnabled = await showNewCheckout();
const currentTheme = await theme();flags@vercel/flagspackage.jsonflags升级说明:v4版本相对于v3有破坏性变更。请查看v4升级指南了解迁移步骤:
- 包已重命名为
@vercel/flags——请更新导入语句和flagspackage.json - /
encrypt()已替换为专用函数:decrypt()、encryptFlagValues()decryptFlagValues() - 必须是恰好32个随机字节的base64编码值
FLAGS_SECRET - 端点使用新的助手函数,可自动处理认证和
.well-known请求头x-flags-sdk-version - 从v4.0.3版本开始,若声明标志时未提供函数(或对应的适配器缺少
decide),会在声明时抛出错误decide
ts
import { flag } from 'flags/next'; // Framework adapters: flags/next, flags/sveltekit
// Define a boolean flag
export const showNewCheckout = flag({
key: 'show-new-checkout',
description: 'Enable the redesigned checkout flow',
decide: () => false, // default value
});
// Define a multi-variant flag
export const theme = flag({
key: 'theme',
options: [
{ value: 'light', label: 'Light Theme' },
{ value: 'dark', label: 'Dark Theme' },
{ value: 'auto', label: 'Auto' },
],
decide: () => 'auto',
});
// Read flag values (Server Components, Route Handlers, Server Actions)
const isEnabled = await showNewCheckout();
const currentTheme = await theme();Vercel Adapter (@flags-sdk/vercel
)
@flags-sdk/vercelVercel 适配器(@flags-sdk/vercel
)
@flags-sdk/vercelConnects the Flags SDK to Vercel Flags as the provider (reads env var):
FLAGSts
import { flag, dedupe } from 'flags/next';
import { vercelAdapter } from '@flags-sdk/vercel';
type Entities = {
user?: { id: string; email: string; plan: string };
team?: { id: string; name: string };
};
// Dedupe ensures identify runs once per request
const identify = dedupe(async (): Promise<Entities> => {
const session = await getSession();
return {
user: session?.user ? {
id: session.user.id,
email: session.user.email,
plan: session.user.plan,
} : undefined,
};
});
export const premiumFeature = flag<boolean, Entities>({
key: 'premium-feature',
adapter: vercelAdapter(), // reads FLAGS env var automatically
identify,
});Environment variables:
- — SDK Key (auto-provisioned when you create your first flag)
FLAGS - — 32 random bytes, base64-encoded; encrypts overrides and authenticates Flags Explorer
FLAGS_SECRET
将Flags SDK与Vercel Flags提供商连接(读取环境变量):
FLAGSts
import { flag, dedupe } from 'flags/next';
import { vercelAdapter } from '@flags-sdk/vercel';
type Entities = {
user?: { id: string; email: string; plan: string };
team?: { id: string; name: string };
};
// Dedupe ensures identify runs once per request
const identify = dedupe(async (): Promise<Entities> => {
const session = await getSession();
return {
user: session?.user ? {
id: session.user.id,
email: session.user.email,
plan: session.user.plan,
} : undefined,
};
});
export const premiumFeature = flag<boolean, Entities>({
key: 'premium-feature',
adapter: vercelAdapter(), // reads FLAGS env var automatically
identify,
});环境变量:
- — SDK密钥(创建第一个标志时自动配置)
FLAGS - — 32个随机字节的base64编码值;用于加密覆盖配置并认证Flags Explorer
FLAGS_SECRET
Flags Explorer Setup (GA)
Flags Explorer 设置(正式可用)
The Flags Explorer is generally available (part of the Vercel Toolbar). It lets developers override flags in their browser session without code changes.
App Router — create the discovery endpoint:
ts
// app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint, getProviderData } from 'flags/next';
import * as flags from '../../../../flags';
export const GET = createFlagsDiscoveryEndpoint(() => getProviderData(flags));Pages Router — API route + rewrite:
ts
// pages/api/vercel/flags.ts
import { verifyAccess, version } from 'flags';
import { getProviderData } from 'flags/next';
import * as flags from '../../../flags';
export default async function handler(req, res) {
const access = await verifyAccess(req.headers['authorization']);
if (!access) return res.status(401).json(null);
res.setHeader('x-flags-sdk-version', version);
return res.json(getProviderData(flags));
}js
// next.config.js (rewrite)
module.exports = {
async rewrites() {
return [{ source: '/.well-known/vercel/flags', destination: '/api/vercel/flags' }];
},
};Flags Explorer已正式可用(属于Vercel工具栏的一部分)。开发者无需修改代码,即可在浏览器会话中覆盖标志值。
App Router — 创建发现端点:
ts
// app/.well-known/vercel/flags/route.ts
import { createFlagsDiscoveryEndpoint, getProviderData } from 'flags/next';
import * as flags from '../../../../flags';
export const GET = createFlagsDiscoveryEndpoint(() => getProviderData(flags));Pages Router — API路由 + 重写规则:
ts
// pages/api/vercel/flags.ts
import { verifyAccess, version } from 'flags';
import { getProviderData } from 'flags/next';
import * as flags from '../../../flags';
export default async function handler(req, res) {
const access = await verifyAccess(req.headers['authorization']);
if (!access) return res.status(401).json(null);
res.setHeader('x-flags-sdk-version', version);
return res.json(getProviderData(flags));
}js
// next.config.js (rewrite)
module.exports = {
async rewrites() {
return [{ source: '/.well-known/vercel/flags', destination: '/api/vercel/flags' }];
},
};Precompute Pattern (Static + Personalized)
预计算模式(静态 + 个性化)
Generate static page variants per flag combination, serve via middleware:
ts
export const layoutVariant = flag({
key: 'layout-variant',
options: [{ value: 'a' }, { value: 'b' }],
decide: () => 'a',
});
export const precompute = [layoutVariant];Key APIs: , , , ,
precompute()evaluate()serialize()getPrecomputed()generatePermutations()根据标志组合生成静态页面变体,通过中间件提供服务:
ts
export const layoutVariant = flag({
key: 'layout-variant',
options: [{ value: 'a' }, { value: 'b' }],
decide: () => 'a',
});
export const precompute = [layoutVariant];核心API:、、、、
precompute()evaluate()serialize()getPrecomputed()generatePermutations()Custom Adapter Interface
自定义适配器接口
ts
export function createExampleAdapter() {
return function exampleAdapter<ValueType, EntitiesType>(): Adapter<ValueType, EntitiesType> {
return {
origin(key) { return `https://example.com/flags/${key}`; },
async decide({ key }): Promise<ValueType> { return false as ValueType; },
};
};
}ts
export function createExampleAdapter() {
return function exampleAdapter<ValueType, EntitiesType>(): Adapter<ValueType, EntitiesType> {
return {
origin(key) { return `https://example.com/flags/${key}`; },
async decide({ key }): Promise<ValueType> { return false as ValueType; },
};
};
}Flags vs Edge Config
Flags 与 Edge Config 对比
| Need | Use | Why |
|---|---|---|
| Gradual rollouts, A/B testing, targeting | Vercel Flags | Dashboard, analytics, Flags Explorer, segments |
| Third-party provider integration | Vercel Flags + adapter | Unified view across providers |
| Ultra-low-latency config reads (non-flag) | Edge Config directly | Sub-ms reads, no compute overhead |
| Simple config without rollout logic | Edge Config directly | Lighter weight |
Important: Vercel Flags is the recommended approach for feature flags. Edge Config is the underlying low-latency storage some adapters use, but developers should use the Flags platform (not raw Edge Config) for flag use cases — it provides targeting rules, segments, percentage rollouts, observability, and Flags Explorer.
| 需求 | 推荐工具 | 原因 |
|---|---|---|
| 灰度发布、A/B测试、定向投放 | Vercel Flags | 提供仪表盘、分析功能、Flags Explorer和用户分群 |
| 第三方提供商集成 | Vercel Flags + 适配器 | 跨提供商的统一视图 |
| 超低延迟配置读取(非标志场景) | 直接使用Edge Config | 亚毫秒级读取速度,无计算开销 |
| 无发布逻辑的简单配置 | 直接使用Edge Config | 更轻量化 |
重要提示:Vercel Flags是实现功能标志的推荐方案。Edge Config是部分适配器使用的底层低延迟存储,但开发者应使用Flags平台(而非原生Edge Config)来处理标志相关场景——它提供定向规则、用户分群、百分比发布、可观测性和Flags Explorer功能。
Provider Adapters
提供商适配器
Featured (Marketplace integration, Edge Config for low latency):
- — Vercel as provider
@flags-sdk/vercel - Statsig, Hypertune, GrowthBook
Additional (published under npm scope):
@flags-sdk- LaunchDarkly, ConfigCat, DevCycle, Flipt, Reflag, PostHog, Flagsmith
OpenFeature adapter: The adapter allows most Node.js OpenFeature Providers to work with the Flags SDK, bridging the OpenFeature ecosystem (AB Tasty, CloudBees, Confidence by Spotify, and more)
@flags-sdk/openfeature精选适配器(支持市场集成,使用Edge Config实现低延迟):
- — 使用Vercel作为提供商
@flags-sdk/vercel - Statsig、Hypertune、GrowthBook
其他适配器(发布在 npm组织下):
@flags-sdk- LaunchDarkly、ConfigCat、DevCycle、Flipt、Reflag、PostHog、Flagsmith
OpenFeature适配器:适配器支持大多数Node.js OpenFeature提供商与Flags SDK配合使用,打通OpenFeature生态(AB Tasty、CloudBees、Spotify Confidence等)
@flags-sdk/openfeatureKey Features
核心功能
- Unified Dashboard at : All flags across all providers in one place
https://vercel.com/{team}/{project}/flags - Flags Explorer (GA): Override flags locally via Vercel Toolbar (no code changes)
- CLI Management: ,
vercel flags add, and full flag lifecycle from the terminalvercel flags sdk-keys ls - Entities & Segments: Define user/team attributes, create reusable targeting segments
- Analytics Integration: Track flag impact via Web Analytics and Runtime Logs
- Drafts Workflow: Define in code → deploy → Vercel detects via Discovery Endpoint → promote when ready
- Framework Support: Next.js (App Router + Pages Router + Routing Middleware) and SvelteKit
- Concurrent Evaluation Fix (v1.0.1): flag evaluations no longer trigger duplicate network requests — initialization is properly shared
Promise.all
- 统一仪表盘:访问即可查看所有提供商的所有标志
https://vercel.com/{team}/{project}/flags - Flags Explorer(正式可用):通过Vercel工具栏在本地覆盖标志值(无需修改代码)
- CLI管理:支持、
vercel flags add,可通过终端完成标志全生命周期管理vercel flags sdk-keys ls - 实体与分群:定义用户/团队属性,创建可复用的定向分群
- 分析集成:通过Web Analytics和运行时日志追踪标志影响
- 草稿工作流:代码中定义标志 → 部署 → Vercel通过发现端点检测到标志 → 准备就绪后正式启用
- 框架支持:Next.js(App Router + Pages Router + 路由中间件)和SvelteKit
- 并发评估修复(v1.0.1):标志评估不再触发重复网络请求——初始化逻辑已正确共享
Promise.all
When to Use
适用场景
- Gradual feature rollouts with percentage targeting
- A/B testing and experimentation
- Per-environment flag configuration (production vs preview vs development)
- Trunk-based development (ship code behind flags)
- Consolidating multiple flag providers into one dashboard
- 基于百分比定向的渐进式功能发布
- A/B测试与实验性功能验证
- 分环境标志配置(生产、预览、开发环境)
- 主干开发模式(代码发布后通过标志控制启用)
- 将多个标志提供商整合至统一仪表盘
When NOT to Use
不适用场景
- Simple static config without targeting → use Edge Config directly
- Runtime configuration not related to features → use environment variables
- Server-side only toggles with no UI → consider environment variables
- 无定向需求的简单静态配置 → 直接使用Edge Config
- 与功能无关的运行时配置 → 使用环境变量
- 仅服务器端使用且无UI的开关 → 可考虑使用环境变量
References
参考链接
- 📖 docs: https://vercel.com/docs/flags
- 📖 Flags SDK: https://flags-sdk.dev
- 📖 SDK reference: https://vercel.com/docs/flags/flags-sdk-reference
- 📖 GitHub: https://github.com/vercel/flags
- 📖 官方文档: https://vercel.com/docs/flags
- 📖 Flags SDK文档: https://flags-sdk.dev
- 📖 SDK参考: https://vercel.com/docs/flags/flags-sdk-reference
- 📖 GitHub仓库: https://github.com/vercel/flags