Prisma
Section titled “Prisma”View the integration on GitHub
PgStack Audit plugs into Prisma and PostgreSQL to track database changes automatically. It supports audit trails with application context and historical queries in your application.
This package passes application-specific context with database changes through the Prisma integration. Context can include the 'where' (API endpoint, worker, etc.), 'who' (user, cron job, etc.), and 'how' behind a change.
Prerequisites
Section titled “Prerequisites”- PostgreSQL 14+
- Prisma
Installation
Section titled “Installation”- Install the NPM package
npm install @bemi-db/prisma- Generate a Prisma migration file to add lightweight PostgreSQL triggers for passing application context with all data changes into PostgreSQL replication log
npx bemi migration:create- Run the Prisma migration
npx prisma migrate devEnable the new Prisma driver adapters to use a native PostgreSQL client for Node.js by adding the following:
generator client { previewFeatures = ["driverAdapters"] ...}Enable PostgreSQL adapter for your Prisma client by using withBemiExtension:
import { PrismaPg, withBemiExtension } from "@bemi-db/prisma";import { PrismaClient } from '@prisma/client';
const adapter = PrismaPg({ connectionString: process.env.DATABASE_URL });const prisma = withBemiExtension(new PrismaClient({ adapter }));Now you can specify custom application context that will be automatically passed with all data changes by following the code examples below.
Application context:
- Is bound to the current asynchronous runtime execution context, for example, an HTTP request.
- Is used only with
INSERT,UPDATE,DELETESQL queries performed via Prisma. Otherwise, it is a no-op. - Is passed directly into PG Write-Ahead Log with data changes without affecting the structure of the database and SQL queries.
Express.js
Section titled “Express.js”Add the bemiMiddleware Express.js middleware to pass application context with all underlying data changes made within an HTTP request:
import { bemiMiddleware } from "@bemi-db/prisma";import express, { Request } from "express";
const app = express();
app.use( bemiMiddleware((req: Request) => ({ // Customizable context userId: req.user?.id, endpoint: req.url, params: req.body, })));Apollo Server
Section titled “Apollo Server”If you use Apollo Server, it's possible use the BemiApolloServerPlugin to pass application context with all underlying data changes made within a GraphQL request:
import { BemiApolloServerPlugin } from "@bemi-db/prisma";import { ApolloServer } from "@apollo/server";
new ApolloServer({ plugins: [ BemiApolloServerPlugin(({ request, contextValue }: any) => ({ // Customizable context userId: contextValue.userId, operationName: request.operationName, variables: request.variables, endpoint: request.http.headers.get('origin'), })), ],});Next.js
Section titled “Next.js”With Next.js API Routes, it is possible to use the setBemiContext function to set application context in a handler function:
import { setBemiContext } from "@bemi-db/prisma";import type { NextApiRequest, NextApiResponse } from "next";
export default function handler(req: NextApiRequest, res: NextApiResponse) { // Customizable context setBemiContext({ url: req.url, userToken: req.cookies['user-token'] });
// ...}Alternatively, you can use our Express.js-compatible bemiMiddleware middleware with next-connect:
import { bemiMiddleware } from "@bemi-db/prisma";import { createRouter, expressWrapper } from "next-connect";import type { NextApiRequest, NextApiResponse } from "next";
const router = createRouter<NextApiRequest, NextApiResponse>();
router.use( // Customizable context bemiMiddleware((req) => ({ url: req.url, userToken: req.cookies['user-token'] }))).get((req, res) => { // ...})
export default router.handler({ onError: (err, req, res) => { res.status(500).end(err.message) },});Note that Next.js middlewares are not supported because they cannot be executed with the Node.js Runtime, see this discussion.
T3 Stack
Section titled “T3 Stack”With the T3 Stack, you can use the bemiTRPCMiddleware that sets the PgStack Audit context in the tRPC context for all API calls:
import { bemiTRPCMiddleware } from "@bemi-db/prisma";
// Create a context middleware for tRPC to set the application contextconst bemiMiddleware = bemiTRPCMiddleware(t, ({ ctx }) => ({ userId: ctx.session?.user?.id,}));
// Use the context middleware in your tRPC proceduresexport const publicProcedure = t.procedure.use(bemiMiddleware);Once it's done, make sure to update your tRPC procedures to perform database changes in the same async context. For example, instead of returning a Promise for a Prisma query directly, execute it the mutation function first and then return the Promise with the manually constructed result:
create: publicProcedure .input(z.object({ name: z.string().min(1) })) .mutation(async ({ ctx, input }) => { // ❌ The Prisma query will be executed in a separate async context, losing the application context return ctx.db.post.create({ data: { name: input.name }});
// ✅ Await for the Prisma query, while it has access to the application context and then use the result const post = await ctx.db.post.create({ data: { name: input.name } }); return { id: post.id }; }),Inline context
Section titled “Inline context”It is also possible to manually set or merge context by using the setBemiContext and mergeBemiContext functions:
import { setBemiContext } from "@bemi-db/prisma";
const MyWorker = () => { setBemiContext({ worker: 'MyWorker', stage: 'calculate' }) // ...
mergeBemiContext({ stage: 'store' }) // ...}Configuration
Section titled “Configuration”SQL query tracking
Section titled “SQL query tracking”You can automatically inject the original SQL query that performed data changes into the application context using injectSqlInContext.
This can be useful for troubleshooting purposes:
import { PrismaPg, withBemiExtension } from "@bemi-db/prisma";import { PrismaClient } from '@prisma/client';
const adapter = PrismaPg({ connectionString: process.env.DATABASE_URL });const prisma = withBemiExtension( new PrismaClient({ adapter }), { injectSqlInContext: true },);Allowlist models
Section titled “Allowlist models”If you want to enable context passing only for specific models, you can specify an includeModels list:
import { PrismaPg, withBemiExtension } from "@bemi-db/prisma";import { PrismaClient } from '@prisma/client';
const adapter = PrismaPg({ connectionString: process.env.DATABASE_URL });const prisma = withBemiExtension( new PrismaClient({ adapter }), { includeModels: ['User', 'Comment'] },);If your database uses a self-signed SSL certificate and you want to enforce using it, you can modify your Connection URL to include the following arguments:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?sslmode=verify-full&sslrootcert=./prod-ca-2021.crtThe sslrootcert argument can be a relative or an absolute path pointing to your self-signed SSL certificate.
Data change tracking
Section titled “Data change tracking”Connect your PostgreSQL database to PgStack Audit using the quickstart. Configure logical replication using the guide for your hosting platform.
With the integration installed, make a change through your application and check the project's Audit view. The change should include the application context supplied by your integration. Changes made outside the integrated application are still captured, but do not receive that application's context.
Use the PgStack database connection details from your project settings to query changes with SQL or your ORM. Replace [USERNAME], [HOSTNAME], and [DATABASE] with those details:
psql postgres://[USERNAME]@[HOSTNAME]:5432/[DATABASE] -c \ 'SELECT "primary_key", "table", "operation", "before", "after", "context", "committed_at" FROM changes;'Example output:
primary_key | table | operation | before | after | context | committed_at-------------+-------+-----------+----------------------------------------------------+-----------------------------------------------------+-------------------------------------------------------------------------------------------+------------------------ 26 | todo | CREATE | {} | {"id": 26, "task": "Sleep", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:09+00 27 | todo | CREATE | {} | {"id": 27, "task": "Eat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:11+00 28 | todo | CREATE | {} | {"id": 28, "task": "Repeat", "is_completed": false} | {"user_id": 187234, "endpoint": "/todo", "method": "POST", "SQL": "INSERT INTO ..."} | 2023-12-11 17:09:13+00 26 | todo | UPDATE | {"id": 26, "task": "Sleep", "is_completed": false} | {"id": 26, "task": "Sleep", "is_completed": true} | {"user_id": 187234, "endpoint": "/todo/complete", "method": "PUT", "SQL": "UPDATE ..."} | 2023-12-11 17:09:15+00 27 | todo | DELETE | {"id": 27, "task": "Eat", "is_completed": false} | {} | {"user_id": 187234, "endpoint": "/todo/27", "method": "DELETE", "SQL": "DELETE FROM ..."} | 2023-12-11 17:09:18+00Data change querying
Section titled “Data change querying”Connect to the PgStack Audit PostgreSQL destination database to query change data from your application.
To query the read-only historical data, add a new Prisma schema
datasource db { provider = "postgresql" url = "postgresql://[USERNAME]:[PASSWORD]@[DESTINATION_HOST]:5432/[DESTINATION_DATABASE]"}
generator client { provider = "prisma-client-js" output = "./generated/pgstack"}
model Change { id String @id primaryKey String @map("primary_key") before Json after Json context Json database String schema String table String operation String committedAt DateTime @map("committed_at") createdAt DateTime @map("created_at")
@@map("changes")}Generate Prisma client:
npx prisma generate --schema prisma/pgstack.prismaInitialize a new Prisma client connected to the destination database:
import { PrismaClient } from '../prisma/generated/pgstack'
const pgstackPrisma = new PrismaClient()Query changes from the destination database:
const changes = await pgstackPrisma.change.findMany({ where: { table: "todo", context: { path: ['userId'], equals: 1 } }, orderBy: { committedAt: "desc" }, take: 1,});Or by using a raw SQL query:
const changes = await pgstackPrisma.$queryRaw` SELECT * FROM "changes" WHERE "table" = 'todo' AND "context" @> '{"userId": 1}' ORDER BY "committed_at" DESC LIMIT 1`;License
Section titled “License”Distributed under the terms of the LGPL-3.0. If you need to modify and distribute the code, please release it to contribute back to the open-source community.
Copyright © 2026 PgStack
