skip to content

After a Prisma 7 upgrade removed prisma.$use, how do you rebuild an audit middleware with $extends, and why might it miss some queries?

level: seniorimportance: should knowfreq 40%

answer

  1. the middleware method is gone
  2. a query component wraps operations
  3. a new client, not a mutation
  4. nested reads skip the hook
  5. computed fields live elsewhere

basics

~20 s

Prisma 7 removed $use; a query extension created with $extends wraps operations instead. $extends returns a new client, so code that keeps the base instance bypasses it, and query hooks see top-level operations only, not relations loaded through include.

solid answer

~50 s

In Prisma 7 `prisma.$use` no longer exists, so an un-ported v6 middleware fails with `TypeError: prisma.$use is not a function`. The replacement is the `query` component of `$extends`: a callback under a model name, `$allModels` or a top-level `$allOperations` receives `{ model, operation, args, query }`, may rewrite `args` except `select` and `include`, and returns `query(args)`. Two behaviours catch upgrades. `$extends` does not mutate the client; it returns a new extended client that shares the base client's connection pool, so modules still importing the base instance run unaudited. And query extensions do not run for nested operations: a `review.findMany` hook hiding flagged reviews does not touch reviews loaded by `product.findMany({ include: { reviews: true } })`. Raw queries reach only a top-level `$allOperations` or a `$queryRaw` key. For derived fields, use the `result` component, computed lazily on access from declared `needs`.

code

typescript · 34 lines
typescript
import { PrismaClient, Prisma } from "./generated/prisma/client";
import { PrismaPg } from "@prisma/adapter-pg";

const base = new PrismaClient({
  adapter: new PrismaPg({ connectionString: process.env.DATABASE_URL }),
});

const audit = Prisma.defineExtension({
  name: "audit",
  query: {
    $allModels: {
      async $allOperations({ model, operation, args, query }) {
        const started = performance.now();
        const result = await query(args);
        console.info({ model, operation, ms: performance.now() - started });
        return result;
      },
    },
  },
});

const margins = Prisma.defineExtension({
  result: {
    product: {
      marginCents: {
        needs: { priceCents: true, costCents: true },
        compute: (p) => p.priceCents - p.costCents,
      },
    },
  },
});

export const prisma = base.$extends(audit).$extends(margins);
export type AppPrismaClient = typeof prisma;

go deeper

for a junior

Recall that Prisma 7 removed $use and that $extends with a query component is the replacement.

for a middle

Explain the query callback's model, operation, args and query arguments, the four extension components, and why the result of $extends must be the client the app imports.

for a senior

Diagnose missed audits: modules on the base client, nested includes and writes bypassing query hooks, and raw queries outside $allModels; then close each gap.

for a principal

Decide which cross-cutting rules live in client extensions and which need database enforcement, given that nested operations bypass query hooks.

## What changed in Prisma 7 Prisma 6 let you register **client middleware** with `prisma.$use(async (params, next) => ...)`, a callback that saw every operation and called `next(params)` to continue. The Prisma 7 upgrade guide lists client middleware as removed and points to **Client Extensions**. The method is gone from the client object, so an un-ported call fails when that line runs, with `TypeError: prisma.$use is not a function`, rather than with a deprecation warning. ## The four extension components `$extends` takes an object with up to four components, each for a different need: | Component | Adds | Example | |---|---|---| | `query` | code around operations: rewrite `args`, time or post-process the result | audit log, default `take`, tenant filter | | `result` | computed fields on returned records | `marginCents` from `priceCents` and `costCents` | | `model` | custom methods on a model delegate | a finder you define on `prisma.product` | | `client` | client-level methods | a helper on the client itself | An optional `name` labels the extension in error output, and `Prisma.defineExtension` lets you declare an extension in its own module and apply it later. ## Porting the audit middleware 1. Move the body of the `$use` callback into `query.$allModels.$allOperations`, or into a single model and operation such as `query.product.update`. 2. Read the callback's `model` and `operation` arguments where the middleware read `params.model` and `params.action`, and call `query(args)` where it called `next(params)`. 3. Return the result of `query(args)`; the hook may await it to time the call or inspect the outcome. 4. Export the value that `$extends` returns, and import only that client in application code. Inside the hook you may change `args`, for example add a `where` condition or cap `take`, but not `select` or `include`, because that would change the result type the caller was promised. ## Why an extension misses queries - **`$extends` returns a new client.** The base client is not mutated; the extended client is a separate, lightweight instance that shares the base client's connection pool. A module that still imports the base instance runs every query unaudited, and nothing fails. - **Nested operations bypass query hooks.** The docs state that the `query` component does not support nested reads and writes. A hook on `review.findMany` runs for `prisma.review.findMany()` but not for reviews loaded by `prisma.product.findMany({ include: { reviews: true } })`, and a hook on `review.create` misses reviews created by a nested write on a product. - **Raw queries are their own operations.** `$queryRaw` and its siblings reach a top-level `query.$allOperations`, where `model` is `undefined`, or a dedicated `query.$queryRaw` key, but not hooks under `$allModels`. - **Conflicting definitions.** When extensions combined on one client define the same method, the extension applied last wins. An audit or filter that must hold for every row access therefore needs a second line: hooks on each model that can be reached through a relation, or a database-level control such as row-level security. ## Computed fields belong in `result` Middleware often decorated returned rows. In Prisma 7 that is the `result` component: each field declares `needs`, the scalar fields it reads, and a `compute` function, and Prisma types the new field. Three rules surprise people: - values are computed lazily, when the property is accessed, not when rows are fetched; - with `select`, the computed field appears only when it is selected itself, and Prisma then reads its `needs` columns for you; - `needs` can reference scalar fields of the same model only, not relations. ## Wiring it once Build the extended client in one module, export it, and derive its type with `typeof prisma` for function signatures. Forbid imports of the base client elsewhere, for example with a lint rule. Because extended clients share one pool, a per-request extended client, such as one carrying the current user's id for a filter, is cheap to create. Finally, test the gaps rather than the happy path. An integration test that loads reviews through `prisma.product.findMany({ include: { reviews: true } })` and asserts what the audit log or filter did will fail loudly the day someone relies on a query hook for a nested read, instead of the gap surfacing in production.

  • How would you enforce a soft-delete filter for reviews when reviews are also loaded through product includes?
    A `query` hook on `review` alone is not enough, because nested reads bypass it. Add the filter where reviews are included, for example a shared `include` object with `where: { deletedAt: null }`, wrap the product operations that include reviews, or enforce it in the database with a view or row-level security. Test the include path explicitly.
  • Does creating an extended client per request open new database connections?
    No. Extended clients are lightweight wrappers that share the base client's connection pool, so `prisma.$extends(...)` per request costs object creation, not connections. That makes per-request extensions carrying a user or tenant id practical. An extension author can still create a separate `PrismaClient` inside it, so check what shared extensions do.

  • prisma.$use still works in Prisma 7 with a deprecation warning.
  • $extends mutates the client, so existing imports pick up the extension.
  • A query hook on review.findMany also filters reviews loaded through include.
  • Each extended client opens its own connection pool.
  • A query extension can swap a select for an include on the fly.

Assumes Prisma ORM 7: the upgrade from 6 removed the $use client middleware API, and Client Extensions created with $extends are its replacement.