flags-sdk

작성자: vercel

Flags SDK(flags npm 패키지)는 Next.js 및 SvelteKit을 위한 기능 플래그 툴킷입니다. 각 기능 플래그를 호출 가능한 함수로 변환하며, 어댑터를 통해 모든 플래그 제공자와 작동하고, 사전 계산 패턴을 사용하여 페이지를 정적으로 유지합니다. Vercel Flags는 자사 제공자로서 Vercel 대시보드 또는 vercel flags CLI에서 플래그를 관리할 수 있게 해줍니다.

npx skills add https://github.com/vercel/flags --skill 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.

Core concepts

Flags as code

Each flag is declared as a function. No string keys at call sites:

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.

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.

Agent workflow: Creating a new flag

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.

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

Steps

  1. Install packages (if not already in package.json):

    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:

    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:

    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):

  7. Set up Flags Explorer (if not already present): Create app/.well-known/vercel/flags/route.ts — see the Flags Explorer setup section below.

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.

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.

Basic flag

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:

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:

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.

Key parameters

ParameterTypeDescription
keystringUnique flag identifier
decidefunctionResolves the flag value
defaultValueanyFallback if decide returns undefined or throws
descriptionstringShown in Flags Explorer
originstringURL to manage the flag in provider dashboard
options{ label?: string, value: any }[]Possible values, used for precompute + Flags Explorer
adapterAdapterProvider adapter implementing decide and origin
identifyfunctionReturns evaluation context (entities) for decide

Dedupe

Wrap shared functions (especially identify) in dedupe to run them once per request:

import { dedupe } from 'flags/next';

const identify = dedupe(({ cookies }) => {
  return { user: { id: cookies.get('uid')?.value } };
});

Note: dedupe is not available in 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().

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):

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.

Flags Explorer setup

Next.js (App Router)

// 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.

SvelteKit

// 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

Required for precompute and Flags Explorer. Must be 32 random bytes, base64-encoded:

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:

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.

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

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.

Encryption functions

For keeping flag data confidential in the browser (used by Flags Explorer):

FunctionPurpose
encryptFlagValuesEncrypt resolved flag values
decryptFlagValuesDecrypt flag values
encryptFlagDefinitionsEncrypt flag definitions/metadata
decryptFlagDefinitionsDecrypt flag definitions
encryptOverridesEncrypt toolbar overrides
decryptOverridesDecrypt toolbar overrides

All use FLAGS_SECRET by default. Example:

import { encryptFlagValues } from 'flags';
import { FlagValues } from 'flags/react';

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

React components

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: '...' } }} />

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, Edge 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

vercel의 다른 스킬

benchmark-sandbox
vercel
Vercel Sandbox에서 vercel-plugin eval 시나리오를 로컬 WezTerm 패널 대신 실행합니다. Claude Code와 플러그인이 사전 설치된 임시 마이크로VM을 프로비저닝합니다.
official
emil-design-eng
vercel
이 스킬은 Emil Kowalski의 UI 폴리시, 컴포넌트 디자인, 애니메이션 결정, 그리고 소프트웨어를 훌륭하게 만드는 보이지 않는 세부 사항에 대한 철학을 인코딩합니다.
official
vercel-react-best-practices
vercel
Vercel Engineering의 React 및 Next.js 성능 최적화 가이드라인입니다. 이 스킬은 React/Next.js 코드를 작성, 검토 또는 리팩토링할 때 사용해야 합니다.
official
vercel-react-best-practices
vercel
Vercel Engineering의 React 및 Next.js 성능 최적화 가이드라인입니다. 이 스킬은 React/Next.js 코드를 작성, 검토 또는 리팩토링할 때 사용해야 합니다.
official
write-guide
vercel
점진적인 예제를 통해 실제 사용 사례를 가르치는 기술 가이드를 제작합니다. 개념은 독자가 필요로 할 때만 소개됩니다.
official
release
vercel
Vercel-plugin 릴리스 — 게이트 실행, 버전 업, 아티팩트 생성, 커밋 및 푸시. "릴리스", "배포", "버전 업 및 푸시", "릴리스 생성" 요청 시 사용.
official
deepsec
vercel
dev3000에서 체크아웃한 Vercel 프로젝트에 대해 DeepSec을 실행합니다. 원클릭 DeepSec 설정, 프로젝트 컨텍스트 부트스트래핑, 제한된 1차 처리 등에 사용합니다.
official
backport-pr
vercel
병합된 Next.js 풀 리퀘스트를 canary에서 next-16-2와 같은 이전 릴리스 브랜치로 백포트합니다. 사용자가 백포트, 체리픽 또는 열기를 요청할 때 사용합니다…
official