TypeORM
Section titled “TypeORM”View the integration on GitHub
PgStack Audit plugs into TypeORM 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 TypeORM 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+
- TypeORM
Installation
Section titled “Installation”- Install the NPM package
npm install @bemi-db/typeorm- Generate a TypeORM migration file to add lightweight PostgreSQL triggers for passing application context with all data changes into PostgreSQL replication log
npx bemi migration:create ./path-to-migrations-dir- Run pending TypeORM migrations
npx typeorm migration:runExpress.js
Section titled “Express.js”Add an Express middleware to pass application context with all underlying data changes within an HTTP request:
import { setContext } from "@bemi-db/typeorm";import express, { Request } from "express";import { AppDataSource } from "./data-source";
const app = express();
// This is where you set any information that should be stored as context with all data changesapp.use( setContext(AppDataSource, (req: Request) => ({ endpoint: req.url, params: req.body, userId: req.user?.id, })));
AppDataSource.initialize() // initialize TypeORM connection as normalApplication 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 TypeORM. 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.
Inline context
Section titled “Inline context”It is also possible to manually set or override context by using the bemiContext function:
import { bemiContext } from "@bemi-db/typeorm";
const MyWorker = () => { bemiContext({ worker: 'MyWorker', stage: 'calculate' }) // ...
bemiContext({ worker: 'MyWorker', stage: 'store' }) // ...}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 database to query change data from your application.
To query the read-only historical data, add the PgStack Audit destination database to TypeORM using multiple data source. Configuration setting are found directly on the PgStack Audit dashboard:
import { DataSource } from "typeorm";import { Change } from "@bemi-db/typeorm";
export const AppDataSource = new DataSource({ type: "postgres", host: "localhost", port: 3306, username: "root", password: "admin", database: "db1", entities: [__dirname + "/entity/*{.js,.ts}"], synchronize: true,});
export const PgStackDataSource = new DataSource({ type: "postgres", name: "pgstackRead", host: "us-west-1-prod-destination-pool.ctbxbtz4ojdc.us-west-1.rds.amazonaws.com", port: 5432, username: "u_9adb30103a55", password: "password", database: "db_9adb30103a55", synchronize: false, logging: true, entities: [Change], migrations: [], ssl: { rejectUnauthorized: false },});Initialize PgStackDataSource the same place you would your main AppDataSource
PgStackDataSource.initialize() .then(() => { console.log("Connected to PgStack Audit"); }) .catch((error) => { console.log(error); });Querying Changes:
import { Change } from "@bemi-db/typeorm";import { PgStackDataSource } from "./index";
const changeRepository = PgStackDataSource.getRepository(Change);
const [changes, changesCount] = await changeRepository.findAndCount();console.log("All changes: ", changes);console.log("changes count: ", changesCount);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
