Imagine a support ticket that says: "This customer's plan dropped from Pro to Basic last Tuesday, and they say they didn't do it." You check the logs and find a PATCH /customers/482 with a 200 response. You can't tell who sent it, what the plan was before, or whether anything else changed in the same request. The data is correct now, but the history is gone.
An audit trail answers that question. Record who changed what, when, and from where in a dedicated, append-only table. Write each record in the same database transaction as the change itself, and show the history as a timeline in your React admin screens. This article covers what to record, where to capture changes in a NestJS app using TypeORM or Prisma, how to pass the user's identity all the way to PostgreSQL, how to stop the table from being edited, how to handle personal data and retention, and what the history view should look like.
An audit trail isn't your application log
Application logs help engineers debug. An audit trail is a business record that support, admins, and sometimes auditors rely on. The OWASP Logging Cheat Sheet notes that audit trails are "usually collected for different purposes than security event logging" and says "they should be kept separate." Keeping them apart also means you can set different retention, access, and integrity rules for each.
OWASP groups useful event attributes into when, where, who, and what, and the OWASP ASVS 5.0 requirements ask for log entries that include "when, where, who, what." For a record-level audit trail, that becomes:
- Who: the actor's ID (OWASP's example is the "user database table primary key-value") and the actor type, such as user, system job, or import.
- What: the action (create, update, delete), the entity type and ID, and the fields that changed with their old and new values.
- When: a timestamp in UTC or with an explicit offset, as ASVS 16.2.2 requires.
- Where: a request or correlation ID that ties the audit entry to your application logs, plus the application or service name if several write to the same database.
Just as important is what to leave out. OWASP's list of data that "should usually not be recorded directly in the logs" includes session identifiers, access tokens, passwords, encryption keys, connection strings, sensitive personal data, and payment card data. If a password hash or API key column changes, record that it changed, not the values.
The table: one generic audit table with JSONB
Most apps are well served by one shared audit table rather than a history table per entity. A typical shape is:
id,occurred_at(atimestamptz),actor_id,actor_typeaction,entity_type,entity_idchanges, ajsonbcolumn holding only the changed fields, each with its old and new valuerequest_id
Store only what changed, not full copies of the row before and after. Full copies multiply storage and copy every piece of personal data in the row into a table that's hard to clean up later. Use jsonb rather than json. The PostgreSQL JSON documentation says jsonb is "significantly faster to process" and supports indexing. For the history screen, the query you'll run most is "all changes to this entity, newest first," so add an index on (entity_type, entity_id, occurred_at).
Where to capture changes: a decision rule
There are four common places to capture changes, and they answer different questions:
- Application layer. A NestJS service, ORM hook, or Prisma extension writes the audit row. It has the full request context, including the user, the request ID, and human-readable intent. It misses writes that bypass the app, such as raw SQL fixes, other services, or manual scripts.
- PostgreSQL triggers. A trigger sees every row change, whoever made it, through the
OLDandNEWrecords described in the PL/pgSQL trigger documentation, which even includes an audit trigger example. But the database doesn't know your app user unless you pass it in, which the actor section below covers. - pgAudit. The pgAudit extension provides "session and/or object audit logging via the standard PostgreSQL logging facility." That's statement logging into server logs, useful for database-level compliance, not a per-record history you can show in a UI.
- Change data capture. Tools like Debezium capture "row-level changes" from the write-ahead log for streaming to other systems. The log contains row data, not your app user, so on its own it doesn't answer "who."
A practical rule: capture in the application layer when the app is the only writer. Use triggers when other writers exist, or when you need a guarantee that no change escapes. Combining them works well, with triggers recording the change and the app supplying the actor.
TypeORM: subscribers fire, but the old values may be missing
TypeORM entity subscribers look like the obvious hook, and the listeners and subscribers documentation confirms that "Events are firing using QueryBuilder and repository/manager methods." The catch is the old values you need for a before-and-after record.
As of November 2026, TypeORM's UpdateEvent typings say the databaseEntity property, the row as it was in the database, "Is set only when one of the following methods are used: .save(), .remove(), .softRemove(), and .recover()." For the list of updated columns, they add: "In query builder has no affected." The docs also warn that event.entity "may not necessarily contain primary key(s) when Repository.update() is used."
So an afterUpdate subscriber still runs after repository.update() or a QueryBuilder update, but it may not know the previous values, which columns changed, or even which row it was. You have three ways to deal with that:
- Route audited writes through save(). For audited entities, load the entity, change it, and call
save(), so the subscriber getsdatabaseEntity. - Read the old row yourself in the same transaction. In the service method, load the current row with the transaction's entity manager, apply the update, and write the audit row with the computed differences, all in one transaction.
- Use a trigger for the change data and supply only the actor from the app.
Whichever you choose, write a test that performs each kind of update your code uses and checks the audit row it produces.
Prisma: check your version first
Prisma's hook API has changed twice, so the right approach depends on your version. As of November 2026:
- Prisma 7: the upgrade guide says "The client middleware API has been removed." The replacement is a query extension, using
$allModelsand$allOperationsto wrap every model operation. - Prisma 8: the migration notes from Prisma 7 say "$extends will not be added. Middleware replaces query extensions." Prisma's release status page still described version 8 as a release candidate when this was written, so check its status before you build on either API.
Two points apply regardless of version. First, an update operation doesn't give you the old values for free. Read the current row in the same interactive transaction before updating, and compute the differences. Second, keep the audit write inside that same transaction, which the next sections explain. Raw queries need their own handling, so check how your version's hook treats them, or audit them with triggers.
Who did it: carrying the actor from the request to the database
The user is known in the NestJS request, but the code that writes the audit row is usually several calls away. Passing the user through every function signature gets messy, and request-scoped providers have their own costs. The NestJS async local storage recipe describes AsyncLocalStorage as "an alternative to REQUEST-scoped providers," and mentions the community nestjs-cls package, which it notes is "not managed by the NestJS core team." In Node.js, the async context module is marked "Stability: 2 - Stable," though some methods such as enterWith are still experimental, so prefer run().
Set the actor once, early in the request, and read it wherever you write audit rows. Not every change comes from a logged-in user, so make the actor explicit in those cases:
- Background jobs and cron tasks: record a system actor such as the job's name, plus the user who scheduled it if there was one.
- Imports: record the import job and the user who uploaded the file.
- Impersonation: record both the support agent and the customer they were acting as. Recording only the customer hides who really made the change.
If triggers capture the change, the database needs the actor too. PostgreSQL's set_config function, described in its configuration functions documentation, does this. Inside the transaction, call set_config('app.user_id', $1, true) with the user ID as a parameter. The trigger then reads it with current_setting('app.user_id', true), which returns NULL instead of an error when the setting is missing. PostgreSQL accepts two-part custom names like app.user_id.
The third argument, true, matters. With it, the value "will only apply during the current transaction." Without it, a session-level setting stays on the database connection after your request ends. With connection pooling, the next request that gets that connection can inherit the previous user's ID, and changes are attributed to the wrong person. A related trap: according to the SET documentation, SET LOCAL outside a transaction block "emits a warning and otherwise has no effect." If your ORM runs that statement outside the transaction, the trigger sees no actor at all.
If you use PgBouncer in transaction pooling mode, its features page says "A server connection is assigned to a client only during a transaction," and its feature table lists SET/RESET as "Never" supported in that mode, with no separate entry for SET LOCAL or set_config. Reasoning from those two facts, a transaction-scoped setting ends when the transaction does, so it shouldn't outlive the connection PgBouncer assigned for that transaction. PgBouncer doesn't state this directly, so test it behind your actual pooler before relying on it. In the trigger, decide what happens when the actor is missing: record an explicit "unknown" or reject the change, but don't silently fall back to the database role, which hides the problem.
Write it in the same transaction
Write the audit row in the same database transaction as the change it describes. Then they succeed or fail together. If the change rolls back, there's no audit row describing something that never happened. If the audit insert fails, the change doesn't go through unrecorded.
Fire-and-forget auditing breaks both guarantees. Sending the audit event to a queue or logging service after the change, without waiting, means a crash or network error can lose records. Sending it before the transaction commits can record changes that later roll back. If you need the audit data in another system as well, write it to the database first and forward it from there, using the same transactional outbox approach used for reliable messaging.
Making it append-only for real
An audit table that anyone can edit isn't much of an audit trail. ASVS 16.4.2 asks that logs be "protected from unauthorized access and cannot be modified." Revoking UPDATE and DELETE is the start, but the PostgreSQL GRANT documentation explains two ways around it: a table's owner "has all privileges by default," and "database superusers can access all objects regardless of object privilege settings."
So the protection depends on roles:
- The app's runtime role must not own the audit table. Let a separate migration role own it, and grant the runtime role only INSERT and SELECT.
- Don't run the app as a superuser. No privilege setting protects the table from one.
- Add a trigger that raises an error on UPDATE or DELETE as defense in depth. It catches mistakes, but anyone who can drop the trigger can bypass it.
- Consider tamper evidence for higher-stakes systems, such as storing a hash of each entry chained to the previous one, so edits made outside the app are detectable.
Personal data, erasure, and retention
An audit trail of customer records is itself personal data, and an append-only design pulls against rights like erasure. This section isn't legal advice, but the design choices are worth making deliberately. The GDPR asks that personal data be limited to what's necessary for its purpose (Article 5(1)(c)) and kept in identifiable form no longer than necessary (Article 5(1)(e)). Article 17 gives people a right to erasure, with exceptions, including where processing is needed to meet a legal obligation or for legal claims. Which of those apply to your audit data is a question for your legal or privacy team.
Design choices that make those conversations easier:
- Store IDs, not personal values, where you can. Recording that
emailchanged, with a reference, is often enough for support. Copying old and new email addresses into a long-lived table usually isn't necessary. - Mask or omit sensitive fields in the change record, and show them as "changed (hidden)" in the UI.
- Set a retention period per entity type, and enforce it. The PostgreSQL partitioning documentation notes that dropping a partition "is far faster than a bulk operation" and avoids the VACUUM overhead of a large DELETE, so partitioning the audit table by month makes retention cheap. A primary key on a partitioned table must include the partition key, so use
(id, occurred_at). - Pseudonymize actors in long-term storage if your policy calls for it, keeping the lookup to real identities separately.
For US teams handling health data, the HIPAA Security Rule requires audit controls: 45 CFR 164.312(b) calls for mechanisms "that record and examine activity in information systems" that contain or use electronic protected health information. The same design applies, with retention and access set by your compliance requirements.
Showing it in React: a history timeline
A history view is where the audit trail pays off for support and admins. Government design systems have useful guidance here. The UK Ministry of Justice's Timeline component shows each event with a title, a date and time, and who or what made the update, and advises: "Show the most recent events first, unless user research suggests a different order is better."
For a record history in React:
- Show one entry per request, not per column. Group changes that share a request ID, so "Plan changed from Pro to Basic, seats changed from 10 to 3" reads as one event.
- Use labels, not column names. Map
plan_tierto "Plan" and enum codes to the words users see. Format dates and money the way the rest of the screen does. - Make system actors obvious. "Nightly billing job" or "CSV import by Dana" is clearer than a blank name or an internal ID.
- Paginate with a cursor. Load the newest page first and fetch older entries using the last
occurred_atandidas the cursor, which the index above supports. - Treat reading history as its own permission. Enforce it in the API, not just by hiding the tab, and apply the same tenant scoping as the record itself. Masked fields should stay masked in the response, not just in the UI.
If you also use version numbers to prevent conflicting edits, show the version on each entry. It makes conflict messages and history easy to connect.
An audit trail checklist
- Keep the audit trail separate from application logs, with its own access and retention rules.
- Record actor ID and type, action, entity type and ID, changed fields with old and new values, a UTC timestamp, and a request ID.
- Never record passwords, tokens, keys, or connection strings. Mask sensitive personal data.
- Use one audit table with a
jsonbchanges column and an index on entity and time. - Capture in the app layer when the app is the only writer, and add triggers when it isn't.
- In TypeORM, don't assume subscribers have old values outside
save(),remove(),softRemove(), andrecover(). - In Prisma, match the approach to your version, and read old values inside the transaction.
- Carry the actor with AsyncLocalStorage, and give jobs, imports, and impersonation explicit actors.
- Pass the actor to triggers with
set_config(..., true)inside the transaction, never a session-level SET. - Write the audit row in the same transaction as the change.
- Give the runtime role INSERT and SELECT only, and keep table ownership elsewhere.
- Set retention per entity, and partition by time so old data can be dropped cheaply.
- Show history newest first, grouped by request, with readable labels and a separate read permission.



