# How middleware works (/docs/orm/middleware/how-middleware-works) > For the complete Prisma documentation index, see [llms.txt](https://www.prisma.io/docs/llms.txt). A markdown version of any docs page is available by appending `.md` to its URL. Middleware runs your code before and after every query, so one policy can cover your whole app. Location: ORM > Middleware > How middleware works Middleware lets you run your own code around every query your app sends through Prisma ORM. For example, you can log every query with its latency, block a `DELETE` that has no `WHERE` clause before it reaches the database, or serve a repeated read from memory instead of running it again. You write the policy once, register it once, and every query follows it, with no call sites to update. If you used `$use` in Prisma ORM 7, the `middleware` array is its replacement. There is no `next()`: you pick the hook that runs at the moment you care about. [Coming from Prisma ORM 7](https://www.prisma.io/docs/orm/coming-from-prisma-orm-7) lists Prisma ORM 7 features next to the Prisma ORM 8 form each one takes. A middleware is a plain object with a name and one or more hooks, and a hook is a function that Prisma ORM calls at a fixed moment around a statement or a transaction. You register the whole object once, in the `middleware` option of your client setup. The setup below registers all three middleware Prisma ships. `lints` and `budgets` are already inside `@prisma/orm-postgres`, but the cache ships as its own package, so install that one first: #### npm ```bash title="Terminal" npm install @prisma/orm-extension-middleware-cache ``` #### pnpm ```bash title="Terminal" pnpm add @prisma/orm-extension-middleware-cache ``` #### yarn ```bash title="Terminal" yarn add @prisma/orm-extension-middleware-cache ``` #### bun ```bash title="Terminal" bun add @prisma/orm-extension-middleware-cache ``` The `src/prisma/db.ts` below imports two files from your own project, `contract.json` and `contract.d.ts`. Both come from your contract, which is the Prisma ORM 8 name for your schema: `contract.prisma` in a generated project, in place of `schema.prisma`. `npx prisma contract emit` writes the two files from it. If you set your project up by hand, [The data contract](https://www.prisma.io/docs/orm/contract-authoring/the-data-contract) covers where they come from. ```ts title="src/prisma/db.ts" import { createCacheMiddleware } from '@prisma/orm-extension-middleware-cache'; import postgres from '@prisma/orm-postgres/runtime'; import { budgets, lints } from '@prisma/orm-postgres/family-runtime'; import { contractFromJson } from '@prisma/orm-postgres/static'; import type { Contract } from './contract.d.js'; import contractJson from './contract.json' with { type: 'json' }; export const db = postgres({ contract: contractFromJson(contractJson), url: process.env['DATABASE_URL']!, middleware: [ createCacheMiddleware(), lints(), budgets({ maxRows: 10_000, maxLatencyMs: 1_000 }), ], }); ``` `npm create prisma@latest` generates a `src/prisma/db.ts` that already builds this client, and the `middleware` option is what you add to it. The generated file builds the client itself when the app runs without Prisma Composer, as it does with `npm run dev`. With `npm run dev:composer` it takes its client from Composer through `service.load()` instead, and the `middleware` option in `db.ts` is never used. To run middleware there too, change `service.load().database.client` to `service.load().database.clientWith({ middleware: [...] })`. The client itself, `postgres(...)`, comes from `@prisma/orm-postgres/runtime`. The built-in middleware and the `SqlMiddleware` type are imported from `@prisma/orm-postgres/family-runtime`, which works with any SQL database. `lints()` and `budgets()` both take an options object, and [lints](https://www.prisma.io/docs/orm/middleware/built-in-lints) and [budgets](https://www.prisma.io/docs/orm/middleware/built-in-budgets) list what goes in it. Writing your own middleware means writing that same kind of object: a `name`, a `familyId` saying which kind of database it works with, and the hooks you want. Here is a complete one that prints every query it sees: ```ts title="src/prisma/query-logger.ts" import type { SqlMiddleware } from '@prisma/orm-postgres/family-runtime'; export function queryLogger(): SqlMiddleware { return { name: 'query-logger', familyId: 'sql', async activityEnded(activity, result) { if (result.kind !== 'statement') return; const count = result.returns === 'rows' ? `${result.rowCount} rows` : 'write'; console.log(`${count} in ${Math.round(result.latencyMs)}ms · ${result.outcome}`); }, }; } ``` The `name` is the label Prisma ORM uses when it has to say which middleware it means in an error message, and nothing requires it to be unique. `familyId: 'sql'` means this middleware works with SQL databases only, so Prisma ORM rejects it on a MongoDB client. Add `queryLogger()` to the `middleware` array in `src/prisma/db.ts`, alongside the built-in middleware or on its own, and every query on that client runs through it. The [authoring guide](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware) builds this logger step by step, with the options and the other hooks. Every query goes through that list, whichever of the two APIs you wrote it with. With the ORM API you write `db.orm.public.User...`, where `public` is the PostgreSQL schema and `User` is the model in your contract. With the [SQL query builder](https://www.prisma.io/docs/orm/reference/sql-query-builder) you build a query and run it in two steps. `.build()` returns a plan, which is the query as a plain object, not yet run. `db.query(plan)` runs it and returns rows, and `db.execute(plan)` runs it and returns how many rows it changed. Both APIs send their queries on the same `db` object, so both see the same middleware. If your database is MongoDB, pass the same `middleware` option to `mongo(...)` from `@prisma/orm-mongo/runtime` and type your own middleware as `MongoMiddleware` from `@prisma/orm-mongo/family-runtime`. ## When your hooks run [#the-two-lifecycles] You write only the hooks you care about, and Prisma ORM skips the ones you leave out. Prisma ORM sends statements, runs the transactions you open with `db.transaction(...)`, and on SQL databases runs ORM calls. Each statement, transaction or ORM call is an **activity**. A middleware sees each activity through lifecycle hooks and interceptors: - **Lifecycle hooks** observe. `activityStarted`, `activityEnded` and `activityFinalized` run for every activity, a statement, a transaction or an ORM call, in that order. - **Interceptors** change or stop a statement while it runs: `beforeCompile`, `beforeEncode`, `intercept.onQuery` or `intercept.onExecute`, and `onRow`. One more interceptor, `intercept.onActivity`, can answer a whole ORM call. A statement calls your hooks in this order: `activityStarted` → `beforeCompile` → `beforeEncode` → `intercept.onQuery` or `intercept.onExecute` → `onRow` (once per row) → `activityEnded` → `activityFinalized` The same order holds for a statement that returns rows and one that only reports how many rows it changed. `activity.returns` on the statement tells them apart: - `'stats'`: a statement that reports only how many rows it changed. `db.execute(plan)` sends one, and so do the ORM methods `createAndCount`, `updateAndCount` and `deleteAndCount`, and a nested write that links or unlinks rows of a many-to-many relation. - `'rows'`: every other statement, including those sent by `db.query(plan)`. `intercept.onQuery` runs only for `'rows'` and `intercept.onExecute` only for `'stats'`, and `onRow` runs only when rows come back. If those names are new, the [queries table](https://www.prisma.io/docs/orm/coming-from-prisma-orm-7#queries) puts each of them next to the Prisma ORM 7 call it replaces. A transaction runs only the three lifecycle hooks: `activityStarted` when it opens, `activityEnded` when its `commit()` or `rollback()` settles, and `activityFinalized` after that. A statement sent inside `db.transaction(...)` is beneath the transaction, so `ctx.inTransaction()` is `true` in its hooks. `ctx.parent` is the context of the activity directly above it: the transaction, or the ORM call that sent the statement. Because the same hooks run for a statement that returns rows and one that reports a count, a check you want on reads and writes alike goes in `beforeEncode`, once: ```ts title="src/prisma/no-delete-all.ts" import type { SqlMiddleware } from '@prisma/orm-postgres/family-runtime'; export function noDeleteAll(): SqlMiddleware { return { name: 'no-delete-all', familyId: 'sql', async beforeEncode(plan) { if (plan.sql.startsWith('DELETE ') && !plan.sql.includes(' WHERE ')) { throw new Error('blocked by policy'); } }, }; } ``` At each step Prisma ORM calls that hook on every middleware you registered, and it waits for each one to finish before the statement moves on, so a hook can be `async` and a slow `activityEnded` delays the `await` in your own code. ### ORM calls [#orm-calls] On a SQL database, each ORM method that runs a query, such as `.all()`, `.first()`, `.create()`, `.updateAll()` or `.aggregate(...)`, runs as one activity whose `activity.kind` is `'orm-call'`. Each run of a [prepared statement](https://www.prisma.io/docs/orm/reference/transactions-and-runtime#dbpreparedeclaration-callback) built from an ORM query is one too. The SQL query builder's `db.query(plan)` and `db.execute(plan)` are not ORM calls: they send one statement, which is its own activity. - **It opens** when the call starts, before it sends anything. For `.all()`, that is when your code starts reading the rows, with `await` or `for await`. - **The statements it sends are beneath it.** A nested create, for example, sends several statements, and all of them are children of the one call. A call that needs a transaction of its own opens it beneath the call. A call made inside `db.transaction(...)` is a child of that transaction. - **It ends** when the call has its result, or fails. For `.all()` read with `for await`, it ends when your code reads the last row, stops early, or the read fails. - **It carries** `activity.id`, `activity.annotations` and `activity.contentHash()`. The annotations are the ones you attached with `meta.annotate(...)`, and the statements the call sends carry none of them, so read them in `activityStarted` from the `orm-call` activity. An ORM call has no `plan` and no `returns`. Use `activity.contentHash()` when you need a key for an ORM read, for example to cache it: the cache uses it for an annotated ORM read that has no `key`. It returns a promise of a digest of the call. For a read, the digest covers the method and the first statement the call sends, with its parameter values. For a write, it covers only the method and the model, because a write's statements depend on the results of earlier ones. So two writes to the same model get the same digest. A call runs `activityStarted`, then `intercept.onActivity`, then the hooks of each statement it sends, then `activityEnded` and `activityFinalized`. In `activityEnded`: - `result.kind` is `'orm-call'`. - `result.outcome` is `'succeeded'`, `'failed'` or `'stopped'`. - `result.source` is `'client'`, or `'middleware'` when `intercept.onActivity` answered the call. - `result.result` is the value the method returns. A call that streams rows, such as `.all()`, keeps them in `result.result` only when it carries an annotation, so an unannotated read does not hold all its rows in memory. - There is no `latencyMs`. To time a call, keep `ctx.now()` in `ctx.state(key)` in `activityStarted`. Outside a transaction, the call is finalized right after it ends: its [`activityFinalized`](#activityfinalized-act-once-the-effects-are-final) hooks run, once its effects are final. The outcome is `'committed'` when the call succeeded and everything beneath it was finalized `'committed'`, otherwise `'unknown'`. ### The order your middleware runs in [#the-order-your-middleware-runs-in] Prisma ORM calls your middleware in the order you listed them in the `middleware` array, at every hook, so the middleware at index 0 goes first. If one middleware rewrites the query in `beforeCompile`, the one after it sees the rewritten version. The lifecycle hooks follow that same order rather than unwinding in reverse, so the middleware at index 0 is also the first to log. Order decides who answers a statement as well: when several middleware implement `intercept.onQuery`, the first one that returns rows wins and the rest are not called at all, and the same holds for `intercept.onExecute` and `intercept.onActivity`. ### activityStarted: the activity begins [#activitystarted-the-activity-begins] `activityStarted(activity, ctx)` runs first, before anything is compiled or sent. `activity.kind` is `'statement'`, `'transaction'` or `'orm-call'`, `activity.id` is a fresh id that every hook of the activity sees, and for a statement `activity.plan` is the plan the caller sent and `activity.returns` is `'rows'` or `'stats'`. Throwing from it fails the activity, and the middleware listed after it never see the activity at all. ### beforeCompile: rewrite the query [#beforecompile-rewrite-the-query] Reach for `beforeCompile` when you want to change what a query asks for rather than only look at it. It hands you a draft with two fields: `meta`, facts about the query that you read but do not change, such as which API built it, and `ast`, the query as a tree of typed objects. The tree is the part you can change, because the SQL text has not been written yet. Return a copy of the draft with a changed `ast` and Prisma ORM runs your version instead, which is how you add a condition to queries without editing a single call site. Return `undefined` and the query goes through as written. The middleware below adds a condition to every `SELECT` whose own `FROM` clause names the `User` table: ```ts title="src/prisma/scope-user-selects.ts" import type { SqlMiddleware } from '@prisma/orm-postgres/family-runtime'; import { AndExpr, type BinaryExpr } from '@prisma/orm-postgres/relational-core/ast'; export function scopeUserSelects(condition: () => BinaryExpr | undefined): SqlMiddleware { return { name: 'scope-user-selects', familyId: 'sql', async beforeCompile(draft) { if (draft.ast.kind !== 'select') return undefined; if (draft.ast.from?.kind !== 'table-source') return undefined; if (draft.ast.from.name !== 'User') return undefined; const predicate = condition(); if (predicate === undefined) return undefined; const where = draft.ast.where ? AndExpr.of([draft.ast.where, predicate]) : predicate; return { ...draft, ast: draft.ast.withWhere(where) }; }, }; } ``` The three checks above are how you say "only `SELECT`s, and only ones over the `User` table". `draft.ast.kind` is `'select'`, `'insert'`, `'update'`, `'delete'`, or `'raw-query'`, and `draft.ast.from.kind` is `'table-source'` when a `SELECT` reads a plain table rather than a subquery or a function. Use the table name as it is in your database rather than the model name in your contract. They are the same, `User`, unless the model sets `@@map`, in which case use the name it maps to. `withWhere` returns a new `SELECT` with that `WHERE` on it and leaves the original alone, which is why the hook returns a copy of the draft. These checks read only the table in the query's own `FROM` clause, so `User` rows that a query loads with `.include(...)` or through a join are not filtered. Do not rely on a middleware like this alone to keep one tenant's rows away from another. The function you pass in returns the comparison to add, or `undefined` to add none, and the middleware calls it for each `SELECT` whose `FROM` clause names `User`, after the three checks. You build the comparison yourself, and the types for building one come from `@prisma/orm-postgres/relational-core/ast`. A value you compare against needs its `codecId`, an id that says how the value is stored, such as `pg/text@1` for text and `pg/int4@1` for a 32-bit integer. [Authoring custom middleware](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware#rewrite-queries-with-beforecompile) lists the id for each field type: ```ts title="src/prisma/db.ts (excerpt)" import { BinaryExpr, ColumnRef, ParamRef } from '@prisma/orm-postgres/relational-core/ast'; import { scopeUserSelects } from './scope-user-selects'; const onlyMia = BinaryExpr.eq( ColumnRef.of('User', 'name'), ParamRef.of('Mia', { codec: { codecId: 'pg/text@1' } }), ); ``` Then `scopeUserSelects(() => onlyMia)` goes in the `middleware` array of your `postgres(...)` client, like any other entry. [Rewrite queries with beforeCompile](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware#rewrite-queries-with-beforecompile) shows how the function can return a different value for each request, and covers the other comparisons and why a value has to go through `ParamRef.of`. `beforeCompile` is not available on MongoDB, because the tree it works on is made of SQL objects. ### beforeEncode: validate or block [#beforeencode-validate-or-block] `beforeEncode` is where you inspect a statement and refuse it. It runs after the SQL text has been written out and before the parameter values are encoded and anything reaches the database, for statements of both kinds. Your hook receives the plan, so you can read the SQL text in `plan.sql` and read the same query as objects in `plan.ast`, which is the tree `beforeCompile` works on. Throwing from the hook blocks the statement, and returning normally lets it carry on to the database: ```ts async beforeEncode(plan) { if (isForbidden(plan)) throw new Error("blocked by policy"); } ``` This is where `lints` stops a `DELETE` without `WHERE`, and where `budgets` rejects a query that would read too many rows. Every hook also receives a context object, `ctx`, which tells it about the activity it is running inside. `ctx` is the argument after `plan`, or after `result` in `activityEnded` and `activityFinalized`. `ctx.state(key)` returns an object that belongs to this one activity, so a value your `beforeEncode` stores there is still there in your `activityEnded`. `ctx.scope` is `'transaction'` for a statement inside `db.transaction(...)` and `'runtime'` for one you sent on `db` directly, so your middleware does see the statements you run in a transaction. [The context object](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware#the-context-object) lists every field it holds. The hook can also change the values the statement sends to the database, and it does that through a third argument, `params`, which you declare as `beforeEncode(plan, ctx, params)` when you want it. `params.entries()` walks those values one at a time, and each entry has three fields: - `entry.value` is the value itself. - `entry.codecId` is the stored type, an id such as `pg/text@1`, `pg/int4@1`, or `pg/timestamptz-date@1`. - `entry.ref` identifies that one value in the query, and it is what you pass to `replaceValue`. Call `params.replaceValue(entry.ref, newValue)` and the database receives your value instead of the original. `params` is typed as optional and Prisma ORM always passes it, so the guard on the first line is there to satisfy TypeScript: ```ts async beforeEncode(plan, ctx, params) { if (!params) return; for (const entry of params.entries()) { if (entry.codecId === 'pg/text@1' && typeof entry.value === 'string') { params.replaceValue(entry.ref, entry.value.trim()); } } }, ``` Check `entry.codecId` before you call `replaceValue`, as the example does. Write the hook as `beforeEncode(plan)` instead and nothing about the values changes. ### intercept: answer without the database [#intercept-answer-without-the-database] `intercept.onQuery` and `intercept.onExecute` let you answer a statement yourself, so the database never sees it. They go in an `intercept` object on your middleware. Return `{ rows }` from `onQuery`, or `{ stats }` from `onExecute`, and that is what your caller gets back, but return `undefined` and the statement carries on to the database as usual. The `stats` you return is the count that statement reports, for example `{ stats: { affectedRows: 0 } }`: ```ts intercept: { async onQuery(plan, ctx) { return cached.has(plan.sql) ? { rows: cached.get(plan.sql) } : undefined; }, }, ``` The rows you return are plain objects, keyed by the column aliases in the SQL, holding the values in the form the database driver hands them over. On PostgreSQL every value that is not SQL `NULL` is the text the database printed, so integers are strings, as are text and timestamps. A `NULL` stays `null`. A read that selects `id`, `email`, and `createdAt` produces rows like this one: ```ts { id: '3', email: 'mia+1@prisma.io', createdAt: '2026-09-17 08:00:08.775+00' } ``` So for a query whose SQL is `SELECT "User"."id" AS "id", "User"."email" AS "email" FROM "public"."User" LIMIT 5`, `return { rows: [{ id: '1', email: 'mia@prisma.io' }] }` is a complete answer to it. Prisma ORM converts the rows you return the same way it converts rows from the database. So if you return a `createdAt` as a string, a caller on the ORM API gets a `Date`, which is the type of a `DateTime` field. `intercept.onActivity(activity, ctx)` answers a whole [ORM call](#orm-calls) instead of one statement. It runs after the call's `activityStarted` hooks and before the call sends anything. Return `{ result }`, where `result` is the value the method returns, and the call sends no statement at all. This is how the cache serves an annotated ORM read. [Answer ORM calls with intercept.onActivity](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware#answer-orm-calls-with-interceptonactivity) shows an example. `beforeEncode` still runs on a statement that `intercept.onQuery` or `intercept.onExecute` answers, because every middleware's `beforeEncode` runs before any of those handlers, whatever order you list the middleware in. So in the setup at the top of this page, where the cache comes first in the array, `lints` still checks a SQL builder query before the cache answers it. An ORM call that `intercept.onActivity` answers is different: it builds no statement, so no `beforeCompile`, `beforeEncode` or `onRow` hook runs for it, and `lints` does not see an ORM read the cache serves. A check that must also cover those reads belongs in `activityStarted`, which runs before `intercept.onActivity`. ### onRow: watch rows arrive [#onrow-watch-rows-arrive] `onRow(row, plan, ctx)` lets you see each row of a result on its way to your code, and `row` is one of those plain row objects. Prisma ORM calls it once for every row as it reads the result, before your `await` on `.all()` or `.first()` resolves, so you can count rows, sample them, or throw to stop the query part way through. If you throw, your `await` rejects with that error and you get no rows at all, not the rows read so far. That is what `budgets` does when a query returns more rows than its `maxRows` budget allows. `onRow` does not run on a statement that returns no rows, and it does not run for rows that an intercept handler answered. ### activityEnded: observe the finished activity [#activityended-observe-the-finished-activity] `activityEnded(activity, result, ctx)` is for recording what happened once the work is over. Prisma ORM calls it once at the end of every activity, whether it succeeded or failed, so check `result.kind` first if you only care about statements. For a statement, `result.outcome` is `'succeeded'`, `'failed'`, or `'stopped'` when your code stopped reading the rows part way through. `result.latencyMs` is how long it took, and `result.source` is `'driver'` for a statement the database answered and `'middleware'` when an intercept handler answered it. `result.returns` says which of the two counts is there: `result.rowCount`, how many rows came back, when it is `'rows'`, or `result.stats.affectedRows`, how many rows the statement changed, when it is `'stats'`. There is no `result.stats` on a write that failed. A statement that fails before it reaches the database, in `beforeCompile`, `beforeEncode` or while its values are encoded, also ends, with `outcome: 'failed'`, `latencyMs: 0` and `source: 'driver'`. A middleware that counts statements or measures latency checks `result.outcome` to leave those out. For a transaction, `result.outcome` is `'succeeded'` when its `commit()` or `rollback()` resolved and `'failed'` when it rejected, so a transaction that rolled back as you asked ends `'succeeded'`. Timing, logging, and latency budgets all belong in this hook. The SQL text is not on the activity; when you want to log it, keep it from `beforeEncode` in `ctx.state(key)`, as [Authoring custom middleware](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware#keep-state-for-one-statement) shows. ### activityFinalized: act once the effects are final [#activityfinalized-act-once-the-effects-are-final] `activityFinalized(activity, result, ctx)` is the last hook of every activity. It runs once, when the activity's effects are final. For a statement inside `db.transaction(...)`, that is after the transaction commits or rolls back, so each statement of the transaction gets its call then, not when the statement itself finished. The statements are finalized first, in the order they started, then the transaction itself. For a statement outside a transaction, it runs right after `activityEnded`. `result.outcome` says what happened: `'committed'` when the transaction committed, or the statement outside a transaction succeeded; `'rolled-back'` when the transaction rolled back; and `'unknown'` when Prisma ORM cannot tell whether the writes landed, for example when a statement outside a transaction failed, or a statement inside a committed transaction failed. Use this hook for work that must not happen for a write that did not last, such as publishing an event or removing a cache entry, and treat `'unknown'` like `'committed'` when a committed write must not be missed. Check `activity.kind === 'statement'` if you act on statements only, because transactions and ORM calls are finalized too. Inside a transaction, the hooks run while the transaction's connection is still checked out, so keep them short. Do not send a query on that connection, and do not wait on another query through the same client: if every connection of the pool is busy, it never finishes. Prisma ORM passes an error thrown from `activityFinalized` to the client's log and does not pass it to your code. Give the client a `log` option, such as `log: console`, to see it. ## What ships built in [#what-ships-built-in] `@prisma/orm-postgres` already contains [lints](https://www.prisma.io/docs/orm/middleware/built-in-lints), which blocks risky query shapes, and [budgets](https://www.prisma.io/docs/orm/middleware/built-in-budgets), which caps row counts and reports slow queries, so you can register either one without installing anything else. Middleware that ships as its own package is an extension like any other, and the [extension directory](https://www.prisma.io/extensions) lists those, including middleware written by the community: | Name | What it adds | Package | Databases | By | | --------------------------------------------------------------------- | ------------------------------------------------------------------------------ | ---------------------------------------- | ---------------------------------- | ------ | | [Cache middleware](https://www.prisma.io/extensions/middleware-cache) | Serve repeated reads from an in-memory or pluggable cache, opted in per query. | `@prisma/orm-extension-middleware-cache` | PostgreSQL, SQLite, MySQL, MariaDB | Prisma | "Opted in per query" in that row means nothing is cached until you say so on one particular read, which you do by attaching `cacheAnnotation({})` to it. How long a cached entry lives is [set on the store](https://www.prisma.io/docs/orm/middleware/built-in-cache#options), not on the annotation. On the ORM API the annotation goes in a callback you pass after the arguments. That callback receives a `meta` object whose `annotate` method attaches the annotation to that one call: ```ts title="src/prisma/get-user-cached.ts" import { cacheAnnotation } from '@prisma/orm-extension-middleware-cache'; import { db } from './db'; export async function getUserCached(id: number) { return db.orm.public.User.first({ id }, (meta) => meta.annotate(cacheAnnotation({})), ); } ``` [Opt a query in](https://www.prisma.io/docs/orm/middleware/built-in-cache#opt-a-query-in) shows the same annotation on a query you built with the SQL query builder. If none of them do what you need, the [authoring guide](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware) builds a working query logger step by step. Once your own middleware is on npm, [submit it to the directory](https://www.prisma.io/extensions/submit) so other Prisma ORM users can find it. ## Which databases a middleware runs on [#which-databases-a-middleware-runs-on] Prisma ORM sorts the databases it supports into two families, SQL and MongoDB, and a middleware cannot always work on both. The `familyId` key next to `name` is where a middleware says which family it was written for, and a middleware that leaves `familyId` out runs on either. - `budgets` and `lints` declare `familyId: 'sql'`. They register on PostgreSQL and are rejected on MongoDB. - The cache declares no `familyId`, so a MongoDB client accepts it too. It caches only reads you opt in, and a MongoDB read has no way to be opted in yet, so on MongoDB it stores and serves nothing. If you register a middleware against a database it was not written for, that client throws at its first query (or at `connect()`, if you call it), before anything reaches the database. The error's `code` is `RUNTIME.MIDDLEWARE_FAMILY_MISMATCH`. A middleware of your own that leaves `familyId` out can still be typed as `SqlMiddleware`, as long as you only ever register it on `postgres(...)`. To write one object that you register on a `postgres(...)` client and a `mongo(...)` client both, type it as `CrossFamilyMiddleware` instead, which you import from `@prisma/orm-postgres/components/runtime`. ## When a middleware or the driver throws [#when-a-middleware-or-the-driver-throws] When your hook throws from `activityStarted`, `beforeCompile`, `beforeEncode`, or an intercept handler, the whole statement fails before anything reaches the database, and your caller gets the error you threw. A throw from `onRow` also fails the statement, but by then the query has run: your caller gets your error and none of the rows, including the ones already read. Your own middleware can throw whatever error you like, as `noDeleteAll` throws a plain `Error`. `lints` and `budgets` throw an ordinary `Error` with a `code` property on it, so you catch them like any other error and read `code` to tell them apart. `budgets` throws two codes, `BUDGET.ROWS_EXCEEDED` and `BUDGET.TIME_EXCEEDED`, and the [lints](https://www.prisma.io/docs/orm/middleware/built-in-lints) page lists the codes `lints` throws. When the database driver is the thing that fails, Prisma ORM still calls `activityEnded` on every middleware, with `result.outcome` set to `'failed'`, so your logging sees failed statements as well as successful ones. A throw from `activityEnded` after a statement succeeded fails it, and your caller gets that error; every other middleware still receives its `activityEnded`. A throw from `activityEnded` while it is handling a failure cannot hide the real error: your caller still gets the failure the driver reported, and Prisma ORM passes your error to the client's log. ## Use with your agent [#use-with-your-agent] Projects created with `npm create prisma@latest` install [Prisma ORM skills](https://www.prisma.io/docs/ai/tools/skills#available-skills-for-prisma-8) for your coding agent. Prompts that work for middleware: - "Register the lints and budgets middleware on our Prisma ORM client with a 10k row budget." - "Add the cache middleware and opt the dashboard queries in with a 60 second time to live." - "Write a middleware that logs every query slower than 250ms." ## See also [#see-also] - [Authoring custom middleware](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware): build and test a query logger step by step - [Writing data](https://www.prisma.io/docs/orm/fundamentals/writing-data): the mutations that lints and budgets guard - [Built-in: budgets](https://www.prisma.io/docs/orm/middleware/built-in-budgets), [Built-in: lints](https://www.prisma.io/docs/orm/middleware/built-in-lints), [Built-in: cache](https://www.prisma.io/docs/orm/middleware/built-in-cache) - [Using extensions](https://www.prisma.io/docs/orm/extensions/using-extensions) for adding database features rather than wrapping queries ## Related pages - [Authoring custom middleware](https://www.prisma.io/docs/orm/middleware/authoring-custom-middleware): Build, register, and run your own Prisma ORM middleware, step by step, starting with a query logger. - [Built-in: budgets](https://www.prisma.io/docs/orm/middleware/built-in-budgets): The budgets middleware stops queries that read too many rows or take too long. - [Built-in: cache](https://www.prisma.io/docs/orm/middleware/built-in-cache): The cache middleware serves repeated reads from an in-memory store, opted in per query with a cache annotation. - [Built-in: lints](https://www.prisma.io/docs/orm/middleware/built-in-lints): The lints middleware inspects each query's structure before it runs and blocks or warns on risky shapes.