Middleware
Middleware allows you to intercept and modify queries before they’re executed and results after they’re returned.What is Middleware?
Middleware functions run in sequence for every query:- Logging queries
- Performance monitoring
- Query modification
- Result transformation
- Access control
- Caching
Basic Usage
Middleware is registered using$use():
Middleware Parameters
params
Theparams object contains query information:
/home/daytona/workspace/source/packages/client/src/runtime/QueryMiddlewareParams.ts:4-14
Example:
next
Thenext function executes the next middleware or the actual query:
Modifying Queries
Modify Arguments
Modify Action
Conditional Execution
Modifying Results
Transform Results
Add Computed Fields
Execution Order
Middleware executes in registration order:Common Patterns
Query Logging
Performance Monitoring
Soft Delete
Caching
Access Control
Middleware vs Extensions
Use middleware when:- You need to intercept ALL queries
- You want to modify behavior globally
- Order of execution matters
- You need to work with low-level query params
- You want to add custom methods
- You need type-safe APIs
- You want to extend specific models
- You need to transform results with type safety
Limitations
Cannot Stop Execution
You must callnext(). You cannot prevent query execution:
Async Only
Middleware must be async functions:Order Matters
Middleware is executed in registration order. Register earlier for outer behavior:Migration from Query Middleware
Query middleware ($use) replaced the older $on('query') event:
$on() for read-only logging and $use() for modifications.
Next Steps
Extensions
Extend Prisma Client with custom methods
Error Handling
Handle errors in middleware