Chris Tam · Last updated 13 November 2026
Product analytics can show where a signup stops when events represent the stages that actually happened. I'll build a local form that creates a real SQLite account with a synthetic username and hashed password, then saves a role. It sends no email and connects to no external identity provider. A second attempt will leave before account creation.
What you'll build
A loopback-only signup fixture with durable Started, Completed and Profile Completed events. The anonymous start and authenticated outcomes share an attempt/device ID. Each stage is queued with its corresponding database operation, then uploaded separately.
Prerequisites
- Node.js 24.14 or later and Corepack for pnpm.
- An existing Amplitude test project, its ingestion API key, and its US or EU data center. Open Organization settings > API Keys and select the test project.
Node24's built-in SQLite API is experimental. Use synthetic credentials and the loopback URL. This teaching fixture omits production authentication features such as TLS, session expiry, recovery and rate limits; keep it local.
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 project
I'll install the Node.js analytics SDK and use pinned versions from the tested example.
mkdir nodejs-signup-funnel
cd nodejs-signup-funnel
mkdir -p src tests
corepack enable{
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"name": "amplitude-nodejs-signup-funnel",
"engines": {
"node": ">=24.14.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"test": "node --test tests/*.test.mjs",
"start": "node --env-file-if-exists=.env.local src/server.js",
"deliver": "node --env-file-if-exists=.env.local src/deliver.js"
},
"dependencies": {
"@amplitude/analytics-node": "1.5.82"
}
}minimumReleaseAge: 10080
trustPolicy: no-downgradenode_modules/
.env.local
data/AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_DB_PATH=data/signup.sqlite
PORT=5194corepack prepare pnpm@10.33.2 --activate
pnpm install
cp .env.example .env.localSet AMPLITUDE_API_KEY to the test-project ingestion key and AMPLITUDE_SERVER_ZONE to US or EU. The project key has the minimum scope needed to ingest data. Keep your local environment file out of source control. These examples never need an Amplitude secret key.
In an existing app, merge these additions into the current SDK entry point and business operations. Preserve authentication, consent, routes and other instrumentation; use the authenticated account ID rather than accepting an arbitrary client-supplied user ID.
2. Commit each funnel stage with its operation
I'll store the attempt, account and profile in SQLite. A stage event enters the outbox in the same transaction as its operation. Its original timestamp and random insert ID persist for delivery retries.
import { DatabaseSync } from 'node:sqlite';
import { randomUUID, scryptSync, randomBytes } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export function openStore(path) {
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path, { timeout: 5000 });
db.exec(`PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS attempts(id TEXT PRIMARY KEY, user_id TEXT, session TEXT, exited INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS users(id TEXT PRIMARY KEY, username TEXT UNIQUE, password_hash TEXT, role TEXT);
CREATE TABLE IF NOT EXISTS outbox(event_key TEXT PRIMARY KEY, body TEXT NOT NULL, sent INTEGER DEFAULT 0);`);
return db;
}
function enqueue(db, id, type, userId) {
const key = id + ':' + type;
const event = { event_type: type, device_id: id, ...(userId ? { user_id: userId } : {}),
insert_id: randomUUID(), time: Date.now(), event_properties: { attempt_id: id, funnel: 'local_signup_v1' } };
db.prepare('INSERT OR IGNORE INTO outbox(event_key,body) VALUES (?,?)').run(key,JSON.stringify(event));
}
export function start(db, prior) {
const old = prior && db.prepare('SELECT * FROM attempts WHERE id=?').get(prior);
if (old && !old.exited) return old.id;
const id = 'build-signup-' + randomUUID();
db.exec('BEGIN IMMEDIATE');
try { db.prepare('INSERT INTO attempts(id) VALUES (?)').run(id);enqueue(db,id,'Signup Started');db.exec('COMMIT');return id; }
catch(e) { db.exec('ROLLBACK');throw e; }
}
export function register(db, id, username, password) {
if (typeof username !== 'string' || !/^demo_[a-z0-9_]{3,40}$/.test(username) || typeof password !== 'string' || password.length < 12 || password.length > 128) throw Error('Use a demo_ username and a 12-128 character synthetic password.');
const salt=randomBytes(16).toString('hex');const hash=salt+':'+scryptSync(password,salt,32).toString('hex');
db.exec('BEGIN IMMEDIATE');
try {
const attempt=db.prepare('SELECT * FROM attempts WHERE id=?').get(id);
if (!attempt || attempt.exited) throw Error('Start a fresh attempt.');
if (attempt.user_id) { db.exec('COMMIT'); return { userId:attempt.user_id, session:attempt.session }; }
const userId='build-signup-user-'+randomUUID(), session=randomBytes(32).toString('hex');
db.prepare('INSERT INTO users(id,username,password_hash) VALUES (?,?,?)').run(userId,username,hash);
db.prepare('UPDATE attempts SET user_id=?,session=? WHERE id=?').run(userId,session,id);
enqueue(db,id,'Signup Completed',userId);db.exec('COMMIT');return {userId,session};
} catch(e) { db.exec('ROLLBACK');throw e; }
}
export function saveProfile(db,id,session,role) {
if (!['developer','analyst'].includes(role)) throw Error('Choose a listed role.');
db.exec('BEGIN IMMEDIATE');
try {
const a=db.prepare('SELECT * FROM attempts WHERE id=? AND session=?').get(id,session);
if (!session || !a?.user_id) throw Error('Create the local account first.');
db.prepare('UPDATE users SET role=? WHERE id=?').run(role,a.user_id);
enqueue(db,id,'Signup Profile Completed',a.user_id);db.exec('COMMIT');return {userId:a.user_id};
} catch(e) { db.exec('ROLLBACK');throw e; }
}
export function leave(db,id) {
db.exec('BEGIN IMMEDIATE');
try {const a=db.prepare('SELECT * FROM attempts WHERE id=?').get(id);if(!a||a.user_id)throw Error('Only an incomplete attempt can exit.');
db.prepare('UPDATE attempts SET exited=1 WHERE id=?').run(id);enqueue(db,id,'Signup Exited');db.exec('COMMIT');
}catch(e){db.exec('ROLLBACK');throw e;}
}
export async function deliver(db,send) {
const results=[];
for(const row of db.prepare('SELECT event_key,body FROM outbox WHERE sent=0 ORDER BY rowid').all()) {
const event=JSON.parse(row.body);
if(Date.now()-event.time>=7*86400000)throw Error('Outbox exceeds deduplication window; reconcile before replay.');
const code=await send(event);
if(code!==200){results.push({event_type:event.event_type,code});break;}
db.prepare('UPDATE outbox SET sent=1 WHERE event_key=?').run(row.event_key);
results.push({event_type:event.event_type,code});
}
return results;
}The Started event has a stable attempt/device ID and no invented user ID. Completed and Profile Completed add the account's server-generated user ID while retaining that device ID. This joins the anonymous and known path. attempt_id appears on every stage so a later attempt can't accidentally complete an earlier one.
A repeated account request for the same attempt returns the committed account; it doesn't insert another user or stage. Profile changes update local state while the unique attempt/stage key keeps its first completion event. A username collision or invalid input rolls back without a Completed event. Raw usernames, passwords and role values are not in telemetry.
Why. A submit click can fail validation or a database constraint. Emit a completion where the operation commits. The outbox is at-least-once; stable device/insert IDs support Amplitude's seven-day deduplication window, and older pending rows stop for reconciliation.
3. Serve the local form and keep session identity on the backend
I'll bind to 127.0.0.1 and require the expected Host and same-origin JSON requests. The server owns the attempt and account session cookies; the browser doesn't supply the authenticated user ID.
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import { openStore, start, register, saveProfile, leave } from './store.js';
export function createApp(db, port) {
const origin = `http://127.0.0.1:${port}`;
return createServer(async (req,res) => {
const json=(code,data)=>{res.writeHead(code,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify(data));};
if(req.headers.host!==`127.0.0.1:${port}`)return json(403,{error:'Use the loopback URL.'});
if(req.method==='GET'&&req.url==='/'){res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'});return res.end(await readFile(new URL('../public/index.html',import.meta.url)));}
if(req.method!=='POST'||req.headers.origin!==origin||req.headers['content-type']!=='application/json')return json(403,{error:'Same-origin JSON required.'});
try {
let raw='';for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>4096)return json(413,{error:'Request too large.'});}
const body=JSON.parse(raw);const cookies=Object.fromEntries((req.headers.cookie||'').split(';').filter(x=>x.includes('=')).map(x=>x.trim().split('=')));
const id=cookies.build_signup_attempt;
if(req.url==='/api/new'){res.setHeader('set-cookie',['build_signup_attempt=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/','build_signup_session=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/']);return json(200,{reset:true});}
if(req.url==='/api/start') {const attempt=start(db,id);res.setHeader('set-cookie',`build_signup_attempt=${attempt}; HttpOnly; SameSite=Strict; Path=/`);return json(200,{attempt});}
if(req.url==='/api/signup') {const account=register(db,id,body.username,body.password);res.setHeader('set-cookie',`build_signup_session=${account.session}; HttpOnly; SameSite=Strict; Path=/`);return json(201,{userId:account.userId});}
if(req.url==='/api/profile')return json(200,saveProfile(db,id,cookies.build_signup_session,body.role));
if(req.url==='/api/leave'){leave(db,id);return json(200,{exited:true});}
return json(404,{error:'Unknown route.'});
}catch{return json(400,{error:'Operation failed. Check synthetic inputs or choose a unique username.'});}
});
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
const port=Number(process.env.PORT||5194);const db=openStore(process.env.BUILD_DB_PATH||'data/signup.sqlite');
const server=createApp(db,port);server.listen(port,'127.0.0.1',()=>console.log(`Open http://127.0.0.1:${port}`));
for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>server.close(()=>db.close()));
}<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Local signup funnel</title>
<style>body{font:18px Arial,sans-serif;background:#F2F4F8;color:#000;margin:40px auto;max-width:700px;padding:24px}main{background:#fff;padding:32px;border-radius:16px}label{display:block;margin:16px 0 8px}button,input,select{font:inherit;padding:10px;margin:8px 8px 8px 0}button{cursor:pointer}code{overflow-wrap:anywhere}:focus-visible{outline:3px solid #0052F2}</style></head><body><main>
<h1>Create a local demo account</h1><p>This fixture stores an account and profile in local SQLite. It sends no email and connects to no external identity service. Use synthetic credentials only.</p>
<button id="start">Start signup</button>
<form id="signup" hidden><label for="username">Synthetic username</label><input id="username" autocomplete="off" required pattern="demo_[a-z0-9_]{3,40}" placeholder="demo_example">
<label for="password">Synthetic password</label><input id="password" type="password" autocomplete="off" required minlength="12" maxlength="128"><button>Create local account</button><button id="leave" type="button">Leave signup</button></form>
<form id="profile" hidden><label for="role">Demo role</label><select id="role"><option value="developer">Developer</option><option value="analyst">Analyst</option></select><button>Save profile</button></form>
<p role="status" id="status">Start a new attempt.</p><p>Attempt: <code id="attempt"></code></p><p>User: <code id="user"></code></p><button id="new">New attempt (reload)</button>
</main><script type="module">
const $=id=>document.getElementById(id);let busy=false;
async function action(fn){if(busy)return;busy=true;for(const b of document.querySelectorAll('button'))b.disabled=true;try{await fn();}catch(e){$('status').textContent=e.message;}finally{busy=false;for(const b of document.querySelectorAll('button'))b.disabled=false;}}
async function post(path,body={}){const res=await fetch('/api/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});const result=await res.json();if(!res.ok)throw Error(result.error);return result;}
$('start').onclick=()=>action(async()=>{const r=await post('start');$('attempt').textContent=r.attempt;$('signup').hidden=false;$('start').hidden=true;$('status').textContent='Started. Enter synthetic credentials.';});
$('signup').onsubmit=e=>{e.preventDefault();void action(async()=>{const r=await post('signup',{username:$('username').value,password:$('password').value});$('password').value='';$('user').textContent=r.userId;$('signup').hidden=true;$('profile').hidden=false;$('status').textContent='Local account committed. Save a profile next.';});};
$('profile').onsubmit=e=>{e.preventDefault();void action(async()=>{await post('profile',{role:$('role').value});$('profile').hidden=true;$('status').textContent='Profile committed.';});};
$('leave').onclick=()=>action(async()=>{await post('leave');$('signup').hidden=true;$('status').textContent='Exited without an account.';});
$('new').onclick=()=>action(async()=>{await post('new');location.reload();});
</script></body></html>The New attempt control clears the fixture's HttpOnly cookies through a server endpoint. It doesn't delete accounts or past analytics. Leave signup commits an explicit exit for an incomplete attempt; it doesn't detect every tab closure.
This is a local account-creation fixture, not a production auth template. Passwords are salted and hashed, but the example has no expiry, recovery, rate limiting, email verification or hosted deployment. Its synchronous password hashing and SQLite operations are chosen for a small local demonstration.
4. Deliver queued stages in order
I'll initialize the SDK once for the delivery command, flush each pending event, then inspect its result code. Delivery stops at the first non200 so later stages aren't deliberately advanced past a failed earlier one.
export async function createSender(env = process.env) {
if (!env.AMPLITUDE_API_KEY?.trim()) return null;
const { createInstance } = await import('@amplitude/analytics-node');
const client = createInstance();
await client.init(env.AMPLITUDE_API_KEY.trim(), {
serverZone: env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
flushIntervalMillis: 1000, flushQueueSize: 100,
flushMaxRetries: 0, requestTimeoutMillis: 5000,
}).promise;
return async (event) => {
const queued = client.track(event);
await client.flush().promise;
return (await queued.promise).code;
};
}import { openStore, deliver } from './store.js';
import { createSender } from './analytics.js';
const db=openStore(process.env.BUILD_DB_PATH||'data/signup.sqlite');
try { const send=await createSender();console.log(send?await deliver(db,send):{analytics:'disabled',pending:db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE sent=0').get().n}); }
catch(e){console.error(e.message);process.exitCode=1;}finally{db.close();}The app commits the account even when analytics is unavailable. Blank-key mode imports no SDK and leaves rows pending. The delivery command uses explicit queue, timeout and retry settings; flush completion alone isn't proof of durable ingestion. Check processed data separately.
Running multiple delivery workers and recovering from long outages need a production policy. This fixture demonstrates one ordered sender and stable event identities, not a general job system.
5. Test and run the example
The HTTP test exercises origin protection, invalid input, idempotent requests, a real account/profile commit, a rejected duplicate username, partial exit and ordered delivery retry. The browser test below covers the visible completed and partial paths.
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp,rm } from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {openStore,deliver} from '../src/store.js';
import {createApp} from '../src/server.js';
test('real HTTP signup commits account/profile; duplicate submit and failed operations do not add stages',async()=>{
const dir=await mkdtemp(join(tmpdir(),'signup-'));const db=openStore(join(dir,'db.sqlite'));const port=5195;const app=createApp(db,port);await new Promise(r=>app.listen(port,'127.0.0.1',r));
let cookies='';const origin=`http://127.0.0.1:${port}`;
const post=async(path,body={},withOrigin=true)=>{const res=await fetch(origin+'/api/'+path,{method:'POST',headers:{'content-type':'application/json',...(withOrigin?{origin}:{}),cookie:cookies},body:JSON.stringify(body)});const incoming=res.headers.getSetCookie().map(x=>x.split(';')[0]);if(incoming.length)cookies=[...new Map([...cookies.split('; ').filter(Boolean),...incoming].map(x=>x.split('='))).entries()].map(x=>x.join('=')).join('; ');return {status:res.status,data:await res.json()};};
try{
assert.equal((await post('start',{},false)).status,403);
const started=await post('start');assert.equal(started.status,200);const id=started.data.attempt;
assert.equal((await post('start')).data.attempt,id);
assert.equal((await post('profile',{role:'developer'})).status,400);
assert.equal((await post('signup',{username:'bad',password:'short'})).status,400);
const account=await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'});assert.equal(account.status,201);
assert.equal((await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'})).data.userId,account.data.userId);
assert.equal((await post('profile',{role:'analyst'})).status,200);
assert.equal((await post('profile',{role:'developer'})).status,200);
const rows=db.prepare('SELECT body FROM outbox ORDER BY rowid').all().map(x=>JSON.parse(x.body));
assert.deepEqual(rows.map(x=>x.event_type),['Signup Started','Signup Completed','Signup Profile Completed']);
assert.ok(rows.every(x=>x.device_id===id&&x.event_properties.attempt_id===id));
assert.equal(rows[0].user_id,undefined);assert.equal(rows[1].user_id,account.data.userId);
assert.ok(!JSON.stringify(rows).includes('PRIVATE_SIGNUP_FIXTURE'));assert.ok(!JSON.stringify(rows).includes('demo_test_fixture'));
assert.equal(db.prepare('SELECT role FROM users').get().role,'developer');
await post('new');await post('start');assert.equal((await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'})).status,400);await post('leave');
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM users').get().n,1);
assert.deepEqual(db.prepare('SELECT body FROM outbox ORDER BY rowid').all().slice(3).map(x=>JSON.parse(x.body).event_type),['Signup Started','Signup Exited']);
let calls=0;await deliver(db,async()=>{calls++;return 500});assert.equal(calls,1);
const replay=[];await deliver(db,async e=>{replay.push(e);return 200});assert.equal(replay.length,5);
assert.deepEqual(replay.slice(0,3),rows);
}finally{await new Promise(r=>app.close(r));db.close();await rm(dir,{recursive:true,force:true});}
});pnpm test
pnpm start
# In another terminal, after exercising the form:
pnpm deliver6. Build the three-step funnel
I'll use the Funnel Analysis setup to compare the processed stages. Create a Funnel Analysis chart in the test project and select Signup Started, Signup Completed, then Signup Profile Completed. Choose This order and a one-hour conversion window for this local run.
Filter each stage's attempt_id to the two IDs displayed during your test. Hold `attempt_id` constant across the steps. The property is on every event. This counts user/attempt pairs rather than simply deduplicating a person who tries more than once.
The expected fixture result is two starts, one account completion and one profile completion:50% from start to final stage. Signup Exited is diagnostic context, not a required funnel step. In production, choose a completion window suited to your flow before interpreting drop-off.
Verify it worked
Use a unique demo_ username and synthetic password for the completed attempt. Keep both displayed attempt IDs.
- Completed browser path: Open
http://127.0.0.1:5194. Start signup, create the local account with a 12+ character synthetic password, and save the role. Note the attempt and user IDs. The UI confirms the account and profile commits. - Partial path: Choose New attempt, start signup, enter synthetic values, then Leave signup before creating an account. Note the different attempt ID. Run
pnpm deliver; expect five accepted events across both paths:three completion-path stages and a partial Started/Exited pair. - Payload check: Inspect the complete event bodies and processed raw metadata. Usernames and
PRIVATE_SIGNUP_FIXTURE_20261113passwords must not appear. Only the stable attempt ID and fixed funnel name belong in event_properties. The backend account/password data remains in local SQLite. - Processed funnel: Allow ten seconds to one minute for Activity. Confirm the completed path shares its device/attempt ID, gains the account user ID on completion, and contains all three stages. The partial device has Started/Exited without Completed. Build the filtered funnel as above and verify 2, 1, 1 counts.
- Failures and blank key: Run the HTTP test for invalid and duplicate submissions, absent session, origin rejection and delivery failure. With a blank key, account creation still works and delivery reports pending rows; adding the test key later sends the saved stages.
Troubleshooting
The funnel combines different signup attempts
Put attempt_id on every stage and hold it constant. A person may try more than once; unique-user counts alone do not distinguish those attempts.
Account creation succeeded but analytics has no completion
Business state commits before upload. Run deliver with the correct test-project key and inspect its codes. A non200 stops that sender with rows preserved. Check the original device/insert IDs before retrying.
A duplicate username fails signup
Use a new synthetic demo_ username. The unique constraint rejects a new attempt using an existing name; no account completion event is queued for the failed attempt.
Reload does not begin a fresh attempt
Choose New attempt to clear the fixture cookies through the server. It retains saved account rows; use a fresh synthetic username as well.
The request is rejected on localhost
Use 127.0.0.1:5194 exactly. The teaching server validates Host, Origin and JSON content type; localhost is a different origin.
Full code reference
The complete runnable example includes the lockfile. These are the complete setup, application and test files.
===== package.json =====
{
"version": "1.0.0",
"private": true,
"type": "module",
"packageManager": "pnpm@10.33.2+sha512.a90faf6feeab71ad6c6e57f94e0fe1a12f5dcc22cd754db40ae9593eb6a3e0b6b12e3540218bb37ae083404b1f2ce6db2a4121e979829b4aff94b99f49da1cf8",
"name": "amplitude-nodejs-signup-funnel",
"engines": {
"node": ">=24.14.0",
"pnpm": ">=10.21.0"
},
"scripts": {
"test": "node --test tests/*.test.mjs",
"start": "node --env-file-if-exists=.env.local src/server.js",
"deliver": "node --env-file-if-exists=.env.local src/deliver.js"
},
"dependencies": {
"@amplitude/analytics-node": "1.5.82"
}
}
===== pnpm-workspace.yaml =====
minimumReleaseAge: 10080
trustPolicy: no-downgrade
===== .gitignore =====
node_modules/
.env.local
data/
===== .env.example =====
AMPLITUDE_API_KEY=
AMPLITUDE_SERVER_ZONE=US
BUILD_DB_PATH=data/signup.sqlite
PORT=5194
===== src/store.js =====
import { DatabaseSync } from 'node:sqlite';
import { randomUUID, scryptSync, randomBytes } from 'node:crypto';
import { mkdirSync } from 'node:fs';
import { dirname } from 'node:path';
export function openStore(path) {
mkdirSync(dirname(path), { recursive: true });
const db = new DatabaseSync(path, { timeout: 5000 });
db.exec(`PRAGMA journal_mode=WAL;
CREATE TABLE IF NOT EXISTS attempts(id TEXT PRIMARY KEY, user_id TEXT, session TEXT, exited INTEGER DEFAULT 0);
CREATE TABLE IF NOT EXISTS users(id TEXT PRIMARY KEY, username TEXT UNIQUE, password_hash TEXT, role TEXT);
CREATE TABLE IF NOT EXISTS outbox(event_key TEXT PRIMARY KEY, body TEXT NOT NULL, sent INTEGER DEFAULT 0);`);
return db;
}
function enqueue(db, id, type, userId) {
const key = id + ':' + type;
const event = { event_type: type, device_id: id, ...(userId ? { user_id: userId } : {}),
insert_id: randomUUID(), time: Date.now(), event_properties: { attempt_id: id, funnel: 'local_signup_v1' } };
db.prepare('INSERT OR IGNORE INTO outbox(event_key,body) VALUES (?,?)').run(key,JSON.stringify(event));
}
export function start(db, prior) {
const old = prior && db.prepare('SELECT * FROM attempts WHERE id=?').get(prior);
if (old && !old.exited) return old.id;
const id = 'build-signup-' + randomUUID();
db.exec('BEGIN IMMEDIATE');
try { db.prepare('INSERT INTO attempts(id) VALUES (?)').run(id);enqueue(db,id,'Signup Started');db.exec('COMMIT');return id; }
catch(e) { db.exec('ROLLBACK');throw e; }
}
export function register(db, id, username, password) {
if (typeof username !== 'string' || !/^demo_[a-z0-9_]{3,40}$/.test(username) || typeof password !== 'string' || password.length < 12 || password.length > 128) throw Error('Use a demo_ username and a 12-128 character synthetic password.');
const salt=randomBytes(16).toString('hex');const hash=salt+':'+scryptSync(password,salt,32).toString('hex');
db.exec('BEGIN IMMEDIATE');
try {
const attempt=db.prepare('SELECT * FROM attempts WHERE id=?').get(id);
if (!attempt || attempt.exited) throw Error('Start a fresh attempt.');
if (attempt.user_id) { db.exec('COMMIT'); return { userId:attempt.user_id, session:attempt.session }; }
const userId='build-signup-user-'+randomUUID(), session=randomBytes(32).toString('hex');
db.prepare('INSERT INTO users(id,username,password_hash) VALUES (?,?,?)').run(userId,username,hash);
db.prepare('UPDATE attempts SET user_id=?,session=? WHERE id=?').run(userId,session,id);
enqueue(db,id,'Signup Completed',userId);db.exec('COMMIT');return {userId,session};
} catch(e) { db.exec('ROLLBACK');throw e; }
}
export function saveProfile(db,id,session,role) {
if (!['developer','analyst'].includes(role)) throw Error('Choose a listed role.');
db.exec('BEGIN IMMEDIATE');
try {
const a=db.prepare('SELECT * FROM attempts WHERE id=? AND session=?').get(id,session);
if (!session || !a?.user_id) throw Error('Create the local account first.');
db.prepare('UPDATE users SET role=? WHERE id=?').run(role,a.user_id);
enqueue(db,id,'Signup Profile Completed',a.user_id);db.exec('COMMIT');return {userId:a.user_id};
} catch(e) { db.exec('ROLLBACK');throw e; }
}
export function leave(db,id) {
db.exec('BEGIN IMMEDIATE');
try {const a=db.prepare('SELECT * FROM attempts WHERE id=?').get(id);if(!a||a.user_id)throw Error('Only an incomplete attempt can exit.');
db.prepare('UPDATE attempts SET exited=1 WHERE id=?').run(id);enqueue(db,id,'Signup Exited');db.exec('COMMIT');
}catch(e){db.exec('ROLLBACK');throw e;}
}
export async function deliver(db,send) {
const results=[];
for(const row of db.prepare('SELECT event_key,body FROM outbox WHERE sent=0 ORDER BY rowid').all()) {
const event=JSON.parse(row.body);
if(Date.now()-event.time>=7*86400000)throw Error('Outbox exceeds deduplication window; reconcile before replay.');
const code=await send(event);
if(code!==200){results.push({event_type:event.event_type,code});break;}
db.prepare('UPDATE outbox SET sent=1 WHERE event_key=?').run(row.event_key);
results.push({event_type:event.event_type,code});
}
return results;
}
===== src/server.js =====
import { createServer } from 'node:http';
import { readFile } from 'node:fs/promises';
import { pathToFileURL } from 'node:url';
import { openStore, start, register, saveProfile, leave } from './store.js';
export function createApp(db, port) {
const origin = `http://127.0.0.1:${port}`;
return createServer(async (req,res) => {
const json=(code,data)=>{res.writeHead(code,{'content-type':'application/json','cache-control':'no-store'});res.end(JSON.stringify(data));};
if(req.headers.host!==`127.0.0.1:${port}`)return json(403,{error:'Use the loopback URL.'});
if(req.method==='GET'&&req.url==='/'){res.writeHead(200,{'content-type':'text/html; charset=utf-8','cache-control':'no-store'});return res.end(await readFile(new URL('../public/index.html',import.meta.url)));}
if(req.method!=='POST'||req.headers.origin!==origin||req.headers['content-type']!=='application/json')return json(403,{error:'Same-origin JSON required.'});
try {
let raw='';for await(const chunk of req){raw+=chunk;if(Buffer.byteLength(raw)>4096)return json(413,{error:'Request too large.'});}
const body=JSON.parse(raw);const cookies=Object.fromEntries((req.headers.cookie||'').split(';').filter(x=>x.includes('=')).map(x=>x.trim().split('=')));
const id=cookies.build_signup_attempt;
if(req.url==='/api/new'){res.setHeader('set-cookie',['build_signup_attempt=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/','build_signup_session=; Max-Age=0; HttpOnly; SameSite=Strict; Path=/']);return json(200,{reset:true});}
if(req.url==='/api/start') {const attempt=start(db,id);res.setHeader('set-cookie',`build_signup_attempt=${attempt}; HttpOnly; SameSite=Strict; Path=/`);return json(200,{attempt});}
if(req.url==='/api/signup') {const account=register(db,id,body.username,body.password);res.setHeader('set-cookie',`build_signup_session=${account.session}; HttpOnly; SameSite=Strict; Path=/`);return json(201,{userId:account.userId});}
if(req.url==='/api/profile')return json(200,saveProfile(db,id,cookies.build_signup_session,body.role));
if(req.url==='/api/leave'){leave(db,id);return json(200,{exited:true});}
return json(404,{error:'Unknown route.'});
}catch{return json(400,{error:'Operation failed. Check synthetic inputs or choose a unique username.'});}
});
}
if(process.argv[1]&&import.meta.url===pathToFileURL(process.argv[1]).href){
const port=Number(process.env.PORT||5194);const db=openStore(process.env.BUILD_DB_PATH||'data/signup.sqlite');
const server=createApp(db,port);server.listen(port,'127.0.0.1',()=>console.log(`Open http://127.0.0.1:${port}`));
for(const signal of ['SIGINT','SIGTERM'])process.on(signal,()=>server.close(()=>db.close()));
}
===== public/index.html =====
<!doctype html>
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>Local signup funnel</title>
<style>body{font:18px Arial,sans-serif;background:#F2F4F8;color:#000;margin:40px auto;max-width:700px;padding:24px}main{background:#fff;padding:32px;border-radius:16px}label{display:block;margin:16px 0 8px}button,input,select{font:inherit;padding:10px;margin:8px 8px 8px 0}button{cursor:pointer}code{overflow-wrap:anywhere}:focus-visible{outline:3px solid #0052F2}</style></head><body><main>
<h1>Create a local demo account</h1><p>This fixture stores an account and profile in local SQLite. It sends no email and connects to no external identity service. Use synthetic credentials only.</p>
<button id="start">Start signup</button>
<form id="signup" hidden><label for="username">Synthetic username</label><input id="username" autocomplete="off" required pattern="demo_[a-z0-9_]{3,40}" placeholder="demo_example">
<label for="password">Synthetic password</label><input id="password" type="password" autocomplete="off" required minlength="12" maxlength="128"><button>Create local account</button><button id="leave" type="button">Leave signup</button></form>
<form id="profile" hidden><label for="role">Demo role</label><select id="role"><option value="developer">Developer</option><option value="analyst">Analyst</option></select><button>Save profile</button></form>
<p role="status" id="status">Start a new attempt.</p><p>Attempt: <code id="attempt"></code></p><p>User: <code id="user"></code></p><button id="new">New attempt (reload)</button>
</main><script type="module">
const $=id=>document.getElementById(id);let busy=false;
async function action(fn){if(busy)return;busy=true;for(const b of document.querySelectorAll('button'))b.disabled=true;try{await fn();}catch(e){$('status').textContent=e.message;}finally{busy=false;for(const b of document.querySelectorAll('button'))b.disabled=false;}}
async function post(path,body={}){const res=await fetch('/api/'+path,{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(body)});const result=await res.json();if(!res.ok)throw Error(result.error);return result;}
$('start').onclick=()=>action(async()=>{const r=await post('start');$('attempt').textContent=r.attempt;$('signup').hidden=false;$('start').hidden=true;$('status').textContent='Started. Enter synthetic credentials.';});
$('signup').onsubmit=e=>{e.preventDefault();void action(async()=>{const r=await post('signup',{username:$('username').value,password:$('password').value});$('password').value='';$('user').textContent=r.userId;$('signup').hidden=true;$('profile').hidden=false;$('status').textContent='Local account committed. Save a profile next.';});};
$('profile').onsubmit=e=>{e.preventDefault();void action(async()=>{await post('profile',{role:$('role').value});$('profile').hidden=true;$('status').textContent='Profile committed.';});};
$('leave').onclick=()=>action(async()=>{await post('leave');$('signup').hidden=true;$('status').textContent='Exited without an account.';});
$('new').onclick=()=>action(async()=>{await post('new');location.reload();});
</script></body></html>
===== src/analytics.js =====
export async function createSender(env = process.env) {
if (!env.AMPLITUDE_API_KEY?.trim()) return null;
const { createInstance } = await import('@amplitude/analytics-node');
const client = createInstance();
await client.init(env.AMPLITUDE_API_KEY.trim(), {
serverZone: env.AMPLITUDE_SERVER_ZONE === 'EU' ? 'EU' : 'US',
flushIntervalMillis: 1000, flushQueueSize: 100,
flushMaxRetries: 0, requestTimeoutMillis: 5000,
}).promise;
return async (event) => {
const queued = client.track(event);
await client.flush().promise;
return (await queued.promise).code;
};
}
===== src/deliver.js =====
import { openStore, deliver } from './store.js';
import { createSender } from './analytics.js';
const db=openStore(process.env.BUILD_DB_PATH||'data/signup.sqlite');
try { const send=await createSender();console.log(send?await deliver(db,send):{analytics:'disabled',pending:db.prepare('SELECT COUNT(*) AS n FROM outbox WHERE sent=0').get().n}); }
catch(e){console.error(e.message);process.exitCode=1;}finally{db.close();}
===== tests/signup.test.mjs =====
import test from 'node:test';
import assert from 'node:assert/strict';
import { mkdtemp,rm } from 'node:fs/promises';
import {tmpdir} from 'node:os';
import {join} from 'node:path';
import {openStore,deliver} from '../src/store.js';
import {createApp} from '../src/server.js';
test('real HTTP signup commits account/profile; duplicate submit and failed operations do not add stages',async()=>{
const dir=await mkdtemp(join(tmpdir(),'signup-'));const db=openStore(join(dir,'db.sqlite'));const port=5195;const app=createApp(db,port);await new Promise(r=>app.listen(port,'127.0.0.1',r));
let cookies='';const origin=`http://127.0.0.1:${port}`;
const post=async(path,body={},withOrigin=true)=>{const res=await fetch(origin+'/api/'+path,{method:'POST',headers:{'content-type':'application/json',...(withOrigin?{origin}:{}),cookie:cookies},body:JSON.stringify(body)});const incoming=res.headers.getSetCookie().map(x=>x.split(';')[0]);if(incoming.length)cookies=[...new Map([...cookies.split('; ').filter(Boolean),...incoming].map(x=>x.split('='))).entries()].map(x=>x.join('=')).join('; ');return {status:res.status,data:await res.json()};};
try{
assert.equal((await post('start',{},false)).status,403);
const started=await post('start');assert.equal(started.status,200);const id=started.data.attempt;
assert.equal((await post('start')).data.attempt,id);
assert.equal((await post('profile',{role:'developer'})).status,400);
assert.equal((await post('signup',{username:'bad',password:'short'})).status,400);
const account=await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'});assert.equal(account.status,201);
assert.equal((await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'})).data.userId,account.data.userId);
assert.equal((await post('profile',{role:'analyst'})).status,200);
assert.equal((await post('profile',{role:'developer'})).status,200);
const rows=db.prepare('SELECT body FROM outbox ORDER BY rowid').all().map(x=>JSON.parse(x.body));
assert.deepEqual(rows.map(x=>x.event_type),['Signup Started','Signup Completed','Signup Profile Completed']);
assert.ok(rows.every(x=>x.device_id===id&&x.event_properties.attempt_id===id));
assert.equal(rows[0].user_id,undefined);assert.equal(rows[1].user_id,account.data.userId);
assert.ok(!JSON.stringify(rows).includes('PRIVATE_SIGNUP_FIXTURE'));assert.ok(!JSON.stringify(rows).includes('demo_test_fixture'));
assert.equal(db.prepare('SELECT role FROM users').get().role,'developer');
await post('new');await post('start');assert.equal((await post('signup',{username:'demo_test_fixture',password:'PRIVATE_SIGNUP_FIXTURE'})).status,400);await post('leave');
assert.equal(db.prepare('SELECT COUNT(*) AS n FROM users').get().n,1);
assert.deepEqual(db.prepare('SELECT body FROM outbox ORDER BY rowid').all().slice(3).map(x=>JSON.parse(x.body).event_type),['Signup Started','Signup Exited']);
let calls=0;await deliver(db,async()=>{calls++;return 500});assert.equal(calls,1);
const replay=[];await deliver(db,async e=>{replay.push(e);return 200});assert.equal(replay.length,5);
assert.deepEqual(replay.slice(0,3),rows);
}finally{await new Promise(r=>app.close(r));db.close();await rm(dir,{recursive:true,force:true});}
});Hand it to your agent
Use https://amplitude.com/build/nodejs-signup-funnel and its linked source.
Inspect the existing application and SDK entry point first. Preserve auth, consent,
and other instrumentation. Read the installed SDK's current docs through Docs MCP.
Use real backend account/profile commits as completion boundaries. Preserve a
stable device/attempt ID from anonymous start to known user stages. Queue each
stage atomically with its business write; keep raw credentials out of telemetry.
Make repeated submissions idempotent, retain stable event IDs on delivery retry,
and hold attempt_id constant in the ordered funnel. Preserve existing auth; do
not deploy the local teaching authentication fixture as production infrastructure.
Run local failure and success checks. Verify real HTTP acceptance and processed
history separately. Keep environment secrets and synthetic fixture data local.
Report changed files and remaining coverage limits.MCP. The Docs MCP server reads public documentation. It cannot inspect this project's events or run the application for you.
What this unlocks
Product analytics can distinguish starting signup, creating an account and completing the profile.
Session replay can add browser context only through a separately configured client with reviewed masking; this fixture has no replay SDK.
Feature flags can vary a later signup flow while these committed outcomes remain its metrics.
Guides and surveys can support users during onboarding through a separately configured browser integration.
Frequently asked questions
Does Signup Completed mean an email was verified?
No. It means the local SQLite account was committed. There is no email service or email verification stage in this example.
Why keep the attempt ID after a user ID exists?
The stable user ID identifies the account; the attempt ID identifies this signup path. Holding it constant prevents stages from different attempts satisfying one conversion.
Can I publish this local authentication server?
The example is a loopback teaching fixture with synthetic credentials. Merge the analytics boundaries into your existing authenticated application; its production security and session lifecycle remain your application's responsibility.
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.