Skip to content

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.

  • PostgreSQL 14+
  • Prisma
  1. Install the NPM package
Terminal window
npm install @bemi-db/prisma
  1. Generate a Prisma migration file to add lightweight PostgreSQL triggers for passing application context with all data changes into PostgreSQL replication log
Terminal window
npx bemi migration:create
  1. Run the Prisma migration
Terminal window
npx prisma migrate dev

Enable the new Prisma driver adapters to use a native PostgreSQL client for Node.js by adding the following:

prisma/schema.prisma
generator client {
previewFeatures = ["driverAdapters"]
...
}

Enable PostgreSQL adapter for your Prisma client by using withBemiExtension:

src/prisma.ts
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, DELETE SQL 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.

Add the bemiMiddleware Express.js middleware to pass application context with all underlying data changes made within an HTTP request:

src/index.ts
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,
}))
);

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:

src/apollo-server.ts
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'),
})),
],
});

With Next.js API Routes, it is possible to use the setBemiContext function to set application context in a handler function:

pages/api/endpoint.ts
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:

pages/api/endpoint.ts
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.

With the T3 Stack, you can use the bemiTRPCMiddleware that sets the PgStack Audit context in the tRPC context for all API calls:

src/server/api/trpc.ts
import { bemiTRPCMiddleware } from "@bemi-db/prisma";
// Create a context middleware for tRPC to set the application context
const bemiMiddleware = bemiTRPCMiddleware(t, ({ ctx }) => ({
userId: ctx.session?.user?.id,
}));
// Use the context middleware in your tRPC procedures
export 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:

src/server/api/routers/post.ts
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 };
}),

It is also possible to manually set or merge context by using the setBemiContext and mergeBemiContext functions:

src/my-worker.ts
import { setBemiContext } from "@bemi-db/prisma";
const MyWorker = () => {
setBemiContext({ worker: 'MyWorker', stage: 'calculate' })
// ...
mergeBemiContext({ stage: 'store' })
// ...
}

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:

src/prisma.ts
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 },
);

If you want to enable context passing only for specific models, you can specify an includeModels list:

src/prisma.ts
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.crt

The sslrootcert argument can be a relative or an absolute path pointing to your self-signed SSL certificate.

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:

Terminal window
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+00

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

prisma/pgstack.prisma
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:

Terminal window
npx prisma generate --schema prisma/pgstack.prisma

Initialize a new Prisma client connected to the destination database:

src/pgstackPrisma.ts
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
`;

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.