How to add feature flags and experiments to your app with v0

Use v0 to fetch a report-layout flag, render its assigned layout, and track an exposure after the report appears. Allow 30 minutes plus product verification.

  • v0
  • Vite
  • Unified SDK 1.1.43
  • 30 min

Chris Tam · Last updated 11 November 2026

v0 lets me build two report layouts and inspect the code that selects between them. Amplitude feature flags assign the layout, while experimentation connects that assignment to report exports.

In this tutorial, you'll give v0 a scoped prompt, review its generated framework files, run a standalone reference, and verify the result in a development Amplitude project.

A browser report app that lets you fetch a report-layout flag, render its assigned layout, and track an exposure only after the assigned report appears. The agent's code is reviewable against the complete files below.

Prerequisites

  • A v0 account with edit access to a chat and enough allowance for your selected model. Inspect Code, App Preview and Terminal before requesting changes.
  • Node.js 22.12 or later and Corepack with pnpm 10.33.2. The example pins Vite 8.3.4 and @amplitude/unified 1.1.43; it doesn't require another Build tutorial.
  • A development Amplitude project and its public client API key from Settings > Projects > your project > General. Confirm its US or EU data center. For flags, also obtain a client deployment key from the same project in Amplitude Experiment.

Sign up for Amplitude if you need an account, and compare plans for your project's allowances. Use synthetic data throughout this walkthrough.

1. Open the project and connect context

Open a new v0 chat for the synthetic report, or open the app you want to extend. I first ask v0 to inspect its actual framework and existing instrumentation. The complete Vite reference below is a behavior reference; v0 should preserve an existing Next.js app and its router.

v0 planning prompt
Planning only. Inspect this v0 project's framework, router, browser entry point, package manager, existing Amplitude client, consent and authentication. Identify its Preview server and proposed files. Preserve the existing application and explain your tests before editing. Do not deploy, connect accounts or enter credentials. Stop after the plan.

Use Code to inspect the files and Terminal for the project's commands. App Preview opens the running application. The v0 workspace reference describes these surfaces.

This SDK setup works without an Amplitude MCP connection. If you already use a connected agent for project context, review its account permissions separately from the app's public ingestion configuration.

2. Give the agent a precise implementation prompt

Review the plan, then ask v0 to implement the integration. The prompt pins the SDK behavior while leaving the framework adaptation to the project you inspected.

v0 implementation prompt
Implement the reviewed plan in this v0 project. Read the current English SDK references and report their URLs:
https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/reference
https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/instrument-and-configure
https://amplitude.com/docs/sdks/experiment-sdks/experiment-javascript
Use these docs for Amplitude facts. If sources disagree, pause that claim and record both statements until the installed SDK or its owner establishes the behavior.

Read the complete public reference at https://github.com/amplitude/ampli-examples/tree/0f6b33751a384faf49539b7078aa3b84cb45908f/browser/coding-tools/feature-flags and its package.json, index.html, main.js, .env.example, .gitignore, pnpm-workspace.yaml and lockfile. Use the complete files in this article if you cannot retrieve the reference. This standalone reference uses Vite. Preserve this project's actual framework, router, scaffold and package manager instead of replacing them with Vite.

For a server-rendered v0 app, dynamically import browser-only SDK code from a client lifecycle or user action. Do not execute it on the server. Use one initialization promise outside React render and preserve it across remounts and repeated actions. Await initAll(apiKey, options) directly; it resolves void. Retain the imported module for track(), experiment() and sessionReplay(). Check against the actual SDK type, not a cast to an invented interface.

Use @amplitude/unified 1.1.43 with one initAll call and top-level serverZone. Read both a project API key and a client deployment key from Vite configuration; reject a blank deployment before initializing. Request sampleRate 0 and skip engagement. Set synthetic user build-web-flags-demo before fetch. Configure automaticExposureTracking false, retryFetchOnFailure false and throwOnError true so a failed fetch enters the fallback handler instead of reusing a cached assignment. Fetch report-layout once, accept only control and expanded, and display Compact fallback for empty, unknown or failed results. Control renders Compact; expanded shows daily totals. Call exposure(report-layout) once after the assigned DOM has had a paint opportunity. Do not expose the fallback. Keep conversions disabled while assignment is pending. Track Report Exported with report_period and layout_source only on export.

Keep the app usable with missing keys, invalid region, failed initialization or unavailable product results. Test the configured path as well as the blank-key path. Preserve an existing client, confirmed identity, consent, enabled products and privacy selectors. Do not copy the demo's synthetic ID or sample/skip choices into production, add a second analytics client, replace whole shared files or reset identity while authentication is anonymous/loading.

The Vite reference uses public VITE_ configuration. In a Next.js browser component, use explicit process.env.NEXT_PUBLIC_AMPLITUDE_API_KEY and process.env.NEXT_PUBLIC_AMPLITUDE_SERVER_ZONE reads; feature flags also need NEXT_PUBLIC_AMPLITUDE_DEPLOYMENT_KEY. Keep secret, admin, model-provider and server deployment credentials out of all public variables. Leave examples blank and local .env.local ignored. Keep real keys out of the chat and project instructions. Preserve the project's dev-server command and narrow host validation.

Run local tests, the existing build and an explicit type check when TypeScript is used. Save the changes in a version and inspect its diff. Report local checks, native v0 Preview and live Amplitude outcomes separately. Do not deploy, publish, broaden targeting, connect accounts, purchase credits or make paid model calls.

MCP. If you already use a connected Amplitude agent, ask it to read the project's existing event names before adding Report Exported. Keep the established taxonomy when the same action already has a name. The MCP reference describes project-context tools.

3. Review the proposed changes

Inspect the SDK calls before relying on the UI. A successful preview or a local export counter does not establish an assignment, guide delivery or replay capture.

v0 review prompt
Show every changed and new file. Trace the public configuration, browser-only SDK import, one cached initialization, confirmed identity and product-specific handlers. Confirm initAll(apiKey, options) is awaited as a plain promise and its void result is not used as a client. Show the actual installed SDK types, generated tests, build results and saved version diff. Keep missing/failed configuration usable and preserve the app's other integrations. Report local checks separately from live product outcomes.

Use the Code tab and saved version diff to inspect the result. The v0 editor guide distinguishes workspace edits from saved changes. If synchronization fails, preserve the affected files, have v0 capture the reviewed changes in a version, then reopen its diff.

The standalone reference uses VITE_ variables, which are public browser configuration. A Next.js adaptation uses explicit NEXT_PUBLIC_ reads instead. Next.js environment guidance explains build-time embedding. Restart after changing configuration and configure hosted builds separately. Never put private credentials in either prefix.

The demo has a fixed synthetic user. Merge an existing app through its current client and confirmed identity, keeping its consent and other enabled products.

4. Check the complete reference implementation

These six files make a complete standalone Vite browser reference. Use them in a separate local directory to inspect and run the SDK behavior. In an existing v0 app, merge that behavior into its framework files; keep its routes, authentication, layout and dev-server configuration.

The Unified SDK installation guide supplies the setup. This example pins 1.1.43 for repeatable checks, rather than claiming it is the latest release. Its initialization returns a plain promise, so the reference awaits it directly.

package.json
{
  "name": "amplitude-build-feature-flags",
  "private": true,
  "version": "1.0.0",
  "type": "module",
  "packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
  "engines": {
    "node": ">=22.12.0",
    "pnpm": ">=10.21.0"
  },
  "scripts": {
    "dev": "vite --host 127.0.0.1",
    "build": "vite build",
    "preview": "vite preview --host 127.0.0.1"
  },
  "dependencies": {
    "@amplitude/unified": "1.1.43"
  },
  "devDependencies": {
    "vite": "8.3.4"
  }
}
pnpm-workspace.yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
.gitignore
node_modules/
dist/
.env.local
.env.qa
.env.example
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
VITE_AMPLITUDE_DEPLOYMENT_KEY=
index.html
<!doctype html>
<html lang="en">
  <head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Usage report demo</title></head>
  <body>
    <main>
      <h1>Usage report</h1>
      <p>84 actions in the past 7 days.</p>
      <button id="start">Start demo</button>
      <button id="export-report">Export report</button>
      <p>Local exports: <span id="exports">0</span></p>
      <p>Layout: <span id="layout">Compact</span></p>
    <p id="detail" hidden>Daily totals: 12 actions per day.</p>
      <p id="status" role="status">Demo stopped. Use synthetic data only.</p>
    </main>
    <script type="module" src="/main.js"></script>
  </body>
</html>
main.js
import * as amplitude from "@amplitude/unified";
const deploymentKey = (import.meta.env.VITE_AMPLITUDE_DEPLOYMENT_KEY || "").trim();
let layoutSource = "fallback";

const apiKey = (import.meta.env.VITE_AMPLITUDE_API_KEY || "").trim();
const zone = (import.meta.env.VITE_AMPLITUDE_SERVER_ZONE || "US").trim();
const status = document.querySelector("#status");
const startButton = document.querySelector("#start");
const exportButton = document.querySelector("#export-report");
let started = false;
let starting;
let exports = 0;

exportButton.addEventListener("click", () => {
  exports += 1;
  document.querySelector("#exports").textContent = String(exports);
  if (started) amplitude.track("Report Exported", { report_period: "7d", layout_source: layoutSource });
});

startButton.addEventListener("click", () => {
  if (starting) return;
  if (!apiKey || !["US", "EU"].includes(zone) || !deploymentKey) {
    status.textContent = "Add the development configuration and restart Vite. Local export still works.";
    return;
  }
  startButton.disabled = true;
  starting = start().catch(() => {
    status.textContent = "Setup failed. Check configuration and connectivity, then reload.";
  });
});

async function start() {
  await amplitude.initAll(apiKey, {
    serverZone: zone,
    analytics: { autocapture: false },
    sessionReplay: { sampleRate: 0 },
    experiment: { deploymentKey, automaticExposureTracking: false, retryFetchOnFailure: false, throwOnError: true, fetchTimeoutMillis: 5000 },
    engagement: { skip: true },
  });
  amplitude.setUserId("build-web-flags-demo");
  started = true;
  const client = amplitude.experiment();
  if (!client) throw new Error("Experiment client unavailable");
  // Do not log conversions under a fallback while assignment is still pending.
  exportButton.disabled = true;
  try {
    await client.fetch();
    const value = client.variant("report-layout").value;
    if (value === "control" || value === "expanded") {
      layoutSource = "assigned";
      document.querySelector("#layout").textContent = value === "expanded" ? "Expanded" : "Compact";
      document.querySelector("#detail").hidden = value !== "expanded";
      await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
      client.exposure("report-layout");
      status.textContent = `Assigned ${value}; device ${amplitude.getDeviceId()}.`;
    } else {
      status.textContent = "No usable assignment. Compact fallback; no assigned exposure.";
    }
  } catch {
    status.textContent = "Fetch failed. Compact fallback; no assigned exposure.";
  } finally {
    exportButton.disabled = false;
  }
}

Install with the pinned package manager. Keep the generated lockfile, or use the matching lockfile in the public reference, then use a frozen install on subsequent checkouts.

Terminal
corepack pnpm install
corepack pnpm build

Copy .env.example to the ignored .env.local before the configured development check. The values in VITE_ variables enter the built browser bundle; keep only public client configuration there. The Vite environment reference explains configuration loading and rebuilds.

5. Configure the development project

Create a feature flag in the development project with key report-layout. Use remote evaluation, add the values control and expanded, and attach the client deployment whose key you configured. Keep the general rollout at zero while testing; put only your intended synthetic testers in test targeting and save the configuration.

Development product settings
Flag key: report-layout
Values: control, expanded
Synthetic user: build-web-flags-demo
control display: Compact
expanded display: Expanded, with daily totals
Fallback display: Compact, layout_source=fallback
Conversion: Report Exported

Test the two values separately in your development targeting. A fetch returning HTTP 200 can still contain no assignment for this flag. The app exposes only a recognized assigned value, and it records layout_source so fallback exports can be distinguished from assigned exports.

For an experiment, create an experiment or convert the flag, configure [Experiment] Exposure as its exposure event, and save Report Exported as the primary conversion metric. Review the hypothesis and targeting before selecting Start Experiment. A flag assignment alone doesn't mean an experiment has started or produced a statistically reliable result.

The sample requests a zero replay sample rate. Check the development project's replay capture settings too. Preserve any existing replay consent and privacy configuration when merging.

6. Run the report

For the local reference, start Vite and open the URL it prints. For a generated v0 app, keep its existing framework command and inspect App Preview. Do not replace a Next.js dev server with the reference's Vite command.

Local reference terminal
corepack pnpm dev

Export before starting the SDK to check that the report stays usable with blank configuration. Then configure the development project, restart, select Start demo once and follow Verify it worked. After the check, stop the server and verify the build:

Local reference terminal
corepack pnpm build

Keep the generated v0 app's direct route loads, navigation and Preview results separate from the standalone reference's checks.

Verify it worked

  1. Leave either client key blank. Export locally and tap Start demo. Confirm the configuration warning, Compact fallback, and no SDK initialization. A missing deployment key must not silently select another deployment.
  2. With valid development keys, target build-web-flags-demo to control. Start once and confirm the report shows Compact with an Assigned status. Export once.
  3. In a separate page load, target the same synthetic tester to expanded. Confirm the extra daily totals appear before the assigned exposure and export. Keep the general audience unchanged.
  4. Test an empty or unavailable assignment. Confirm Compact fallback, no assigned exposure, and layout_source: fallback on any export tracked after initialization.
  5. In User Lookup, check the processed [Experiment] Exposure and Report Exported events for the same user, device, and test time. The integrated SDK sends the exposure; don't add a second custom exposure event.
  6. Open the experiment and confirm its saved exposure definition, primary conversion metric, deployment, and started state. Verify that processed test activity belongs to that setup. Do not infer a winner from a passing integration test.

Troubleshooting

Preview is blank or rejects the host. Confirm the app's existing dev server is running and inspect its actual Preview URL. Keep framework host validation enabled. If an additional trusted host is required, allow that exact host rather than disabling validation globally.

Start demo asks for configuration. Fill in .env.local and restart Vite. The guard deliberately leaves the SDK stopped when the required client configuration is missing or the region isn't US or EU.

The report stays Compact. Check whether the status says Assigned control or fallback. Verify the exact flag key, values, deployment association, tester inclusion, saved state, and region.

A missing deployment still returns flags in another app. This example rejects an empty client deployment key. Without that guard, the Unified integration can fall back to the project API key's deployment.

An exposure arrives before the assigned report appears. Keep automatic exposure disabled and the explicit exposure call after rendering. Remove automatic reads or duplicate exposure calls added by the agent.

The fetch fails. Keep the usable Compact fallback. Check connectivity and targeting, then reload for a new attempt. The demo disables background fetch retries and doesn't retry initialization within the same page load.

The SDK crashes during server rendering. Keep the browser SDK out of server-evaluated imports. Ask v0 to move its dynamic import into a client lifecycle or user action and preserve a single initialization promise across component remounts. Test a direct route load as well as client navigation.

Preview has no configuration. Check the generated app's framework-specific public environment variables and restart its development process. A later runtime variable does not rewrite a static browser bundle that already embedded its values.

The agent added a second SDK or broke an existing route. Review the repository's original entry point and merge into its existing client. Keep one Amplitude initialization for this app; don't combine this example with a second script loader or independently initialized browser package.

FAQ

Which Amplitude key goes in the browser app?

The browser app uses a public project API key and a client deployment key. An MCP connection authenticates separately. Keep server deployment keys, admin tokens, and secret keys out of browser configuration and committed source.

Can I use this in an existing v0 app?

Yes. Have the agent merge the behavior into the existing browser entry point and client. Preserve authentication, consent, and routing. The standalone reference uses Vite. Keep the existing app scaffold and router. If it renders on a server, load browser-only SDK code dynamically from a client lifecycle or user action, and test direct route loads.

Does a successful build prove the product works?

No. A build checks that the browser app can be bundled. The Verify section separately checks the rendered experience, processed activity, and the product result. Record which checks you performed before broadening the audience.

Will the agent make the same changes every time?

Treat its output as a change to review. Keep the explicit prompt, pinned reference, and repository rules, then compare its diff with the required behavior. An agent can propose a different implementation without establishing that its SDK calls or product settings are correct.

Full code reference

Step 4 contains every file needed by the standalone browser reference. Read the public example and lockfile. Compare its SDK behavior with v0's actual framework files; a matching local reference does not establish that a generated adaptation behaves identically.

Save the project instructions

Add these constraints through v0 Instructions and apply them to the conversation. Preserve any existing project guidance and keep credentials out of instructions.

v0 reusable instructions
Preserve the app's framework, router, consent, confirmed identity, enabled Amplitude products and package manager. Keep browser-only SDK imports out of server execution. Reuse one initialization promise and use the imported module after await initAll(apiKey, options). Do not cast an invented SDK interface over the real package. Keep public browser configuration separate from private server credentials. Preserve the product-specific fallback, event timing and privacy rules in this tutorial. Run local checks and inspect the saved version diff. Verify the rendered experience and processed service result separately before rollout. Pause conflicting SDK claims until source evidence or an owner resolves them.

What this unlocks

Feature flags assign the report layout. Experimentation connects [Experiment] Exposure to the primary conversion Report Exported for the same identity. Keep the event name and report-period property consistent as you extend the app.

Next steps

Amplitude is the leading all-in-one analytics platform for building better products. Product and engineering teams use Amplitude to connect product analytics and web analytics with session replay, heatmaps, experimentation, feature flags, and guides and surveys in one unified workflow, with AI agents working across all of it. Learn how Amplitude is building self-improving products with Wave, helping teams turn product data into PRs.

Build the report, then check the result

Connect a development project and verify the report action before you roll out the integration.