---
title: "How to redact event properties before sending in React"
description: "Redact Amplitude event properties in React with an explicit enrichment policy. Test nested fields, URLs, blocked events, and safe processed data."
canonical: "https://amplitude.com/build/react-event-redaction"
---

# How to redact event properties before sending in React

Redact Amplitude event properties in React with an explicit enrichment policy. Test nested fields, URLs, blocked events, and safe processed data.

Source: https://amplitude.com/build/react-event-redaction

---

# How to redact event properties before sending in React

Add a local enrichment plugin that keeps an explicit event schema and drops unlisted data before upload. Test fake sensitive values and a safe control event in a standalone React app in about 20 minutes.

- React
- Vite
- Unified SDK 1.2.1
- 20 min

Chris Tam · Last updated 13 November 2026

[Product analytics](https://amplitude.com/amplitude-analytics) needs the context you choose to collect. I'll send a synthetic support-search fixture containing fake email, query, and token values through an event policy. The policy keeps only a category, a result flag, and selected SDK identity and timing fields.

In this tutorial, I'll register a local enrichment plugin, test the complete uploaded event, and verify a safe event in Amplitude. The [React analytics tutorial](https://amplitude.com/build/react-product-analytics) covers the broader integration; this example stands alone.

## What you'll build

A React app that sends `Support Search Completed` with `category` and `has_results`, while omitting the fake sensitive fields and URL from its fixture. Unlisted event names and invalid allowed values are dropped. This finite policy retains SDK identifiers; it is not a general personal-data detector or anonymization system.

## 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.
- 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-event-redaction
cd react-event-redaction
mkdir -p src tests
corepack enable
```

package.json

```json
{
  "name": "amplitude-react-event-redaction",
  "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": "node --test tests/*.test.mjs"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6"
  }
```

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>Event redaction 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_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. Define the event policy

I'll use a [local SDK enrichment plugin](https://amplitude.com/docs/sdks/sdk-plugins) to build a new event object. Only listed fields survive. Invalid event names, device IDs, or allowed values return `null`.

src/policy.js

```javascript
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const demoUser = /^build-redaction-[0-9a-f-]{36}$/i;

export function projectAllowedEvent(event) {
  try {
    if (event?.event_type !== 'Support Search Completed' || !uuid.test(event.device_id ?? '')) return null;
    const input = event.event_properties ?? {};
    if (!['billing', 'setup', 'other'].includes(input.category)
      || typeof input.has_results !== 'boolean') return null;
    // Construct a new event: unlisted top-level and nested fields are omitted.
    return {
      event_type: 'Support Search Completed',
      device_id: event.device_id,
      ...(demoUser.test(event.user_id ?? '') ? { user_id: event.user_id } : {}),
      ...(Number.isFinite(event.time) ? { time: event.time } : {}),
      ...(Number.isFinite(event.session_id) ? { session_id: event.session_id } : {}),
      ...(Number.isSafeInteger(event.event_id) ? { event_id: event.event_id } : {}),
      ...(uuid.test(event.insert_id ?? '') ? { insert_id: event.insert_id } : {}),
      event_properties: { category: input.category, has_results: input.has_results },
    };
  } catch {
    return null;
  }

export function redactionPlugin() {
  return {
    name: 'build-redaction-policy', type: 'enrichment',
    execute: async (event) => projectAllowedEvent(event),
  };
}
```

The policy keeps the SDK's UUID device ID and valid timing/deduplication fields. It keeps a user ID only when it matches the demo's approved opaque format. Event properties are restricted to the fixed `category` values and a boolean `has_results`. User properties, groups, page URLs, and all other top-level or nested fields are omitted.

**Why.** Deleting one `email` field leaves other paths untouched. Constructing the output makes the example's collection boundary explicit. The `catch` returns `null`, so a malformed input or unexpected read error doesn't fall back to uploading the original event.

This policy handles one event schema. Review every event type and identifier format before adapting it to an existing app. Retaining device IDs and ordinary network delivery means this isn't anonymization or a complete privacy program.

## 3. Register the plugin before sending events

I'll initialize with automatic capture disabled, then await plugin registration before enabling the send controls. The [Browser reference](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference#plugin) defines the enrichment stage and its drop behavior.

src/analytics.js

```javascript
import * as amplitude from '@amplitude/unified';
import { redactionPlugin } from './policy.js';
import { rawFixture, privateMarker } from './fixture.js';

let ready;
let enabled = false;
export function initializeAnalytics() {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
  if (!ready) {
    ready = amplitude.initAll(apiKey, {
      serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
      analytics: {
        autocapture: false, remoteConfig: { fetchRemoteConfig: false },
        transport: { type: 'fetch', referrerPolicy: 'no-referrer' },
      },
      sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
    }).then(async () => {
      await amplitude.add(redactionPlugin()).promise;
      enabled = true;
      return { status: 'ready', deviceId: amplitude.getDeviceId() };
    }).catch((error) => {
      console.error('Policy initialization failed', error);
      return { status: 'error', deviceId: null };
    });
  }
  return ready;
}

export async function sendPolicyFixture(blocked = false) {
  if (!enabled) return 'Analytics disabled. Add the test-project key and rebuild.';
  const event = blocked ? { event_type: `${privateMarker} Unknown Event` } : rawFixture(window.location.href);
  const result = await amplitude.track(event).promise;
  if (blocked && result.code === 0) return 'Unlisted event dropped by the policy.';
  if (result.code !== 200) throw new Error(result.message);
  return 'Allowed event accepted. Inspect the actual uploaded and processed fields.';
}
```

The SDK runs enrichment before destinations. This app adds its policy after initialization and before application tracking. Replay sampling is zero, guides and surveys are skipped, and analytics remote fetching is disabled. The upload uses fetch with a `no-referrer` policy; the event policy also omits the fixture's URL field.

The fixture deliberately supplies a fake user ID in one event; the policy removes it. A production implementation should use its approved stable account identifiers and cover the existing taxonomy. Other SDK instances, server events, replay, and external destinations need their own collection policy.

**MCP.** Use the [Docs MCP server](https://amplitude.com/docs/amplitude-ai/docs-mcp-server) to check the current `add` and plugin contracts before modifying an existing pipeline. That server reads public docs, not your live event data.

## 4. Add a synthetic privacy fixture

I'll keep the raw test values in a clearly labeled fixture, then send it through the actual SDK. A second button attempts an event name outside the allowlist.

src/fixture.js

```javascript
export const privateMarker = 'PRIVATE_FIXTURE_20261113';

export function rawFixture(pageUrl) {
  return {
    event_type: 'Support Search Completed',
    user_id: `${privateMarker}@example.test`,
    user_properties: { email: `${privateMarker}@example.test`, nested: { token: privateMarker } },
    groups: { company: privateMarker },
    event_properties: {
      category: 'billing', has_results: true,
      email: `${privateMarker}@example.test`,
      query: privateMarker, page_location: pageUrl,
      nested: { secret: privateMarker },
    },
  };
}
```

src/App.jsx

```jsx
import React, { useRef, useState } from 'react';
import { sendPolicyFixture } from './analytics.js';
import { privateMarker } from './fixture.js';

export function App({ analytics }) {
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('Send a synthetic fixture through the policy.');
  const pending = useRef(false);
  async function send(blocked) {
    if (pending.current) return;
    pending.current = true; setBusy(true);
    try { setMessage(await sendPolicyFixture(blocked)); }
    catch (error) { setMessage(error.message); }
    finally { pending.current = false; setBusy(false); }
  }
  return (
    <main>
      <p className="eyebrow">EVENT POLICY DEMO</p><h1>Redact before upload</h1>
      <p>This fixture uses fake email, search text, and token values marked <code>{privateMarker}</code>. The policy keeps a category and result flag, plus selected SDK identifiers and timing. It is a finite example policy, not a general detector of personal data.</p>
      <button id="send-allowed" disabled={busy} onClick={() => send(false)}>Send allowed fixture</button>
      <button id="send-blocked" disabled={busy} onClick={() => send(true)}>Try an unlisted event</button>
      <p role="status">{busy ? 'Processing...' : message}</p>
      <aside>
        <p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p>
      </aside>
    </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; }
```

Use the fake `PRIVATE_FIXTURE_20261113` marker rather than real personal data. Putting it in the local page query and fragment also checks that the allowed event doesn't inherit that URL. Keep automatic capture off while testing the fixture.

## 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/policy.test.mjs

```javascript
import test from 'node:test';
import assert from 'node:assert/strict';
import { projectAllowedEvent, redactionPlugin } from '../src/policy.js';
import { rawFixture, privateMarker } from '../src/fixture.js';

const device = '11111111-2222-4333-8444-555555555555';
test('entire projected event excludes fixture values at every level without mutating input', async () => {
  const input = { ...rawFixture(`https://example.test/?email=${privateMarker}#${privateMarker}`), device_id: device, time: 123 };
  const original = JSON.stringify(input);
  const event = await redactionPlugin().execute(input);
  assert.deepEqual(event, { event_type: 'Support Search Completed', device_id: device, time: 123, event_properties: { category: 'billing', has_results: true } });
  assert.ok(!JSON.stringify(event).includes(privateMarker));
  assert.equal(JSON.stringify(input), original);
});

test('unlisted events, malformed categories and malformed identity are dropped', () => {
  assert.equal(projectAllowedEvent({ event_type: privateMarker, device_id: device }), null);
  assert.equal(projectAllowedEvent({ ...rawFixture('https://example.test'), device_id: privateMarker }), null);
  assert.equal(projectAllowedEvent({ ...rawFixture('https://example.test'), device_id: device, event_properties: { category: privateMarker, has_results: true } }), null);
});

test('unexpected policy read errors fail closed', () => {
  const event = { event_type: 'Support Search Completed', device_id: device,
    get event_properties() { throw new Error('Untrusted getter'); } };
  assert.equal(projectAllowedEvent(event), null);
});
```

Terminal

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

Open the local URL printed by Vite.

## Verify it worked

Inspect the whole uploaded event, including identifiers and nested fields, then confirm the safe result is processed.

1. **Blank-key app:** Run once with no key. Confirm analytics is disabled and clicking the allowed-fixture button sends no Amplitude event. Add the test key and rebuild.
2. **Allowed fixture:** Open the app with `?email=PRIVATE_FIXTURE_20261113#token=PRIVATE_FIXTURE_20261113` added to its local URL. Click Send allowed fixture. Confirm HTTP 200 transport acceptance, then use Instrumentation Explorer to inspect the complete event. The marker, fake email, nested token, groups, user properties, and full page URL should be absent. `category: billing` and `has_results: true` should remain.
3. **Dropped event:** Click Try an unlisted event. Confirm the UI reports a policy drop and that no corresponding upload appears over a bounded observation window. Send the allowed fixture again to confirm tracking remains functional.
4. **Processed result:** In User Lookup, search the displayed device ID and inspect the two `Support Search Completed` events. Events normally populate in ten seconds to one minute. Match timestamps, verify the two safe properties, and inspect Raw for unexpected fields. Network shows upload status; the extension and processed event show contents because SDK requests can be compressed.

## Troubleshooting

### The fake email still appears

Confirm the running build registered the plugin before application tracking. Inspect the entire event rather than only event\_properties, and check for another SDK instance or destination that bypasses this policy.

### Every event is dropped

This example only permits `Support Search Completed` with one of the three category values and a boolean result flag. Add a reviewed schema for another event rather than making the policy pass everything through.

### A user profile is still identifiable

The example retains SDK device identifiers and can retain approved user IDs. It doesn't delete earlier events, erase server-side profiles, or remove all network metadata. Choose identity and retention policies separately.

### An exception restores the original event

Keep projection errors handled inside your own policy and return `null`. Don't catch an error by returning the unmodified input. Verify the malformed-input path as well as successful redaction.

### The property panel looks clean but another field contains a test value

Inspect Raw and the complete outbound event. Sensitive values can occur in event names, identifiers, user properties, groups, or URL/context properties. The new-object projection is intended to make those paths explicit.

## Full code reference

The [complete runnable example](https://github.com/amplitude/ampli-examples/tree/43ade017989c2660f6288a6954aa81ac9da84bd6/browser/javascript/v2/react-event-redaction) 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-event-redaction",
  "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": "node --test tests/*.test.mjs"
  },
  "dependencies": {
    "@amplitude/unified": "1.2.1",
    "react": "19.3.1",
    "react-dom": "19.3.1"
  },
  "devDependencies": {
    "vite": "8.3.6"
  }

===== 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>Event redaction 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_SERVER_ZONE=US

===== src/policy.js =====
const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const demoUser = /^build-redaction-[0-9a-f-]{36}$/i;

export function projectAllowedEvent(event) {
  try {
    if (event?.event_type !== 'Support Search Completed' || !uuid.test(event.device_id ?? '')) return null;
    const input = event.event_properties ?? {};
    if (!['billing', 'setup', 'other'].includes(input.category)
      || typeof input.has_results !== 'boolean') return null;
    // Construct a new event: unlisted top-level and nested fields are omitted.
    return {
      event_type: 'Support Search Completed',
      device_id: event.device_id,
      ...(demoUser.test(event.user_id ?? '') ? { user_id: event.user_id } : {}),
      ...(Number.isFinite(event.time) ? { time: event.time } : {}),
      ...(Number.isFinite(event.session_id) ? { session_id: event.session_id } : {}),
      ...(Number.isSafeInteger(event.event_id) ? { event_id: event.event_id } : {}),
      ...(uuid.test(event.insert_id ?? '') ? { insert_id: event.insert_id } : {}),
      event_properties: { category: input.category, has_results: input.has_results },
    };
  } catch {
    return null;
  }

export function redactionPlugin() {
  return {
    name: 'build-redaction-policy', type: 'enrichment',
    execute: async (event) => projectAllowedEvent(event),
  };
}

===== src/analytics.js =====
import * as amplitude from '@amplitude/unified';
import { redactionPlugin } from './policy.js';
import { rawFixture, privateMarker } from './fixture.js';

let ready;
let enabled = false;
export function initializeAnalytics() {
  const apiKey = import.meta.env.VITE_AMPLITUDE_API_KEY?.trim();
  if (!apiKey) return Promise.resolve({ status: 'disabled', deviceId: null });
  if (!ready) {
    ready = amplitude.initAll(apiKey, {
      serverZone: import.meta.env.VITE_AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
      analytics: {
        autocapture: false, remoteConfig: { fetchRemoteConfig: false },
        transport: { type: 'fetch', referrerPolicy: 'no-referrer' },
      },
      sessionReplay: { sampleRate: 0 }, engagement: { skip: true },
    }).then(async () => {
      await amplitude.add(redactionPlugin()).promise;
      enabled = true;
      return { status: 'ready', deviceId: amplitude.getDeviceId() };
    }).catch((error) => {
      console.error('Policy initialization failed', error);
      return { status: 'error', deviceId: null };
    });
  }
  return ready;
}

export async function sendPolicyFixture(blocked = false) {
  if (!enabled) return 'Analytics disabled. Add the test-project key and rebuild.';
  const event = blocked ? { event_type: `${privateMarker} Unknown Event` } : rawFixture(window.location.href);
  const result = await amplitude.track(event).promise;
  if (blocked && result.code === 0) return 'Unlisted event dropped by the policy.';
  if (result.code !== 200) throw new Error(result.message);
  return 'Allowed event accepted. Inspect the actual uploaded and processed fields.';
}

===== src/fixture.js =====
export const privateMarker = 'PRIVATE_FIXTURE_20261113';

export function rawFixture(pageUrl) {
  return {
    event_type: 'Support Search Completed',
    user_id: `${privateMarker}@example.test`,
    user_properties: { email: `${privateMarker}@example.test`, nested: { token: privateMarker } },
    groups: { company: privateMarker },
    event_properties: {
      category: 'billing', has_results: true,
      email: `${privateMarker}@example.test`,
      query: privateMarker, page_location: pageUrl,
      nested: { secret: privateMarker },
    },
  };
}

===== src/App.jsx =====
import React, { useRef, useState } from 'react';
import { sendPolicyFixture } from './analytics.js';
import { privateMarker } from './fixture.js';

export function App({ analytics }) {
  const [busy, setBusy] = useState(false);
  const [message, setMessage] = useState('Send a synthetic fixture through the policy.');
  const pending = useRef(false);
  async function send(blocked) {
    if (pending.current) return;
    pending.current = true; setBusy(true);
    try { setMessage(await sendPolicyFixture(blocked)); }
    catch (error) { setMessage(error.message); }
    finally { pending.current = false; setBusy(false); }
  }
  return (
    <main>
      <p className="eyebrow">EVENT POLICY DEMO</p><h1>Redact before upload</h1>
      <p>This fixture uses fake email, search text, and token values marked <code>{privateMarker}</code>. The policy keeps a category and result flag, plus selected SDK identifiers and timing. It is a finite example policy, not a general detector of personal data.</p>
      <button id="send-allowed" disabled={busy} onClick={() => send(false)}>Send allowed fixture</button>
      <button id="send-blocked" disabled={busy} onClick={() => send(true)}>Try an unlisted event</button>
      <p role="status">{busy ? 'Processing...' : message}</p>
      <aside>
        <p>Analytics: <strong id="analytics-status">{analytics.status}</strong></p>
        <p>Device ID: <code id="device-id">{analytics.deviceId ?? 'not initialized'}</code></p>
      </aside>
    </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/policy.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { projectAllowedEvent, redactionPlugin } from '../src/policy.js';
import { rawFixture, privateMarker } from '../src/fixture.js';

const device = '11111111-2222-4333-8444-555555555555';
test('entire projected event excludes fixture values at every level without mutating input', async () => {
  const input = { ...rawFixture(`https://example.test/?email=${privateMarker}#${privateMarker}`), device_id: device, time: 123 };
  const original = JSON.stringify(input);
  const event = await redactionPlugin().execute(input);
  assert.deepEqual(event, { event_type: 'Support Search Completed', device_id: device, time: 123, event_properties: { category: 'billing', has_results: true } });
  assert.ok(!JSON.stringify(event).includes(privateMarker));
  assert.equal(JSON.stringify(input), original);
});

test('unlisted events, malformed categories and malformed identity are dropped', () => {
  assert.equal(projectAllowedEvent({ event_type: privateMarker, device_id: device }), null);
  assert.equal(projectAllowedEvent({ ...rawFixture('https://example.test'), device_id: privateMarker }), null);
  assert.equal(projectAllowedEvent({ ...rawFixture('https://example.test'), device_id: device, event_properties: { category: privateMarker, has_results: true } }), null);
});

test('unexpected policy read errors fail closed', () => {
  const event = { event_type: 'Support Search Completed', device_id: device,
    get event_properties() { throw new Error('Untrusted getter'); } };
  assert.equal(projectAllowedEvent(event), null);
});
```

## 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-event-redaction 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.

Build an explicit output schema in a local enrichment plugin. Return null for
unlisted event types, invalid values, or policy errors. Register and await the
plugin before application tracking. Cover top-level identity, user properties,
groups, nested data and URL/context fields; do not only delete one email key.
Preserve only approved identifiers and metadata. Do not describe this finite
policy as general PII detection or anonymization. Test with synthetic markers,
inspect complete real SDK uploads, verify a safe processed event, and test drops.
Keep replay, other SDK instances and destinations within their own reviewed policy.

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

[Product analytics](https://amplitude.com/amplitude-analytics) can compare support-search outcomes by the allowed `category` property.

[Session replay](https://amplitude.com/session-replay) can be configured separately when its own masking and capture policy is ready.

[Feature flags](https://amplitude.com/feature-management) can vary a future search experience while a reviewed event schema measures outcomes.

[Guides and surveys](https://amplitude.com/guides-and-surveys) can collect feedback through a separately configured experience; their data needs its own policy.

## Frequently asked questions

### Does this find every kind of personal data?

No. It implements a finite allowlist for one fixture and preserves SDK identifiers. Define approved schemas and review the full collection path for your application instead of treating a regex or this demo as universal detection.

### Is this configured in Amplitude remote settings?

This example is a local plugin added with `add`. It ships with the application code. It doesn't enable a remotely supplied enrichment function or require a project-setting change.

### Does it redact existing data?

It changes the event sent by this client after registration. It doesn't rewrite events already ingested or apply to another client, server, or destination.

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

[SDK plugins →](https://amplitude.com/docs/sdks/sdk-plugins)[Plugin contract →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference#plugin)[Browser transport and configuration →](https://amplitude.com/docs/sdks/analytics/browser/browser-sdk-2/reference)[Install the Browser Unified SDK →](https://amplitude.com/docs/sdks/analytics/browser/browser-unified-sdk/get-started)[Debug analytics →](https://amplitude.com/docs/analytics/debug-analytics)[Docs MCP server →](https://amplitude.com/docs/amplitude-ai/docs-mcp-server)

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-event-redaction.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)
