Hono & Express
Attribute PostgreSQL audit trails in Hono and Express apps by binding the request actor once at your HTTP boundary with @auditstream/node.
Auditstream is an open-source database audit trail engine written in Rust. Its CLI generates PostgreSQL triggers that record who changed which row, with before and after values; @auditstream/node is a pure-ESM TypeScript package that binds the request actor (a signed-in user, API key, service, or AI agent) once per request so your database adapter tags downstream SQL with it.
Before you start
Requirements: PostgreSQL 15–19 (the only supported database in v0.1) · ESM-only SDK · Node.js 22.12+, Bun, Deno, or Cloudflare Workers (
nodejs_alsflag or compatibility date>= 2026-08-04).
- Generate and apply the capture migration. Install the
auditstreamCLI, runauditstream initfor the tables you want to audit (use--excludefor secret columns such aspassword_hash), apply the generated migration in a single transaction on a direct (non-pooled) connection (for example Prisma Migrate, Drizzle Kit overpgorpostgres.js, orpsql --single-transaction— not autocommit HTTP runners such as Drizzle’s Neon HTTP migrator), then runauditstream verify.auditstream initonly writes migration files andauditstream.toml; nothing is captured until the migration is applied, andauditstream verifychecks PostgreSQL triggers and schema health (not app-layer attribution). - Install the SDK and your database adapter.
pnpm add @auditstream/node @auditstream/drizzle # or @auditstream/prisma- Wire one database adapter. Middleware only opens the actor scope; the adapter attaches it to each query. Configure Drizzle (
wrapPgPoolfrom@auditstream/drizzle/pg,wrapPostgresJsfrom@auditstream/drizzle/postgres-js,wrapNeonHttpfrom@auditstream/drizzle/neon-http, or Drizzle 1.xauditComment()), Prisma 7.1+ (comments: [auditstream()]), ortagSql()from@auditstream/nodefor plain SQL drivers. Without an adapter, audited writes are still captured, but withactor = NULL. - Register the middleware after authentication. Mount
auditstream()below your authentication middleware on the same routes (shown below) so every downstream write runs inside an isolatedAsyncLocalStorage.run()scope.
Hono
Register @auditstream/node/hono after your authentication middleware on the routes it protects (runs on Node.js, Bun, Deno, and Cloudflare Workers with nodejs_als or compatibility date >= 2026-08-04):
import { Hono } from "hono";
import { jwt } from "hono/jwt";
import { auditstream } from "@auditstream/node/hono";
const app = new Hono();
// 1. Verify authentication first on protected routes
app.use("/api/*", jwt({ secret: process.env.JWT_SECRET!, alg: "HS256" }));
// 2. Bind the verified actor for all downstream database writes
app.use(
"/api/*",
auditstream({
actor: (c) => {
const payload = c.get("jwtPayload");
if (typeof payload !== "object" || payload === null || !("sub" in payload)) {
return undefined;
}
const sub = typeof payload.sub === "string" ? payload.sub.trim() : "";
return sub.length > 0 ? { type: "user", id: sub } : undefined;
},
context: (c) => {
const requestId = c.req.header("x-request-id");
return requestId !== undefined && /^[A-Za-z0-9._-]{1,64}$/.test(requestId)
? { requestId, source: "api" }
: { source: "api" };
},
}),
);- Middleware order matters: Mounting
auditstream()before authentication (or on"*"whilejwt()runs on"/api/*") silently recordsactor = NULLand skipscontext. On strictly authenticated route prefixes, fail closed (for example, thrownew HTTPException(401)) if an expected identity claim is missing. - Opaque IDs only: Ensure
subis an opaque identifier rather than an email address or PII — trailing SQL comments appear inpg_stat_activityand PostgreSQL logs. - Other auth providers &
asyncresolvers: Using Better Auth, Clerk, Supabase, or custom session middleware?actormay beasync(for exampleasync (c) => { ... }) or read any verifiedc.get(...)variable set by upstream middleware. - Full example: See the runnable Hono + Drizzle demo in the SDK monorepo for pool wrapping, migrations, and transaction savepoints (it uses a demo-only
x-demo-userheader for localcurltesting — replace it with verified authentication in production).
Express
Register @auditstream/node/express after your session or JWT middleware populates req.user:
import express, { type Request } from "express";
import { auditstream } from "@auditstream/node/express";
import { authMiddleware } from "./auth";
interface AuthedRequest extends Request {
user?: { id?: string | number };
}
const app = express();
// 1. Verify authentication first
app.use("/api", authMiddleware);
// 2. Bind the verified actor for all downstream database writes
app.use(
"/api",
auditstream({
actor: (req) => {
const rawId = (req as AuthedRequest).user?.id;
const id =
typeof rawId === "number"
? String(rawId)
: typeof rawId === "string"
? rawId.trim()
: "";
return id.length > 0 ? { type: "user", id } : undefined;
},
context: (req) => {
const requestId = req.header("x-request-id");
return requestId !== undefined && /^[A-Za-z0-9._-]{1,64}$/.test(requestId)
? { requestId, source: "api" }
: { source: "api" };
},
}),
);Request context & validation
context is optional and is only invoked when actor returns an Actor.
Validate actor and context values:
actor(id,tenant,onBehalfOf) andcontext(requestId,source, opt-inipanduserAgent) share one 512-byte serialized UTF-8 JSON limit and reject NUL (\u0000) or unpaired UTF-16 surrogates. Violating those rules throwsAuditstreamError(INVALID_ACTOR,INVALID_CONTEXT, orPAYLOAD_TOO_LARGE) and aborts the request with HTTP 500 before route handlers run. Always bound client headers such asx-request-id(and overwrite them at a trusted proxy/gateway if relied on for correlation), and map long federated OIDC/SAMLsubclaims to internal opaque IDs soactor+contextstays well under 512 bytes.
Public & nested scopes
- Returning
undefined: Public or unauthenticated routes stay untagged — PostgreSQL still captures any audited write withactor = NULLanddb_user = session_user. - Overriding inside a request: Calling
audit.as(agentActor, fn)from@auditstream/nodeinside a route handler temporarily replaces the entire outer scope for that callback (for example, attributing an AI tool callonBehalfOfthe signed-in user) and restores the outer request scope automatically when it resolves. Pass{ context: audit.current()?.context }to preserverequestIdandsource, copytenantontoagentActorif needed, and keeponBehalfOfstrictly one level deep.
Verify attribution
After sending an authenticated write request, confirm actor is populated (not NULL) with the CLI — and assert actor IS NOT NULL in your integration tests:
auditstream history --table public.invoice --limit 10