Next.js
Bind authenticated users and AI agents in Next.js 16 Route Handlers and Server Actions with @auditstream/node/next.
On this page
@auditstream/node/next provides withAudit for Route Handlers and auditAction for Server Actions so every awaited Prisma or Drizzle mutation automatically inherits the verified session actor.
Install
pnpm add @auditstream/node
# Plus your ORM adapter (@auditstream/prisma or @auditstream/drizzle)Handlers & Actions
Bind the verified session at the handler or action boundary:
import { withAudit, auditAction } from "@auditstream/node/next";
import { db } from "@/lib/db";
import { getVerifiedSessionActor } from "@/lib/auth";
export const POST = withAudit(
async (request: Request) => {
const body = await request.json();
await db.invoice.update({
where: { id: body.invoiceId },
data: { status: "paid" },
});
return Response.json({ ok: true });
},
{
actor: async () => await getVerifiedSessionActor(),
context: (request) => {
const requestId = request.headers.get("x-request-id");
return requestId && /^[A-Za-z0-9._-]{1,64}$/.test(requestId)
? { requestId, source: "next-route" }
: { source: "next-route" };
},
},
);
export const approveInvoice = auditAction(
async (invoiceId: string) => {
await db.invoice.update({
where: { id: invoiceId },
data: { status: "paid" },
});
},
{ actor: async () => await getVerifiedSessionActor() },
);Validate client headers: Always validate and bound client-supplied headers such as
x-request-id(and opt-inuserAgent) before placing them incontext. Empty, malformed (NUL or unpaired surrogate), or oversized headers can triggerINVALID_CONTEXTor exceed the 512-byte serialized actor+context payload limit (PAYLOAD_TOO_LARGE).
Why not Next.js
proxy?AsyncLocalStoragedoes not propagate across the Next.js 16proxyboundary into Route Handlers or Server Actions. Always bind the verified session insidewithAuditandauditAction.
Exposing audit feeds safely
When rendering an activity log in a Next.js page or API route, never return raw audit.query() or audit.history() rows directly to the client. Raw HistoryEntry objects include internal PostgreSQL metadata (db_user, xact_id, table_oid, actor_source) and full before/after JSONB payloads.
- Enforce authentication and
tenantfiltering on the server. - Project each entry into an explicit allowlisted DTO before serialization.
- Follow the copy-paste Activity Feed (BFF) guide or inspect the full working integration in
examples/next-prisma.