Skip to main content

flags-sdk

Set up and use feature flags and A/B tests with the Flags SDK (`flags` npm package) and Vercel Flags. Use when installing or configuring the SDK, adding a new or existing flag, wiring `vercelAdapter` (OIDC or SDK keys), declaring flags with `flag()`, using the `vercel flags` CLI (create, inspect, list, enable, disable, set, update, split, rollout, rules, segments, use-targeting, evaluations, versions, open, archive, unarchive, rm, sdk-keys, override, prepare), setting up providers/adapters (Vercel, Statsig, LaunchDarkly, PostHog, GrowthBook, Global Config, OpenFeature, Split, Flagsmith, Reflag, Optimizely, or custom), precompute, `identify`/`dedupe`, Flags Explorer/Toolbar, Next.js or SvelteKit, or encrypting flag values. Triggers: feature flags, feature gates, A/B testing, experimentation, gradual rollout, traffic split, targeting rules, flag overrides, precompute, Flags Explorer, Vercel Flags, vercel flags CLI, `flags/next`, `flags/sveltekit`, `flags/react`, `@flags-sdk/*`.

소스 정보

저장소
vercel/vercel-plugin
최근 소스 활동
2026년 10월 2일 16:42
감지된 SKILL.md 언어
영어
스타
301
포크
64

설치 방법

기본적으로 소스를 먼저 확인하는 Prompt가 선택됩니다. 직접 명령으로 전환하거나 로컬 사본을 다운로드할 수도 있습니다.

소스 파일 검토

설치 여부를 결정하기 전에 SKILL.md와 SkillsMP에 표시된 보조 파일을 읽어 보세요.

파일 탐색기
12 개 파일

SKILL.md 표시 중

SKILL.md
소스 지침 · 읽기 전용 미리보기
name
flags-sdk
description
Set up and use feature flags and A/B tests with the Flags SDK (`flags` npm package) and Vercel Flags. Use when installing or configuring the SDK, adding a new or existing flag, wiring `vercelAdapter` (OIDC or SDK keys), declaring flags with `flag()`, using the `vercel flags` CLI (create, inspect, list, enable, disable, set, update, split, rollout, rules, segments, use-targeting, evaluations, versions, open, archive, unarchive, rm, sdk-keys, override, prepare), setting up providers/adapters (Vercel, Statsig, LaunchDarkly, PostHog, GrowthBook, Global Config, OpenFeature, Split, Flagsmith, Reflag, Optimizely, or custom), precompute, `identify`/`dedupe`, Flags Explorer/Toolbar, Next.js or SvelteKit, or encrypting flag values. Triggers: feature flags, feature gates, A/B testing, experimentation, gradual rollout, traffic split, targeting rules, flag overrides, precompute, Flags Explorer, Vercel Flags, vercel flags CLI, `flags/next`, `flags/sveltekit`, `flags/react`, `@flags-sdk/*`.
summary
Flags SDK guidance — declare flags with flag(), connect provider adapters, manage Vercel Flags via the vercel flags CLI, precompute static variants, and set up the Flags Explorer.
metadata
{"priority":6,"docs":["https://vercel.com/docs/flags","https://flags-sdk.dev"],"sitemap":"https://vercel.com/sitemap.xml","pathPatterns":["flags.ts","flags.tsx","lib/flags.ts","src/flags.ts","lib/flags/**","src/flags/**",".well-known/vercel/flags/**"],"importPatterns":["flags/next","flags/sveltekit","flags/react","flags","@flags-sdk/*","@vercel/flags"],"bashPatterns":["\\bvercel\\s+flags\\b","\\bvc\\s+flags\\b","\\bnpm\\s+(install|i|add)\\s+[^\\n]*\\bflags\\b","\\bpnpm\\s+(install|i|add)\\s+[^\\n]*\\bflags\\b","\\bbun\\s+(install|i|add)\\s+[^\\n]*\\bflags\\b","\\byarn\\s+add\\s+[^\\n]*\\bflags\\b","\\bnpm\\s+(install|i|add)\\s+[^\\n]*@flags-sdk/","\\bpnpm\\s+(install|i|add)\\s+[^\\n]*@flags-sdk/","\\bbun\\s+(install|i|add)\\s+[^\\n]*@flags-sdk/","\\byarn\\s+add\\s+[^\\n]*@flags-sdk/"],"promptSignals":{"phrases":["feature flag","feature flags","flags sdk","vercel flags","flags explorer","feature gate","feature gating","a/b test","a/b testing","ab test","ab testing","flag rollout","gradual rollout","percentage rollout","kill switch","flag variant","flag adapter","precompute flags","traffic split","targeting rules","flag rules","flag segments","flag targeting","flag evaluations","flag overrides","existing flag"],"allOf":["[Truncated]","[Truncated]","[Truncated]","[Truncated]","[Truncated]","[Truncated]"],"anyOf":["flag","experiment","experimentation","rollout","variant"],"noneOf":["command-line flag","command line flag","cli flag","compiler flag","flag emoji","rolling release"],"minScore":6}}
retrieval
{"aliases":["feature flags","feature toggles","vercel flags","flags sdk","a/b testing"],"intents":["add a feature flag","run an a/b test","gate a feature","roll out gradually","manage flags from cli"],"entities":["Flags SDK","Vercel Flags","Flags Explorer","vercelAdapter","precompute","FLAGS_SECRET"]}
chainTo
[{"pattern":"precompute\\s*\\(|generatePermutations|flags/next.*precompute","targetSkill":"routing-middleware","message":"Precompute pattern detected — loading Routing Middleware guidance for the middleware rewrites that serve static flag variants."},{"pattern":"@flags-sdk/(edge|global)-config|create(Edge|Global)ConfigAdapter","targetSkill":"vercel-storage","message":"Global Config flag adapter detected — loading Vercel storage guidance for Global Config setup and limits."}]
# Set up and use the 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. - Docs: https://flags-sdk.dev - Repo: https://github.com/vercel/flags When the user asks to install, configure, or set up feature flags, follow [Set up the SDK](#set-up-the-sdk) (including `vercel env pull` when `.env.local` is missing). When they ask to create or add a flag, follow [Create a flag](#create-a-flag). A request is CLI-only when the user asks to inspect, create, or change a remote flag and the request involves no code; then follow [CLI-only flag management](#cli-only-flag-management). Inside an app repository, treat an ambiguous request as the full flow. Do not leave CLI steps as "next steps" for the user — execute them yourself. ## 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(); ``` ### 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. ### 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. ## Set up the SDK One-time project setup. Run this when the Flags SDK is not installed yet, or when Toolbar / Flags Explorer / `.env.local` are missing. Skip any step that is already done. ### 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) - Is the project linked? → Skip `vercel link` in step 2 - Does `.env.local` contain `VERCEL_OIDC_TOKEN=` (or a `FLAGS=` SDK key)? → Env vars already pulled, skip step 3 - Is `@vercel/toolbar` in `package.json`? → Skip toolbar setup (step 4) - Does `flags.ts` (or `lib/flags.ts`, `src/flags.ts`) exist? → Skip creating it (step 5) - Does `app/.well-known/vercel/flags/route.ts` exist? → Flags Explorer already set up, skip step 6 ### Steps 1. **Install packages** (if not already in `package.json`): ```bash pnpm i flags @flags-sdk/vercel ``` 2. **Link the project to Vercel** (required for `vercel env pull` and local OIDC token refresh): > **Prerequisite**: The Vercel CLI must be installed and authenticated. If it 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. Verify the link as described in [Project targeting](#project-targeting). If the project is not linked, run `vercel link`. 3. **Pull environment variables**: If `.env.local` lacks `VERCEL_OIDC_TOKEN=`, follow [Pull environment variables](#pull-environment-variables). 4. **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](references/nextjs.md#toolbar-setup) for the full code. 5. **Ensure `flags.ts` exists**: If missing, create `flags.ts` (or `lib/flags.ts` / `src/flags.ts` to match the project) with `export {}` so TypeScript treats it as a module. Flags Explorer imports this file — create it before the discovery route. 6. **Set up Flags Explorer** (if not already present): Create `app/.well-known/vercel/flags/route.ts` — see [Flags Explorer setup](#flags-explorer-setup). Do this only after `flags.ts` exists. Point the import at the real flags file path (the snippet assumes root `flags.ts`). ## Pull environment variables `vercel env pull` writes the Development credentials to `.env.local`: the Vercel OIDC token that `vercelAdapter` uses locally (deployments receive it automatically, [Getting started](https://vercel.com/docs/flags/vercel-flags/quickstart#pull-local-openid-connect-credentials)) and the Development `FLAGS_SECRET` for Flags Explorer and overrides. Run it when: - `.env.local` lacks `VERCEL_OIDC_TOKEN=` (or a `FLAGS=` SDK key) - you created the project's first flag; activating Vercel Flags creates a `FLAGS_SECRET` per environment - local evaluation fails with an authentication error; the SDK refreshes an expired token through the linked project, re-pulling is the fallback SDK keys (`FLAGS`) are only for apps outside Vercel, custom environments, or flags of another project ([SDK Keys](https://vercel.com/docs/flags/vercel-flags/dashboard/sdk-keys)). If `FLAGS_SECRET` is still missing after the pull, generate it per [FLAGS_SECRET](#flags_secret). ## Create a flag When a user asks you to create or add a feature flag that does not exist on Vercel yet, follow these steps in order. For a [CLI-only request](#cli-only-flag-management), run step 2 only. If the flag was already created in the dashboard (the prompt says so, or `vercel flags create` reports the key exists), follow [Add a flag that already exists on Vercel](#add-a-flag-that-already-exists-on-vercel) instead. ### Before you start - Complete [Set up the SDK](#set-up-the-sdk) first if packages, Vercel link, `.env.local`, Toolbar, `flags.ts`, or Flags Explorer are missing. Skip steps that are already done. Skip this entirely for a [CLI-only request](#cli-only-flag-management). - Does `.env.local` contain `VERCEL_OIDC_TOKEN=`? → Env vars already pulled; see [Pull environment variables](#pull-environment-variables) if local evaluation fails with an authentication error. - Does `flags.ts` (or `lib/flags.ts`, `src/flags.ts`) exist? → Add to it rather than creating from scratch. ### Steps 1. **Ensure the SDK is set up**: Follow [Set up the SDK](#set-up-the-sdk) if needed, then continue. 2. **Register the flag with Vercel**: Run `vercel flags create <flag-key> --kind boolean --description "<description>"`. Target the project as described in [Project targeting](#project-targeting). 3. **Pull environment variables**: If this is the project's first flag, follow [Pull environment variables](#pull-environment-variables) again; activation created the `FLAGS_SECRET`. 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>; } ``` ## Add a flag that already exists on Vercel Use this flow when the flag was created in the dashboard or by someone else, for example when the prompt says the flag "has already been created" or asks you to run `vercel flags inspect`. Do not run `vercel flags create` for an existing key. For a [CLI-only request](#cli-only-flag-management), run step 2 only. 1. **Ensure the SDK is set up**: Follow [Set up the SDK](#set-up-the-sdk) if needed. 2. **Read the definition**: Run `vercel flags inspect <flag-key>`. Note the kind, the variants (value and label), the description, and what each environment serves. 3. **Pull environment variables**: If `.env.local` lacks `VERCEL_OIDC_TOKEN=`, follow [Pull environment variables](#pull-environment-variables). 4. **Declare the flag**: Add it to `flags.ts` with `vercelAdapter`. Map the `inspect` output: - `key`: the flag key exactly as printed - kind → type parameter: `boolean` → `flag<boolean>`, `string` → `flag<string>`, `number` → `flag<number>`, `json` → `flag<YourType>` - `description`: copy from `inspect` - `defaultValue`: the value to serve when the flag is archived or evaluation fails (usually what production serves today) - `options`: optional; mirror the variants when you use precompute or want them listed in Flags Explorer - `identify`: add or reuse one when the flag has targeting, using the entity attributes configured in the dashboard (see [Flag with evaluation context](#flag-with-evaluation-context)) ```ts export const welcomeMessage = flag<string>({ key: 'welcome-message', description: 'Copy shown on the landing page', defaultValue: 'control', adapter: vercelAdapter, }); ``` 5. **Use the flag** as in [Create a flag](#create-a-flag) step 5. ## CLI-only flag management Managing remote flags with `vercel flags` requires an authenticated CLI, but not SDK packages, Toolbar, Flags Explorer, or `.env.local`. For a CLI-only request, skip app setup and code changes. Target the project as described in [Project targeting](#project-targeting), then follow [references/providers.md — `vercel flags` CLI](references/providers.md#vercel-flags-cli) for command semantics and safety notes. CLI authentication is separate from the app's OIDC or SDK key. Pull local credentials only when the app needs local SDK evaluation, not to prepare a CLI flag command. ### Project targeting Use `--project <name-or-id>` and `--scope <team>` to select the target without a local link. If the CLI rejects `--project`, upgrade it first (`pnpm i -g vercel`). Without these options the commands use the linked project: run `vercel project inspect --non-interactive` and check the reported owner and project name; a `.vercel/` directory alone does not prove a link. If it reports `link_required`, the project is not linked. If the user named a project or team and the output differs, stop and ask instead of relinking. For a CLI-only request in an unlinked directory, prefer `--project` / `--scope` over `vercel link`; if the target project is unknown, ask. ## 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. `vercelAdapter()` authenticates with the project's Vercel OIDC token and evaluates the configuration of the current environment; SDK keys (`FLAGS`) are for manual authentication only ([SDK Keys](https://vercel.com/docs/flags/vercel-flags/dashboard/sdk-keys)). Activating Vercel Flags creates a `FLAGS_SECRET` per environment for Flags Explorer. To install the SDK, follow [Set up the SDK](#set-up-the-sdk). To create a flag end-to-end, follow [Create a flag](#create-a-flag). For a flag that already exists on Vercel, follow [Add a flag that already exists on Vercel](#add-a-flag-that-already-exists-on-vercel). For the full Vercel provider reference — user targeting, how the CLI maps to the SDK (keys, kinds, targeting attributes, SDK keys, overrides, `prepare`), lifecycle and safety, custom adapter configuration, and Flags Explorer setup — see [references/providers.md](references/providers.md#vercel). For the current `vercel flags` subcommands and options (targeting, splits, rollouts, rules, segments, evaluations, versions, and more), run `vercel flags --help` or `vercel flags <cmd> --help`. For CLI-wide contracts (linking, non-interactive mode, output parsing), use the `vercel-cli` skill. ## Declaring flags When using Vercel Flags, declare flags with `vercelAdapter` as shown in [Create a flag](#create-a-flag). For other providers, see [references/providers.md](references/providers.md). Below are the general `flag()` patterns. ### 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; }, }); ``` ### 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); }, }); ``` With `vercelAdapter`, the entity and attribute names in the returned object (`user.id` here) are what dashboard rules and `vercel flags split|rollout|rules --by` target. They must match the entities and attribute types configured in the dashboard. See [references/providers.md — User targeting](references/providers.md#user-targeting) and [Attribute types](references/providers.md#attribute-types). ### 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](references/providers.md) for all supported adapters. ### Key parameters | Parameter | Type | Description |
GitHub에서 보기
이 SKILL.md는 매우 커서 SkillsMP가 여기에는 첫 섹션만 미리 보여줍니다. GitHub에서 보기