Chris Tam · Last updated 13 November 2026
Product analytics keeps development activity out of a production dataset when each build uses the intended project's ingestion key. I'll build a local React fixture in three Vite modes. Its button sends an environment-check event with a synthetic build marker; its screen shows the configured destination so I can compare it with processed data.
For this recipe, all three destinations should be designated test projects, including the production-mode destination. A production build mode isn't permission to send fixtures to a real production project. The checks below separate local configuration validation from actual routing verification.
What you'll build
A standalone Vite app with three mode-specific local environment files, a pre-build guard for distinct keys/project IDs/markers, and an explicit event per test build. The UI displays configuration labels; only Amplitude's processed events establish the actual destination.
Prerequisites
- Node.js 22.12 or later and Corepack for pnpm.
- Three designated Amplitude ingestion test projects and their own keys/IDs, with permission to inspect events. Open Organization settings > API Keys and select each project. A portfolio project is not an ingestion test destination.
- 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 to get your project API key.
1. Create the standalone app
I'll use the Browser Unified SDK package installation in a small Vite app. The versions below are pinned to the tested example.
mkdir vite-analytics-environments
cd vite-analytics-environments
mkdir -p src tests scripts
corepack enable{
"name": "amplitude-vite-analytics-environments",
"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",
"test": "node --test tests/*.test.mjs",
"check:env": "node scripts/check-environments.mjs",
"build:development": "node scripts/check-environments.mjs && vite build --mode development --outDir dist/development",
"build:staging": "node scripts/check-environments.mjs && vite build --mode staging --outDir dist/staging",
"build:production": "node scripts/check-environments.mjs && vite build --mode production --outDir dist/production",
"build": "pnpm build:development && pnpm build:staging && pnpm build:production",
"preview": "vite preview --host 127.0.0.1"
},
"dependencies": {
"@amplitude/unified": "1.2.1",
"react": "19.3.1",
"react-dom": "19.3.1"
},
"devDependencies": {
"vite": "8.3.6"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradenode_modules/
dist/
.env
.env.local
.env.*.local<!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>VITE_AMPLITUDE_API_KEY=
VITE_AMPLITUDE_PROJECT_ID=
VITE_APP_ENV=development
VITE_AMPLITUDE_SERVER_ZONE=US
VITE_BUILD_MARKER=build-env-development-v1corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.development.local
cp .env.example .env.staging.local
cp .env.example .env.production.localUse three designated ingestion projects: development, staging, and a production-mode test destination. In each corresponding mode file, set its distinct VITE_AMPLITUDE_API_KEY, numeric VITE_AMPLITUDE_PROJECT_ID, exact VITE_APP_ENV, explicit VITE_AMPLITUDE_SERVER_ZONE (US or EU), and unique VITE_BUILD_MARKER. Do not store these keys in a generic .env.local file. Use plain unquoted values. Project IDs and keys must be correctly paired; the guard cannot establish ownership from their strings.
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. Validate the three mode files before bundling
I'll follow Vite's environment and mode rules and keep all five settings in each mode-specific file. The build scripts run a guard first. It requires three distinct ingestion keys, project IDs and markers, with the environment label matching its mode.
export const modes=['development','staging','production'];
export function resolveEnvironment(mode,env){
if(!modes.includes(mode))throw Error('Unknown build mode.');
if(!env.VITE_AMPLITUDE_API_KEY?.trim())return {mode,status:'disabled'};
if(!/^[a-zA-Z0-9_-]{10,128}$/.test(env.VITE_AMPLITUDE_API_KEY.trim()))throw Error('Use a plain ingestion key without quotes or variable expansion.');
if(env.VITE_APP_ENV!==mode)throw Error('Environment label must match the Vite mode.');
if(!/^\d{3,12}$/.test(env.VITE_AMPLITUDE_PROJECT_ID||''))throw Error('Set the designated numeric project ID.');
if(!['US','EU'].includes(env.VITE_AMPLITUDE_SERVER_ZONE))throw Error('Use an explicit US or EU zone.');
if(!/^build-env-[a-z0-9-]{3,80}$/.test(env.VITE_BUILD_MARKER||''))throw Error('Use a synthetic build-env- marker.');
return {mode,status:'configured',apiKey:env.VITE_AMPLITUDE_API_KEY.trim(),projectId:env.VITE_AMPLITUDE_PROJECT_ID,zone:env.VITE_AMPLITUDE_SERVER_ZONE,marker:env.VITE_BUILD_MARKER};
}
export function validateProfiles(profiles){
const resolved=modes.map(mode=>resolveEnvironment(mode,profiles[mode]||{}));
if(resolved.some(x=>x.status!=='configured'))throw Error('Configure all three mode files first.');
for(const field of ['apiKey','projectId','marker'])if(new Set(resolved.map(x=>x[field])).size!==3)throw Error(`Each mode needs a distinct ${field}.`);
return resolved;
}import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import { modes,validateProfiles } from '../src/environment.js';
export function readProfiles(root=process.cwd(),processEnv=process.env){
const keys=['VITE_AMPLITUDE_API_KEY','VITE_AMPLITUDE_PROJECT_ID','VITE_APP_ENV','VITE_AMPLITUDE_SERVER_ZONE','VITE_BUILD_MARKER'];
for(const key of keys)if(processEnv[key]!==undefined)throw Error('Remove global VITE environment overrides; use the reviewed mode files.');
const profiles={};
for(const mode of modes){
const text=readFileSync(`${root}/.env.${mode}.local`,'utf8');
profiles[mode]=Object.fromEntries(text.split('\n').filter(x=>x.trim()&&!x.trim().startsWith('#')).map(line=>{const i=line.indexOf('=');if(i<0)throw Error('Use plain KEY=value lines.');return [line.slice(0,i).trim(),line.slice(i+1).trim()];}));
}
return validateProfiles(profiles);
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
try{console.log(readProfiles().map(({mode,projectId,marker})=>({mode,projectId,marker})));}
catch(e){console.error(e.message);process.exitCode=1;}
}Use plain unquoted values without variable expansion. The key validator rejects quotes, spaces and expansion syntax. The build guard also rejects global process-level overrides of these VITE settings because Vite gives them higher priority than files. This keeps the reviewed mode files authoritative for the recipe; don't bypass it with an unguarded vite build command.
Set development/staging/production as each file's VITE_APP_ENV and give each a distinct build-env- marker. Supply each designated project's own numeric ID, key and data center. The production-mode file still points to the designated production-mode test project for this initial exercise.
Why. A single .env.local key is loaded for all modes and can make a staging build send to the wrong place. A different label or instanceName doesn't change the key's ingestion destination. Separate projects and the correct keys establish the intended routing, which still needs a live check.
3. Initialize from the compiled mode configuration
I'll resolve import.meta.env.MODE and its selected values, then initialize the SDK once with that key and data center. Unknown modes or inconsistent configured values fail closed; a missing key leaves the app disabled.
import * as amplitude from '@amplitude/unified';
import {resolveEnvironment} from './environment.js';
let ready;
export function initializeAnalytics(){
if(!ready)ready=(async()=>{
const config=resolveEnvironment(import.meta.env.MODE,import.meta.env);
if(config.status==='disabled')return config;
await amplitude.initAll(config.apiKey,{instanceName:'build-env-'+config.mode,serverZone:config.zone,analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true}});
return {mode:config.mode,status:'ready',projectId:config.projectId,marker:config.marker,deviceId:amplitude.getDeviceId()};
})().catch(()=>({mode:import.meta.env.MODE,status:'error'}));
return ready;
}
export async function sendEnvironmentCheck(config){
if(config.status!=='ready')return {code:0};
return amplitude.track('Build Environment Check',{app_environment:config.mode,configured_project_id:config.projectId,build_marker:config.marker}).promise;
}VITE_ values are bundled into client code. The Amplitude ingestion key is public and has minimum ingestion scope; secret keys stay on a server. The displayed project ID is a human-entered label, not a server lookup that proves the key belongs to that ID.
Vite mode and NODE_ENV are different. A staging mode build can still be an optimized production build. Changing the local env file after compilation doesn't change an already served bundle: rebuild and preview the correct output directory.
Autocapture is off, replay0 and guides and surveys skipped. Analytics remote fetching is disabled so these local collection settings apply. Keep your existing auth and consent when adapting this into an application.
MCP. Use the Docs MCP server to check current SDK configuration before an agent adapts your build. It can't verify that your environment secret store contains the key for the intended Amplitude project.
4. Display the configured destination and send one check
I'll show the compiled mode, project label, build marker and SDK device ID. The button sends one explicit Build Environment Check. Its success message reports HTTP acceptance, then asks for the separate processed-destination check.
import React,{useState} from 'react';
import {sendEnvironmentCheck} from './analytics.js';
export function App({analytics}){
const [busy,setBusy]=useState(false),[message,setMessage]=useState('Use only the three designated test destinations.');
async function send(){if(busy||analytics.status!=='ready')return;setBusy(true);try{const result=await sendEnvironmentCheck(analytics);setMessage(result.code===200?'HTTP accepted. Verify the destination in Amplitude.':'Upload not accepted.');}catch{setMessage('Upload failed.');}finally{setBusy(false);}}
return <main><h1>Check the analytics environment</h1><p>Each Vite mode builds with its own ingestion key. This UI displays configured labels, not a server-verified project lookup.</p><p>Status: <strong id="status">{analytics.status}</strong></p><p>Mode: <strong id="mode">{analytics.mode}</strong></p><p>Configured project: <code id="project">{analytics.projectId||'unconfigured'}</code></p><p>Marker: <code id="marker">{analytics.marker||'unconfigured'}</code></p><p>Device: <code id="device">{analytics.deviceId||'not initialized'}</code></p><button id="send" disabled={busy||analytics.status!=='ready'} onClick={send}>Send environment check</button><p role="status">{message}</p></main>;
}: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 event carries app_environment, configured_project_id and build_marker. Those properties help find the fixture, but they don't move an event between projects. If a key/project label pair is wrong, inspect the actual ingestion destination and correct the mode file.
Use three separate preview ports or stop one preview before opening the next output. A preview server serves the compiled directory; its own runtime mode doesn't select a new key.
5. Mount and test the app
I'll start the app once outside the React component tree and retain Strict Mode. The tests check configuration rejection and the actual mode-file reader before any SDK upload.
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>));import test from 'node:test';import assert from 'node:assert/strict';
import {mkdtemp,writeFile,rm} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join} from 'node:path';
import {modes,resolveEnvironment,validateProfiles} from '../src/environment.js';import {readProfiles} from '../scripts/check-environments.mjs';
const profiles=()=>Object.fromEntries(modes.map((mode,i)=>[mode,{VITE_APP_ENV:mode,VITE_AMPLITUDE_API_KEY:'fixture-key-'+mode,VITE_AMPLITUDE_PROJECT_ID:String(700001+i),VITE_AMPLITUDE_SERVER_ZONE:'US',VITE_BUILD_MARKER:'build-env-'+mode+'-test'}]));
test('mode/label/region/id validation and disabled mode fail closed',()=>{
const p=profiles();assert.equal(validateProfiles(p).length,3);
assert.deepEqual(resolveEnvironment('development',{}),{mode:'development',status:'disabled'});
assert.throws(()=>resolveEnvironment('preview',{}),/Unknown/);
for(const bad of [{VITE_APP_ENV:'production'},{VITE_AMPLITUDE_SERVER_ZONE:'unknown'},{VITE_AMPLITUDE_PROJECT_ID:'wrong'},{VITE_BUILD_MARKER:'raw-url'},{VITE_AMPLITUDE_API_KEY:'${OTHER_KEY}'}])assert.throws(()=>resolveEnvironment('development',{...p.development,...bad}));
for(const key of ['VITE_AMPLITUDE_API_KEY','VITE_AMPLITUDE_PROJECT_ID','VITE_BUILD_MARKER']){const p=profiles();p.staging[key]=p.development[key];assert.throws(()=>validateProfiles(p),/distinct/);}
});
test('actual mode-file reader rejects missing/reused destinations without printing keys',async()=>{
const dir=await mkdtemp(join(tmpdir(),'env-'));try{
await assert.rejects(async()=>readProfiles(dir));const p=profiles();
for(const mode of modes)await writeFile(join(dir,`.env.${mode}.local`),Object.entries(p[mode]).map(([k,v])=>k+'='+v).join('\n'));
assert.deepEqual(readProfiles(dir).map(x=>x.mode),modes);
assert.throws(()=>readProfiles(dir,{VITE_AMPLITUDE_API_KEY:'global-key-override'}),/global VITE/);
p.staging.VITE_AMPLITUDE_PROJECT_ID=p.development.VITE_AMPLITUDE_PROJECT_ID;
await writeFile(join(dir,'.env.staging.local'),Object.entries(p.staging).map(([k,v])=>k+'='+v).join('\n'));
assert.throws(()=>readProfiles(dir),/distinct projectId/);
}finally{await rm(dir,{recursive:true,force:true});}
});pnpm test
pnpm check:env
pnpm build
pnpm preview --outDir dist/development --port 5198
# In separate terminals:
pnpm preview --outDir dist/staging --port 5199
pnpm preview --outDir dist/production --port 5200Open the three local preview URLs printed by Vite. The output directories were compiled with their respective modes.
Verify it worked
Test the three builds with designated ingestion projects and unique synthetic markers. Keep the same run markers while checking all destinations.
- Local validation: Run pnpm test and pnpm check:env. The tests reject unknown/mismatched mode, wrong zone/ID/marker, reused destinations and a global VITE override. Blank-key resolution stays disabled. These assertions do not contact Amplitude.
- Build each mode: Run pnpm build to create dist/development, dist/staging and dist/production. Preview each directory as shown above. Confirm the screen's mode, project label and marker match the reviewed file. Restart/rebuild after configuration changes.
- Actual ingestion: In each compiled preview, send one environment check. Confirm HTTP200, then use Instrumentation Explorer to inspect the full event and SDK device ID. SDK bodies may be compressed, so use Network for status and the extension for event contents.
- Destination and separation: In each designated project, find its own marker in User Lookup Activity or an event query. Allow ten seconds to one minute. Verify that the other two markers are absent from that project over the same time window. Repeat for all three projects. A configured ID on the app screen is not proof of routing.
- Wrong configuration: Reusing a key/project ID or mismatching a mode label should fail the build guard before bundling. If an incorrectly paired but distinct key and label still passes, the live destination check catches it; correct the pairing and rebuild before using the configuration.
Troubleshooting
Staging events appear in the wrong project
The ingestion key determines the actual project. Compare the compiled mode file and any process-level overrides, then rebuild. An event property or instanceName cannot reroute an already sent event.
The guard rejects a global VITE variable
This recipe uses reviewed mode files, and Vite would otherwise prefer global values. Remove those overrides for these build scripts, or deliberately redesign and test the CI configuration rather than bypassing the guard.
Changing .env has no effect on preview
The values were compiled into the bundle. Rebuild the selected output and serve that directory. Vite preview does not inject new analytics keys at runtime.
The app says ready but the project ID is wrong
Ready means SDK initialization completed. The ID is configured text, not an API-key ownership check. Inspect processed data in the intended project and correct the key/ID pairing.
I only have one designated test project
Finish local configuration tests, but keep the three-project live separation check pending. Do not substitute a production or portfolio project just to claim the check passed.
Full code reference
The complete runnable example includes the lockfile. These are the complete application and test files, combined for copying. Keep environment values local.
===== package.json =====
{
"name": "amplitude-vite-analytics-environments",
"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",
"test": "node --test tests/*.test.mjs",
"check:env": "node scripts/check-environments.mjs",
"build:development": "node scripts/check-environments.mjs && vite build --mode development --outDir dist/development",
"build:staging": "node scripts/check-environments.mjs && vite build --mode staging --outDir dist/staging",
"build:production": "node scripts/check-environments.mjs && vite build --mode production --outDir dist/production",
"build": "pnpm build:development && pnpm build:staging && pnpm build:production",
"preview": "vite preview --host 127.0.0.1"
},
"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>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_PROJECT_ID=
VITE_APP_ENV=development
VITE_AMPLITUDE_SERVER_ZONE=US
VITE_BUILD_MARKER=build-env-development-v1
===== src/environment.js =====
export const modes=['development','staging','production'];
export function resolveEnvironment(mode,env){
if(!modes.includes(mode))throw Error('Unknown build mode.');
if(!env.VITE_AMPLITUDE_API_KEY?.trim())return {mode,status:'disabled'};
if(!/^[a-zA-Z0-9_-]{10,128}$/.test(env.VITE_AMPLITUDE_API_KEY.trim()))throw Error('Use a plain ingestion key without quotes or variable expansion.');
if(env.VITE_APP_ENV!==mode)throw Error('Environment label must match the Vite mode.');
if(!/^\d{3,12}$/.test(env.VITE_AMPLITUDE_PROJECT_ID||''))throw Error('Set the designated numeric project ID.');
if(!['US','EU'].includes(env.VITE_AMPLITUDE_SERVER_ZONE))throw Error('Use an explicit US or EU zone.');
if(!/^build-env-[a-z0-9-]{3,80}$/.test(env.VITE_BUILD_MARKER||''))throw Error('Use a synthetic build-env- marker.');
return {mode,status:'configured',apiKey:env.VITE_AMPLITUDE_API_KEY.trim(),projectId:env.VITE_AMPLITUDE_PROJECT_ID,zone:env.VITE_AMPLITUDE_SERVER_ZONE,marker:env.VITE_BUILD_MARKER};
}
export function validateProfiles(profiles){
const resolved=modes.map(mode=>resolveEnvironment(mode,profiles[mode]||{}));
if(resolved.some(x=>x.status!=='configured'))throw Error('Configure all three mode files first.');
for(const field of ['apiKey','projectId','marker'])if(new Set(resolved.map(x=>x[field])).size!==3)throw Error(`Each mode needs a distinct ${field}.`);
return resolved;
}
===== scripts/check-environments.mjs =====
import { readFileSync } from 'node:fs';
import { pathToFileURL } from 'node:url';
import { modes,validateProfiles } from '../src/environment.js';
export function readProfiles(root=process.cwd(),processEnv=process.env){
const keys=['VITE_AMPLITUDE_API_KEY','VITE_AMPLITUDE_PROJECT_ID','VITE_APP_ENV','VITE_AMPLITUDE_SERVER_ZONE','VITE_BUILD_MARKER'];
for(const key of keys)if(processEnv[key]!==undefined)throw Error('Remove global VITE environment overrides; use the reviewed mode files.');
const profiles={};
for(const mode of modes){
const text=readFileSync(`${root}/.env.${mode}.local`,'utf8');
profiles[mode]=Object.fromEntries(text.split('\n').filter(x=>x.trim()&&!x.trim().startsWith('#')).map(line=>{const i=line.indexOf('=');if(i<0)throw Error('Use plain KEY=value lines.');return [line.slice(0,i).trim(),line.slice(i+1).trim()];}));
}
return validateProfiles(profiles);
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
try{console.log(readProfiles().map(({mode,projectId,marker})=>({mode,projectId,marker})));}
catch(e){console.error(e.message);process.exitCode=1;}
}
===== src/analytics.js =====
import * as amplitude from '@amplitude/unified';
import {resolveEnvironment} from './environment.js';
let ready;
export function initializeAnalytics(){
if(!ready)ready=(async()=>{
const config=resolveEnvironment(import.meta.env.MODE,import.meta.env);
if(config.status==='disabled')return config;
await amplitude.initAll(config.apiKey,{instanceName:'build-env-'+config.mode,serverZone:config.zone,analytics:{autocapture:false,remoteConfig:{fetchRemoteConfig:false}},sessionReplay:{sampleRate:0},engagement:{skip:true}});
return {mode:config.mode,status:'ready',projectId:config.projectId,marker:config.marker,deviceId:amplitude.getDeviceId()};
})().catch(()=>({mode:import.meta.env.MODE,status:'error'}));
return ready;
}
export async function sendEnvironmentCheck(config){
if(config.status!=='ready')return {code:0};
return amplitude.track('Build Environment Check',{app_environment:config.mode,configured_project_id:config.projectId,build_marker:config.marker}).promise;
}
===== src/App.jsx =====
import React,{useState} from 'react';
import {sendEnvironmentCheck} from './analytics.js';
export function App({analytics}){
const [busy,setBusy]=useState(false),[message,setMessage]=useState('Use only the three designated test destinations.');
async function send(){if(busy||analytics.status!=='ready')return;setBusy(true);try{const result=await sendEnvironmentCheck(analytics);setMessage(result.code===200?'HTTP accepted. Verify the destination in Amplitude.':'Upload not accepted.');}catch{setMessage('Upload failed.');}finally{setBusy(false);}}
return <main><h1>Check the analytics environment</h1><p>Each Vite mode builds with its own ingestion key. This UI displays configured labels, not a server-verified project lookup.</p><p>Status: <strong id="status">{analytics.status}</strong></p><p>Mode: <strong id="mode">{analytics.mode}</strong></p><p>Configured project: <code id="project">{analytics.projectId||'unconfigured'}</code></p><p>Marker: <code id="marker">{analytics.marker||'unconfigured'}</code></p><p>Device: <code id="device">{analytics.deviceId||'not initialized'}</code></p><button id="send" disabled={busy||analytics.status!=='ready'} onClick={send}>Send environment check</button><p role="status">{message}</p></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/environment.test.mjs =====
import test from 'node:test';import assert from 'node:assert/strict';
import {mkdtemp,writeFile,rm} from 'node:fs/promises';import {tmpdir} from 'node:os';import {join} from 'node:path';
import {modes,resolveEnvironment,validateProfiles} from '../src/environment.js';import {readProfiles} from '../scripts/check-environments.mjs';
const profiles=()=>Object.fromEntries(modes.map((mode,i)=>[mode,{VITE_APP_ENV:mode,VITE_AMPLITUDE_API_KEY:'fixture-key-'+mode,VITE_AMPLITUDE_PROJECT_ID:String(700001+i),VITE_AMPLITUDE_SERVER_ZONE:'US',VITE_BUILD_MARKER:'build-env-'+mode+'-test'}]));
test('mode/label/region/id validation and disabled mode fail closed',()=>{
const p=profiles();assert.equal(validateProfiles(p).length,3);
assert.deepEqual(resolveEnvironment('development',{}),{mode:'development',status:'disabled'});
assert.throws(()=>resolveEnvironment('preview',{}),/Unknown/);
for(const bad of [{VITE_APP_ENV:'production'},{VITE_AMPLITUDE_SERVER_ZONE:'unknown'},{VITE_AMPLITUDE_PROJECT_ID:'wrong'},{VITE_BUILD_MARKER:'raw-url'},{VITE_AMPLITUDE_API_KEY:'${OTHER_KEY}'}])assert.throws(()=>resolveEnvironment('development',{...p.development,...bad}));
for(const key of ['VITE_AMPLITUDE_API_KEY','VITE_AMPLITUDE_PROJECT_ID','VITE_BUILD_MARKER']){const p=profiles();p.staging[key]=p.development[key];assert.throws(()=>validateProfiles(p),/distinct/);}
});
test('actual mode-file reader rejects missing/reused destinations without printing keys',async()=>{
const dir=await mkdtemp(join(tmpdir(),'env-'));try{
await assert.rejects(async()=>readProfiles(dir));const p=profiles();
for(const mode of modes)await writeFile(join(dir,`.env.${mode}.local`),Object.entries(p[mode]).map(([k,v])=>k+'='+v).join('\n'));
assert.deepEqual(readProfiles(dir).map(x=>x.mode),modes);
assert.throws(()=>readProfiles(dir,{VITE_AMPLITUDE_API_KEY:'global-key-override'}),/global VITE/);
p.staging.VITE_AMPLITUDE_PROJECT_ID=p.development.VITE_AMPLITUDE_PROJECT_ID;
await writeFile(join(dir,'.env.staging.local'),Object.entries(p.staging).map(([k,v])=>k+'='+v).join('\n'));
assert.throws(()=>readProfiles(dir),/distinct projectId/);
}finally{await rm(dir,{recursive:true,force:true});}
});Hand it to your agent
Use this prompt to adapt the example to an existing application.
Use https://amplitude.com/build/vite-analytics-environments 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.
Use explicit Vite modes with all five settings in each reviewed mode file. Guard
mode labels, zones, plain keys and distinct project IDs/keys/markers before
bundling. Reject unreviewed global VITE overrides and variable expansion. Keep
VITE values public and secret keys out of browser builds. Initialize once from
the compiled config, preserve auth/consent, and send an explicit synthetic check.
Verify actual processed destinations and absence from the other designated
projects; labels, mocked requests and local builds do not prove isolation.
Rebuild after changing keys. Use only designated test destinations for fixtures.
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 can keep each environment's event history in its intended project when the build uses the correct key.
Session replay needs its own per-project capture configuration if enabled; this example sets replay0.
Feature flags need their own matching project/deployment configuration. An analytics environment key alone does not establish a flag deployment.
Guides and surveys need their own reviewed project and targeting settings when enabled.
Frequently asked questions
Does adding an environment property separate projects?
No. It labels an event within the project selected by its ingestion key. This recipe uses separate designated project keys and checks the actual destinations.
Can I use NODE_ENV to choose the analytics destination?
Use Vite's explicit mode and reviewed mode-specific settings here. NODE_ENV describes a different concept; an optimized staging build can have NODE_ENV=production.
Does the guard prove a key belongs to the displayed project ID?
No. It validates local structure and distinctness. Verify the actual event marker in each designated project and its absence from the others before relying on the separation.
Next steps
Reference docs
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.