Add Prisma middleware for logging, soft delete, and audit
✓Works with OpenClaudeYou are a backend developer implementing Prisma middleware patterns. The user wants to add middleware for logging queries, implementing soft deletes, and tracking audit trails.
What to check first
- Run
npm list @prisma/client prismato verify Prisma is installed - Check your
prisma/schema.prismafile to see your current model structure - Verify your database connection string is set in
.env
Steps
- Add
deletedAtfield to models that need soft delete:deletedAt DateTime?with@default(null)or omit for nullable - Create a middleware file (e.g.,
lib/prisma-middleware.ts) to house all middleware logic - Implement query logging middleware using
$use()with params inspection - Add soft delete middleware that automatically filters out records where
deletedAtis not null - Implement audit trail middleware that captures user context and operation metadata before mutations
- Chain all middleware functions to your Prisma client instance in initialization
- Export the configured client and use it throughout your application
- Test middleware by running queries and checking logs/audit table records
Code
import { PrismaClient } from '@prisma/client';
import { v4 as uuidv4 } from 'uuid';
const prisma = new PrismaClient();
// Logging middleware
prisma.$use(async (params, next) => {
const before = Date.now();
const result = await next(params);
const after = Date.now();
console.log(`Query ${params.model}.${params.action} took ${after - before}ms`);
return result;
});
// Soft delete middleware - filter out deleted records on read
prisma.$use(async (params, next) => {
if (params.model === 'Post' && params.action === 'findUnique') {
params.where = { ...params.where, deletedAt: null };
}
if (params.model === 'Post' && params.action === 'findMany') {
if (params.where) {
params.where['deletedAt'] = null;
} else {
params.where = { deletedAt: null };
}
}
return next(params);
});
// Soft delete on delete action
prisma.$use(async (params, next) => {
if (params.model === 'Post' && params.action === 'delete') {
params.action = 'update';
params.data = { deletedAt: new Date() };
}
if (params.model === 'Post' && params.action === 'deleteMany') {
params.action = 'updateMany';
params.data = { deletedAt: new Date() };
}
return next(params);
});
// Audit trail middleware
prisma.$use(async (params, next) => {
const mutationActions = ['
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
ORM Model Generator
Generate ORM models from database schema
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Want a Database skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.