Free 40-page Claude guide — setup, 120 prompt codes, MCP servers, AI agents. Download free →
CLSkills
DatabaseintermediateNew

Prisma Middleware

Share

Add Prisma middleware for logging, soft delete, and audit

Works with OpenClaude

You 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 prisma to verify Prisma is installed
  • Check your prisma/schema.prisma file to see your current model structure
  • Verify your database connection string is set in .env

Steps

  1. Add deletedAt field to models that need soft delete: deletedAt DateTime? with @default(null) or omit for nullable
  2. Create a middleware file (e.g., lib/prisma-middleware.ts) to house all middleware logic
  3. Implement query logging middleware using $use() with params inspection
  4. Add soft delete middleware that automatically filters out records where deletedAt is not null
  5. Implement audit trail middleware that captures user context and operation metadata before mutations
  6. Chain all middleware functions to your Prisma client instance in initialization
  7. Export the configured client and use it throughout your application
  8. 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

Quick Info

CategoryDatabase
Difficultyintermediate
Version1.0.0
AuthorClaude Skills Hub
prismamiddlewarelogging

Install command:

curl -o ~/.claude/skills/prisma-middleware.md https://clskills.in/skills/database/prisma-middleware.md

Related Database Skills

Other Claude Code skills in the same category — free to download.

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.