---
title: "How to use feature flag payloads as remote configuration in React"
description: "Use Amplitude flag payloads as React remote configuration. Validate types and bounds, render safe defaults, and test malformed or missing payloads."
canonical: "https://amplitude.com/build/react-feature-flags-payloads"
---

# How to use feature flag payloads as remote configuration in React

Use Amplitude flag payloads as React remote configuration. Validate types and bounds, render safe defaults, and test malformed or missing payloads.

Source: https://amplitude.com/build/react-feature-flags-payloads

---

# How to use feature flag payloads as remote configuration in React

Read a feature flag payload after assignment, validate its shape, and apply safe defaults. Build a React report fixture and check real assignments separately from local payload tests.

- React
- Vite
- Unified SDK 1.2.1
- 20 min

Chris Tam · Last updated 16 November 2026

[Feature flags](https://amplitude.com/feature-management) can carry configuration data as well as a variant value. I'll build a React list of ten demo reports. An expanded variant's validated payload controls how many reports appear and whether a weekly comparison is visible; missing or malformed data uses two reports and no comparison.

The list and comparison are local fixtures. I'll use an existing designated test flag for remote assignment and the actual SDK in local valid/invalid payload tests. Payloads are public client data, not executable code, authorization rules or secret storage.

## What you'll build

A standalone React report list with a strict payload projection. Only an expanded variant with reportLimit as an integer 1-10 and showComparison as a boolean can supply remote configuration. Control, unassigned, missing, malformed and out-of-range payloads use local defaults.

## Prerequisites

- Node.js 22.12 or later and Corepack for pnpm.
- An Amplitude test project and its ingestion API key. Open Organization settings > API Keys and select the test project.
- For remote verification, a client deployment key from that test project, with the test flag included in the deployment.
- An existing test flag with `control` and `expanded` variants and designated test identities. For the valid remote-payload check, the `expanded` variant must contain the JSON object payload `{"reportLimit":5,"showComparison":true}`. The example uses `report-layout`; adapt its key and test identities to your project.
- The project data center, US or EU. Preserve your existing consent flow when adapting the example.

No Amplitude account yet? A free account is enough for this tutorial; nothing here needs a paid plan. [Sign up for free](https://app.amplitude.com/signup) to get your project API key.

## 1. Create the standalone app

I'll use the [Browser Unified SDK package installation](https://amplitude.com/docs/get-started/install-with-package-manager) in a small Vite app. The versions below are pinned to the tested example.

Terminal

```sh
mkdir react-feature-flags-payloads
cd react-feature-flags-payloads
mkdir -p src tests
corepack enable
```

package.json

```json
{
  "name": "amplitude-react-feature-flags-payloads",
  "version": "1.0.0",
  "private": true,
  "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",
    "test": "vitest run"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6",
    "vitest": "5.0.5",
    "jsdom": "31.0.0"
  }
```

pnpm-workspace.yaml

```yaml
minimumReleaseAge: 10080
trustPolicy: no-downgrade
```

.gitignore

```text
node_modules/
dist/
.env
.env.local
.env.*.local
```

index.html

```html
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>
```

.env.example

```text
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_DEPLOYMENT_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US
```

Terminal

```sh
corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.local
```

Put the test-project key in `VITE_AMPLITUDE_API_KEY` in `.env.local`, and set `VITE_AMPLITUDE_SERVER_ZONE` to `US` or `EU`. Vite exposes `VITE_` variables in the browser bundle. The project API key is public and has the minimum scope needed to ingest data; a server secret key stays out of browser code.

In an existing application, merge the changes into its current Amplitude module and application flow. Keep authentication, consent, routes, and other instrumentation. Don't add another SDK installation or replace production files with the demo.

## 2. Project the payload into a bounded application config

I'll check the variant value before its payload, then build a fresh config object. The [variant payload reference](https://amplitude.com/docs/sdks/experiment-sdks/experiment-javascript#variant) describes payload as arbitrary configured data; its shape and safety rules belong to the application.

vitest.config.js

```javascript
import { defineConfig } from 'vitest/config';
export default defineConfig({ test: { environment: 'jsdom', restoreMocks: true } });
```

src/config.js

```javascript
const defaults=Object.freeze({reportLimit:2,showComparison:false});
export function configFromVariant(variant){
 if(variant?.value!=='expanded')return {...defaults,source:variant?.value==='control'?'control':'missing_variant'};
 const payload=variant.payload;
 const valid=payload!==null&&typeof payload==='object'&&!Array.isArray(payload)&&Object.keys(payload).length===2&&Object.keys(payload).every(k=>['reportLimit','showComparison'].includes(k))&&Number.isInteger(payload.reportLimit)&&payload.reportLimit>=1&&payload.reportLimit<=10&&typeof payload.showComparison==='boolean';
 return valid?{reportLimit:payload.reportLimit,showComparison:payload.showComparison,source:'remote'}:{...defaults,source:'invalid_payload'};
}
```

A valid expanded payload is `{"reportLimit":5,"showComparison":true}`. The validator requires exactly those two keys, an integer limit from 1 to 10, and a boolean comparison. It rejects arrays, JSON strings, missing fields, extra fields and wrong types. It doesn't coerce data or spread the payload into component props.

**Why.** A payload editor can save data the application doesn't understand. Treat the remote value as an input boundary. Keeping defaults in code lets the interface work when a payload is absent, invalid or belongs to a different variant.

## 3. Fetch the assignment before reading its payload

I'll initialize the [Unified Experiment integration](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/instrument-and-configure#use-feature-experiment) with explicit ingestion and client deployment keys. The selected synthetic identity is set before the fetch. Clearing cached variants first prevents a previous identity's payload from driving the new view.

src/flags.js

```javascript
import { createInstance } from '@amplitude/unified';
export const flagKey='report-layout';
export async function createReportClient({apiKey,deploymentKey,zone='US',instanceName='build-payload-demo',experimentOptions={}}) {
  if(!apiKey?.trim()||!deploymentKey?.trim())return null;
  const analytics=createInstance();
  await analytics.initAll(apiKey,{instanceName,serverZone:zone==='EU'?'EU':'US',analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true},experiment:{deploymentKey,fetchOnStart:false,pollOnStart:false,automaticFetchOnAmplitudeIdentityChange:false,automaticExposureTracking:false,retryFetchOnFailure:false,fetchTimeoutMillis:1000,...experimentOptions}});
  const experiment=analytics.experiment();
  if(!experiment)throw Error('Experiment did not initialize.');
  return {analytics,experiment};
}
```

src/analytics.js

```javascript
import { createReportClient, flagKey } from './flags.js';
import { configFromVariant } from './config.js';
let ready;
export function initializeAnalytics(){
 if(!ready)ready=createReportClient({apiKey:import.meta.env.VITE_AMPLITUDE_API_KEY,deploymentKey:import.meta.env.VITE_AMPLITUDE_DEPLOYMENT_KEY,zone:import.meta.env.VITE_AMPLITUDE_SERVER_ZONE});
 return ready.then(client=>({status:client?'ready':'disabled',client})).catch(()=>({status:'error',client:null}));
}
export async function chooseConfig(client,userId){
 if(!client)return {config:configFromVariant(null),assigned:false};
 client.analytics.setUserId(userId);client.experiment.clear();
 await client.experiment.fetch({user_id:userId,device_id:client.analytics.getDeviceId()});
 const variant=client.experiment.all()[flagKey];
 return {config:configFromVariant(variant),assigned:typeof variant?.value==='string'};
}
export function exposeReport(client){client?.experiment.exposure(flagKey);}
```

Use an existing test flag associated with that client deployment. For the valid path, its expanded variant needs the JSON payload above and a designated expanded test user. Keep control without relying on a payload. Adapt the exact key and synthetic IDs to your test project; no application button changes targeting.

A failed fetch can resolve with cached values. Here the cache is cleared before each selected identity, so missing data falls back locally. A blank key returns disabled. Automatic exposure and identity-change fetches are off; the UI exposes only after it renders the selected assignment.

Unified1.2.1 bundles beta Experiment plugin1.0.0-beta.52. The package is pinned and tested here. Autocapture is off, replay0 and guides and surveys skipped; analytics remote configuration fetching is disabled.

**MCP.** Use the [Docs MCP server](https://amplitude.com/docs/amplitude-ai/docs-mcp-server) to check installed SDK fetch/cache rules before an agent edits your integration. It doesn't validate your flag's actual remote payload or the application's schema.

## 4. Render only the validated configuration

I'll pass the projected config to a report component. The list slices local demo data by its validated limit. The comparison appears only for an explicit true boolean. A visible config source distinguishes valid remote data from control, missing assignment and invalid payload fallback.

src/App.jsx

```jsx
import React,{useRef,useState,useEffect} from 'react';
import {chooseConfig,exposeReport} from './analytics.js';
import {configFromVariant} from './config.js';
export function Report({config}){
 const reports=Array.from({length:10},(_,i)=>`Demo report ${i+1}`);
 return <section id="report"><h2>Local report list</h2><p>Config source: <strong id="config-source">{config.source}</strong></p>
 <p>Report limit: <strong id="report-limit">{config.reportLimit}</strong></p><ul id="reports">{reports.slice(0,config.reportLimit).map(x=><li key={x}>{x}</li>)}</ul>{config.showComparison&&<p id="comparison">Weekly comparison (demo): +2 reports</p>}</section>;
}
export function App({analytics}){
 const [result,setResult]=useState({config:configFromVariant(null),assigned:false}),[busy,setBusy]=useState(false),[token,setToken]=useState(0),[message,setMessage]=useState('Choose an existing designated test identity.');const exposed=useRef(-1);
 useEffect(()=>{if(result.assigned&&exposed.current!==token){exposed.current=token;exposeReport(analytics.client);}},[result,token,analytics.client]);
 async function load(user){if(busy)return;setBusy(true);try{setResult(await chooseConfig(analytics.client,user));setToken(x=>x+1);setMessage('Assignment checked; inspect config source.');}catch{setResult({config:configFromVariant(null),assigned:false});setMessage('Fetch failed; safe defaults.');}finally{setBusy(false);}}
 return <main><h1>Validate remote report configuration</h1><p>This local list contains ten demo reports. A valid expanded payload controls its limit and comparison. Missing or invalid data uses two reports and no comparison.</p>
 <button id="control" disabled={busy} onClick={()=>load('build-ios-flags-control-20261029')}>Load control test user</button>
 <button id="expanded" disabled={busy} onClick={()=>load('build-web-flags-demo')}>Load expanded test user</button>
 <p role="status">{message}</p><p>Analytics: <strong>{analytics.status}</strong></p><Report config={result.config}/></main>;
}
```

src/style.css

```css
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }
```

The effect exposes the assigned variant after React commits the report. Exposure describes the assigned variant even if its malformed payload triggered a safe fallback. Keep that distinction when interpreting a metric; assignment isn't proof that every payload was usable.

The payload is not evaluated as JavaScript or inserted as HTML. Client flags are not an authorization or server-enforced limit: keep permission and billing checks on the server. A local report limit only controls presentation.

## 5. Mount and test the app

I'll start the app once outside the React component tree and retain Strict Mode. The tests exercise the operation or session behavior separately from the UI.

src/main.jsx

```jsx
import React,{StrictMode} from 'react';import {createRoot} from 'react-dom/client';
import {App} from './App.jsx';import {initializeAnalytics} from './analytics.js';import './style.css';
initializeAnalytics().then(analytics=>createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics}/></StrictMode>));
```

tests/payload.test.mjs

```javascript
import React,{act} from 'react';
import {createRoot} from 'react-dom/client';
import {test,expect,vi} from 'vitest';
import {createReportClient,flagKey} from '../src/flags.js';
import {configFromVariant} from '../src/config.js';
import {Report} from '../src/App.jsx';

test('actual Experiment client supplies valid/control/missing/invalid payload inputs to strict application projection',async()=>{
 const variants=[{value:'expanded',payload:{reportLimit:5,showComparison:true}},{value:'control',payload:{reportLimit:9,showComparison:true}},undefined,{value:'expanded'},...[
  null,'{"reportLimit":5,"showComparison":true}',[],{reportLimit:100,showComparison:true},{reportLimit:2.5,showComparison:false},{reportLimit:5,showComparison:'true'},{reportLimit:5,showComparison:true,private:'PRIVATE_PAYLOAD_FIXTURE'}
 ].map(payload=>({value:'expanded',payload}))];
 for(const [index,variant] of variants.entries()){
  const c=await createReportClient({apiKey:'fake-test-key',deploymentKey:'fake-deployment-key',instanceName:crypto.randomUUID(),experimentOptions:{source:'initialVariants',initialVariants:variant?{[flagKey]:variant}:{},httpClient:{request:vi.fn().mockRejectedValue(Error('No network'))}}});
  const result=configFromVariant(c.experiment.all()[flagKey]);
  if(index===0)expect(result).toEqual({reportLimit:5,showComparison:true,source:'remote'});
  else expect(result).toMatchObject({reportLimit:2,showComparison:false});
  expect(JSON.stringify(result)).not.toContain('PRIVATE_PAYLOAD_FIXTURE');
 }
});
test('validated config determines rendered report count and comparison; invalid config uses visible defaults',async()=>{
 globalThis.IS_REACT_ACT_ENVIRONMENT=true;
 const host=document.createElement('div');document.body.append(host);const root=createRoot(host);
 try {
  await act(()=>root.render(React.createElement(Report,{config:configFromVariant({value:'expanded',payload:{reportLimit:5,showComparison:true}})})));
  expect(host.querySelectorAll('li')).toHaveLength(5);expect(host.querySelector('#comparison')).not.toBeNull();
  await act(()=>root.render(React.createElement(Report,{config:configFromVariant({value:'expanded',payload:{reportLimit:999,showComparison:true}})})));
  expect(host.querySelectorAll('li')).toHaveLength(2);expect(host.querySelector('#comparison')).toBeNull();expect(host.querySelector('#config-source').textContent).toBe('invalid_payload');
 }finally{await act(()=>root.unmount());host.remove();}
});
```

Terminal

```sh
pnpm test
pnpm build
pnpm dev
```

Open the local URL printed by Vite.

## Verify it worked

Run local tests first, then verify an existing configured test flag. Treat each kind of evidence separately.

1. **Local validation and rendering:** Run pnpm test. The actual Experiment client supplies valid, control, absent and malformed payload inputs. The React render test shows five reports with comparison for a valid config, then two reports and no comparison for an invalid config. These fixtures do not establish a real remote payload.
2. **Real valid payload:** In your existing test flag, use the expanded JSON `{"reportLimit":5,"showComparison":true}` and an already designated expanded test identity. With the ingestion/client deployment keys set, load that identity. Confirm config source=remote, limit 5, five visible reports and a comparison. Inspect the actual assigned variant payload rather than substituting a local fixture.
3. **Real missing payload:** A real expanded assignment without a payload should show invalid\_payload, two reports and no comparison. A control assignment shows control defaults. Missing flag/key or blank-key mode uses missing\_variant defaults. These are safe outcomes, not evidence of a successful valid-payload fetch.
4. **Malformed data:** The tests exercise a JSON string, array, missing fields, wrong boolean, fractional/out-of-range limit and extra field. Confirm none can bypass the projection or leak the synthetic extra-field marker into the returned config.
5. **Exposure and identity:** Verify the correct assigned flag/variant/user after rendering, with cache clearing before identity changes. Preserve the existing app's auth and consent rather than copying synthetic IDs into production. Configuration fetch and payload validation need their own checks in addition to exposure ingestion.

## Troubleshooting

### Expanded assignment still shows two reports

Inspect config source and the actual variant payload. A missing/malformed payload intentionally uses defaults. The variant value alone does not establish usable remote config.

### The payload is a JSON string instead of an object

Store an actual JSON object in the variant payload. The validator deliberately rejects a string containing JSON rather than guessing how many parsing layers were intended.

### An extra payload field makes the config fall back

This fixture uses an exact schema. Add a reviewed field to the validator and tests before changing the remote format; do not spread arbitrary remote fields into components.

### A user switch shows the old configuration

Clear cached variants before the new identity fetch. A failed refresh can leave cached values; this app chooses safe local defaults instead of another identity's configuration.

### The browser receives no flag

Use the correct client deployment containing that flag. An omitted deploymentKey falls back to the analytics key's default deployment. Keep live targeting changes outside application debugging until deliberately reviewed.

## Full code reference

The [complete runnable example](https://github.com/amplitude/ampli-examples/tree/534513bf81e3222735658d33e812d69c36ae7e0d/browser/javascript/v2/react-feature-flags-payloads) includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.

Full code reference

```text
===== package.json =====
{
  "name": "amplitude-react-feature-flags-payloads",
  "version": "1.0.0",
  "private": true,
  "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",
    "test": "vitest run"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6",
    "vitest": "5.0.5",
    "jsdom": "31.0.0"
  }

===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade

===== .gitignore =====
node_modules/
dist/
.env
.env.local
.env.*.local

===== index.html =====
<!doctype html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Form drop-off demo</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/main.jsx"></script>
  </body>
</html>

===== .env.example =====
VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_DEPLOYMENT_KEY=
VITE_AMPLITUDE_SERVER_ZONE=US

===== vitest.config.js =====
import { defineConfig } from 'vitest/config';
export default defineConfig({ test: { environment: 'jsdom', restoreMocks: true } });

===== src/config.js =====
const defaults=Object.freeze({reportLimit:2,showComparison:false});
export function configFromVariant(variant){
 if(variant?.value!=='expanded')return {...defaults,source:variant?.value==='control'?'control':'missing_variant'};
 const payload=variant.payload;
 const valid=payload!==null&&typeof payload==='object'&&!Array.isArray(payload)&&Object.keys(payload).length===2&&Object.keys(payload).every(k=>['reportLimit','showComparison'].includes(k))&&Number.isInteger(payload.reportLimit)&&payload.reportLimit>=1&&payload.reportLimit<=10&&typeof payload.showComparison==='boolean';
 return valid?{reportLimit:payload.reportLimit,showComparison:payload.showComparison,source:'remote'}:{...defaults,source:'invalid_payload'};
}

===== src/flags.js =====
import { createInstance } from '@amplitude/unified';
export const flagKey='report-layout';
export async function createReportClient({apiKey,deploymentKey,zone='US',instanceName='build-payload-demo',experimentOptions={}}) {
  if(!apiKey?.trim()||!deploymentKey?.trim())return null;
  const analytics=createInstance();
  await analytics.initAll(apiKey,{instanceName,serverZone:zone==='EU'?'EU':'US',analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true},experiment:{deploymentKey,fetchOnStart:false,pollOnStart:false,automaticFetchOnAmplitudeIdentityChange:false,automaticExposureTracking:false,retryFetchOnFailure:false,fetchTimeoutMillis:1000,...experimentOptions}});
  const experiment=analytics.experiment();
  if(!experiment)throw Error('Experiment did not initialize.');
  return {analytics,experiment};
}

===== src/analytics.js =====
import { createReportClient, flagKey } from './flags.js';
import { configFromVariant } from './config.js';
let ready;
export function initializeAnalytics(){
 if(!ready)ready=createReportClient({apiKey:import.meta.env.VITE_AMPLITUDE_API_KEY,deploymentKey:import.meta.env.VITE_AMPLITUDE_DEPLOYMENT_KEY,zone:import.meta.env.VITE_AMPLITUDE_SERVER_ZONE});
 return ready.then(client=>({status:client?'ready':'disabled',client})).catch(()=>({status:'error',client:null}));
}
export async function chooseConfig(client,userId){
 if(!client)return {config:configFromVariant(null),assigned:false};
 client.analytics.setUserId(userId);client.experiment.clear();
 await client.experiment.fetch({user_id:userId,device_id:client.analytics.getDeviceId()});
 const variant=client.experiment.all()[flagKey];
 return {config:configFromVariant(variant),assigned:typeof variant?.value==='string'};
}
export function exposeReport(client){client?.experiment.exposure(flagKey);}

===== src/App.jsx =====
import React,{useRef,useState,useEffect} from 'react';
import {chooseConfig,exposeReport} from './analytics.js';
import {configFromVariant} from './config.js';
export function Report({config}){
 const reports=Array.from({length:10},(_,i)=>`Demo report ${i+1}`);
 return <section id="report"><h2>Local report list</h2><p>Config source: <strong id="config-source">{config.source}</strong></p>
 <p>Report limit: <strong id="report-limit">{config.reportLimit}</strong></p><ul id="reports">{reports.slice(0,config.reportLimit).map(x=><li key={x}>{x}</li>)}</ul>{config.showComparison&&<p id="comparison">Weekly comparison (demo): +2 reports</p>}</section>;
}
export function App({analytics}){
 const [result,setResult]=useState({config:configFromVariant(null),assigned:false}),[busy,setBusy]=useState(false),[token,setToken]=useState(0),[message,setMessage]=useState('Choose an existing designated test identity.');const exposed=useRef(-1);
 useEffect(()=>{if(result.assigned&&exposed.current!==token){exposed.current=token;exposeReport(analytics.client);}},[result,token,analytics.client]);
 async function load(user){if(busy)return;setBusy(true);try{setResult(await chooseConfig(analytics.client,user));setToken(x=>x+1);setMessage('Assignment checked; inspect config source.');}catch{setResult({config:configFromVariant(null),assigned:false});setMessage('Fetch failed; safe defaults.');}finally{setBusy(false);}}
 return <main><h1>Validate remote report configuration</h1><p>This local list contains ten demo reports. A valid expanded payload controls its limit and comparison. Missing or invalid data uses two reports and no comparison.</p>
 <button id="control" disabled={busy} onClick={()=>load('build-ios-flags-control-20261029')}>Load control test user</button>
 <button id="expanded" disabled={busy} onClick={()=>load('build-web-flags-demo')}>Load expanded test user</button>
 <p role="status">{message}</p><p>Analytics: <strong>{analytics.status}</strong></p><Report config={result.config}/></main>;
}

===== src/style.css =====
:root { font-family: Helvetica, Arial, sans-serif; color: #000000; background: #F2F4F8; }
body { margin: 0; }
main { max-width: 760px; margin: 40px auto; padding: 32px; background: #FFFFFF; border-radius: 16px; }
h1 { font-size: 36px; }
p { line-height: 1.5; }
.eyebrow { font-size: 12px; letter-spacing: 0.08em; }
nav { display: flex; gap: 20px; flex-wrap: wrap; padding: 16px 0; }
a { color: #0052F2; }
section, aside { border-top: 1px solid #D5D9E0; margin-top: 24px; padding-top: 24px; }
label { display: block; margin-bottom: 8px; }
button, select, [role='button'] { font: inherit; padding: 10px 14px; margin: 0 12px 12px 0; border: 1px solid #000000; border-radius: 6px; color: #000000; background: #FFFFFF; }
button, [role='button'] { cursor: pointer; }
#save-settings { color: #FFFFFF; background: #0052F2; border-color: #0052F2; }
[role='button'] { display: inline-block; }
:focus-visible { outline: 3px solid #0052F2; outline-offset: 3px; }
code { overflow-wrap: anywhere; }
@media (max-width: 800px) { main { margin: 16px; padding: 24px; } }

button:disabled, select:disabled { opacity: 0.6; cursor: wait; }
form { margin-top: 24px; }

===== src/main.jsx =====
import React,{StrictMode} from 'react';import {createRoot} from 'react-dom/client';
import {App} from './App.jsx';import {initializeAnalytics} from './analytics.js';import './style.css';
initializeAnalytics().then(analytics=>createRoot(document.getElementById('root')).render(<StrictMode><App analytics={analytics}/></StrictMode>));

===== tests/payload.test.mjs =====
import React,{act} from 'react';
import {createRoot} from 'react-dom/client';
import {test,expect,vi} from 'vitest';
import {createReportClient,flagKey} from '../src/flags.js';
import {configFromVariant} from '../src/config.js';
import {Report} from '../src/App.jsx';

test('actual Experiment client supplies valid/control/missing/invalid payload inputs to strict application projection',async()=>{
 const variants=[{value:'expanded',payload:{reportLimit:5,showComparison:true}},{value:'control',payload:{reportLimit:9,showComparison:true}},undefined,{value:'expanded'},...[
  null,'{"reportLimit":5,"showComparison":true}',[],{reportLimit:100,showComparison:true},{reportLimit:2.5,showComparison:false},{reportLimit:5,showComparison:'true'},{reportLimit:5,showComparison:true,private:'PRIVATE_PAYLOAD_FIXTURE'}
 ].map(payload=>({value:'expanded',payload}))];
 for(const [index,variant] of variants.entries()){
  const c=await createReportClient({apiKey:'fake-test-key',deploymentKey:'fake-deployment-key',instanceName:crypto.randomUUID(),experimentOptions:{source:'initialVariants',initialVariants:variant?{[flagKey]:variant}:{},httpClient:{request:vi.fn().mockRejectedValue(Error('No network'))}}});
  const result=configFromVariant(c.experiment.all()[flagKey]);
  if(index===0)expect(result).toEqual({reportLimit:5,showComparison:true,source:'remote'});
  else expect(result).toMatchObject({reportLimit:2,showComparison:false});
  expect(JSON.stringify(result)).not.toContain('PRIVATE_PAYLOAD_FIXTURE');
 }
});
test('validated config determines rendered report count and comparison; invalid config uses visible defaults',async()=>{
 globalThis.IS_REACT_ACT_ENVIRONMENT=true;
 const host=document.createElement('div');document.body.append(host);const root=createRoot(host);
 try {
  await act(()=>root.render(React.createElement(Report,{config:configFromVariant({value:'expanded',payload:{reportLimit:5,showComparison:true}})})));
  expect(host.querySelectorAll('li')).toHaveLength(5);expect(host.querySelector('#comparison')).not.toBeNull();
  await act(()=>root.render(React.createElement(Report,{config:configFromVariant({value:'expanded',payload:{reportLimit:999,showComparison:true}})})));
  expect(host.querySelectorAll('li')).toHaveLength(2);expect(host.querySelector('#comparison')).toBeNull();expect(host.querySelector('#config-source').textContent).toBe('invalid_payload');
 }finally{await act(()=>root.unmount());host.remove();}
});
```

## Hand it to your agent

Use this prompt to adapt the example to an existing application.

Implementation prompt

```text
Use https://amplitude.com/build/react-feature-flags-payloads and its linked source.
Inspect the current SDK entry point and application flow first. Merge into existing
files; preserve auth, consent, routes, and other instrumentation. Fetch current
Amplitude docs for the installed SDK. Keep the ingestion key in the existing
environment mechanism and never add server secrets to browser code.

Read the assigned variant before its payload. Require the exact reviewed object
shape, bounded integer reportLimit and boolean showComparison. Build a new config
object; never spread, evaluate or inject arbitrary payload fields. Keep defaults
in code for control/missing/malformed data and distinguish their source visibly.
Clear prior identity cache before fetch, preserve consent/auth, and expose after
rendering. Test actual SDK inputs and React output locally, then verify a real
valid payload independently. Do not treat a local fixture, missing-payload fallback
or exposure event as proof of a valid remote-config fetch.

Test blank-key startup and failure paths as well as success. Confirm real SDK
uploads and processed data separately from local tests. Report changed files and
remaining coverage limits.
```

## What this unlocks

[Feature flags](https://amplitude.com/feature-management) can change bounded presentation settings while code defines their valid shape and defaults.

[Product analytics](https://amplitude.com/amplitude-analytics) can compare business outcomes alongside \[Experiment] Exposure events; validate payload application separately.

[Session replay](https://amplitude.com/session-replay) can add visual browser context through a separately reviewed capture policy. This example sets replay0.

[Guides and surveys](https://amplitude.com/guides-and-surveys) can support the report experience through their own configuration.

## Frequently asked questions

### Can a payload contain a secret?

No. Browser-delivered flag configuration is visible to the client. Keep credentials and authorization decisions on the server.

### Why reject an otherwise harmless extra field?

An exact schema makes format changes explicit. You can choose a different reviewed compatibility policy, but the example never copies unvalidated fields into its application configuration.

### Does an exposure mean the remote config was applied?

It means the assigned variant was exposed. An invalid payload can still use fallback presentation. Inspect the config source and validate the actual payload when checking that specific outcome.

## Next steps

[Web frameworksReact product analyticsInstall analytics and track deliberate business events.](https://amplitude.com/build/react-product-analytics)[Use caseCustom events alongside autocaptureSeparate interaction capture from confirmed outcomes.](https://amplitude.com/build/react-custom-events)[Use caseStitch client and server eventsUse a consistent identity across browser and backend events.](https://amplitude.com/build/stitch-client-server-events)

Reference docs

[Experiment JavaScript SDK →](https://amplitude.com/docs/sdks/experiment-sdks/experiment-javascript)[Feature Experiment variants →](https://amplitude.com/docs/feature-experiment/data-model)[Configure the Unified SDK →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/instrument-and-configure)[Debug analytics →](https://amplitude.com/docs/analytics/debug-analytics)

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

For agents

[View raw .md](/build/react-feature-flags-payloads.md)[llms.txt](/llms.txt)

## Connect the next event

Make the identity and properties explicit, then verify them in your test project.

[Create a free account](https://app.amplitude.com/signup)[Browse all Build tutorials](https://amplitude.com/build)
