docs: add Prisma Next Middleware and Extensions sections#8008
Conversation
Adds six pages to the Prisma Next docs collection under /next: Middleware (new section, 5 pages): - how-middleware-works: hooks, lifecycle, registration, built-ins - built-in-budgets: row-count and latency ceilings (BUDGET.* errors) - built-in-lints: structural query checks (LINT.* rules) - built-in-cache: opt-in per-query caching via cacheAnnotation - authoring-custom-middleware: complete slow-query warning example (implemented and tested in prisma/prisma-next examples/prisma-next-demo), hook/context reference, beforeCompile rewriting variation Extensions (new section, 1 page): - using-extensions: end-to-end pgvector setup (install, control and runtime registration, contract types, baseline migrations) plus the catalog table of available extensions All package names, import paths, option defaults, and error codes verified against the prisma/prisma-next source at v0.14.0. Uses "middleware" throughout (the retired "plugin" term does not appear). Note: the spec listed "Built-in: telemetry", but no telemetry middleware package exists in the product today; the shipped built-in from a separate package is @prisma-next/middleware-cache, documented instead. The client-extensions redirect from the ticket is deliberately not added: /orm/prisma-client/client-extensions still serves live Prisma 7 content, so redirecting it away is deferred to the broader IA work (DR-8687). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
WalkthroughThis PR adds Prisma Next docs for middleware and extensions, plus navigation metadata and a cspell entry. ChangesMiddleware and Extensions Documentation
Estimated code review effort: 2 (Simple) | ~15 minutes Possibly related PRs
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
Comment |
🍈 Lychee Link Check Report35 links: ✅ All links are working!Full Statistics Table
|
|
The latest updates on your projects. Learn more about Argos notifications ↗︎
|
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@apps/docs/content/docs/`(index)/next/extensions/using-extensions.mdx:
- Around line 83-93: The extension table links currently point to GitHub package
directories rather than documentation guides, so clarify the destination or
change the targets. Update the table rows in using-extensions.mdx and the
surrounding copy so readers understand these links leave the docs site, or
retarget them to the actual guide pages if those exist.
In
`@apps/docs/content/docs/`(index)/next/middleware/authoring-custom-middleware.mdx:
- Around line 47-60: The middleware registration order in the db runtime setup
is wrong: `budgets()` is placed before `slowQueryWarning()`, so `afterExecute`
can throw before the custom warning runs. Update the `postgres<Contract>`
configuration in the `db` setup so `slowQueryWarning({ thresholdMs: 250 })` is
registered before `budgets()` in the `middleware` array, while keeping `lints()`
first with the built-ins.
In `@apps/docs/content/docs/`(index)/next/middleware/built-in-cache.mdx:
- Around line 54-65: The ORM example currently creates orm with an empty
collections object, which leaves models.public without a User binding and makes
models.User.first unusable. Update the snippet to pass the generated collection
bindings into orm via the collections option, or change the example to use the
higher-level db.orm.User API if that is the intended flow; reference orm,
collections, models.public, and models.User.first to keep the fix aligned with
the existing snippet.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: b5064920-c168-40b9-a0a3-619a1b43ef4c
📒 Files selected for processing (10)
apps/docs/content/docs/(index)/meta.jsonapps/docs/content/docs/(index)/next/extensions/meta.jsonapps/docs/content/docs/(index)/next/extensions/using-extensions.mdxapps/docs/content/docs/(index)/next/middleware/authoring-custom-middleware.mdxapps/docs/content/docs/(index)/next/middleware/built-in-budgets.mdxapps/docs/content/docs/(index)/next/middleware/built-in-cache.mdxapps/docs/content/docs/(index)/next/middleware/built-in-lints.mdxapps/docs/content/docs/(index)/next/middleware/how-middleware-works.mdxapps/docs/content/docs/(index)/next/middleware/meta.jsonapps/docs/cspell.json
| Register it in the `middleware` array on the runtime setup, next to the built-ins: | ||
|
|
||
| ```ts title="src/prisma/db.ts" | ||
| import postgres from '@prisma-next/postgres/runtime'; | ||
| import { budgets, lints } from '@prisma-next/sql-runtime'; | ||
| import type { Contract } from './contract.d'; | ||
| import contractJson from './contract.json' with { type: 'json' }; | ||
| import { slowQueryWarning } from './slow-query-warning'; | ||
|
|
||
| export const db = postgres<Contract>({ | ||
| contractJson, | ||
| url: process.env.DATABASE_URL, | ||
| middleware: [lints(), budgets(), slowQueryWarning({ thresholdMs: 250 })], | ||
| }); |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
rg -n "afterExecute" "apps/docs/content/docs/(index)/next/middleware"Repository: prisma/web
Length of output: 3682
🏁 Script executed:
#!/bin/bash
set -euo pipefail
sed -n '20,150p' apps/docs/content/docs/(index)/next/middleware/authoring-custom-middleware.mdx
printf '\n---\n'
sed -n '1,220p' apps/docs/content/docs/(index)/next/middleware/how-middleware-works.mdx
printf '\n---\n'
sed -n '1,220p' apps/docs/content/docs/(index)/next/middleware/built-in-budgets.mdxRepository: prisma/web
Length of output: 201
🏁 Script executed:
#!/bin/bash
set -euo pipefail
FILE='apps/docs/content/docs/(index)/next/middleware/authoring-custom-middleware.mdx'
WORKS='apps/docs/content/docs/(index)/next/middleware/how-middleware-works.mdx'
BUDGETS='apps/docs/content/docs/(index)/next/middleware/built-in-budgets.mdx'
sed -n '20,150p' "$FILE"
printf '\n---\n'
sed -n '1,220p' "$WORKS"
printf '\n---\n'
sed -n '1,220p' "$BUDGETS"Repository: prisma/web
Length of output: 17491
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Find implementation sites for the middleware chain.
rg -n --hidden --glob '!**/node_modules/**' --glob '!**/dist/**' --glob '!**/build/**' \
"afterExecute|beforeExecute|middleware.*order|run.*middleware|execute.*middleware" \
.Repository: prisma/web
Length of output: 10112
🏁 Script executed:
#!/bin/bash
set -euo pipefail
# Narrow to likely runtime packages and inspect middleware execution code.
git ls-files | rg '(^|/)(runtime|middleware|sql-runtime|postgres/runtime|mongo/runtime)'Repository: prisma/web
Length of output: 700
Register slowQueryWarning() before budgets()
afterExecute runs in registration order, and budgets() throws on slow queries. With the current order, the custom warning can be skipped on the very queries this example is meant to surface.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In
`@apps/docs/content/docs/`(index)/next/middleware/authoring-custom-middleware.mdx
around lines 47 - 60, The middleware registration order in the db runtime setup
is wrong: `budgets()` is placed before `slowQueryWarning()`, so `afterExecute`
can throw before the custom warning runs. Update the `postgres<Contract>`
configuration in the `db` setup so `slowQueryWarning({ thresholdMs: 250 })` is
registered before `budgets()` in the `middleware` array, while keeping `lints()`
first with the built-ins.
These are ORM concept docs, so they belong in the Prisma Next ORM collection at /orm/next (next to the overview), not the getting-started collection at /next. Updates frontmatter urls, cross-links, and moves the sidebar wiring from (index)/meta.json to orm/next/meta.json. No redirects needed: the /next/middleware and /next/extensions URLs were never deployed to production. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- Extensions table: add Status and Guide columns; mark ParadeDB and Supabase as Experimental per their READMEs; open the catalog with an explicit invitation to build an extension (call for extension authors) - Correct the Supabase row and maturity note: the runtime export is a minimal descriptor that satisfies the pack-requirements check; the role-binding runtime (asUser/asServiceRole) lands in M2 per the package README, so the page no longer claims role-bound helpers - Overview built-ins table: budgets latency wording now says the latency budget raises BUDGET.TIME_EXCEEDED after execution rather than implying it prevents slow queries - budgets: document severities.latency as accepted by the options type but not read in v0.14 (behavior is runtime-mode-driven) - lints: document unindexedPredicate as a type-level key with no active rule in v0.14, and the raw-SQL fallback severity differences (select * escalates to error for raw plans) Not acted on, deliberately: the client-extensions redirect (still serving live Prisma 7 content; deferred to the DR-8687 IA work) and Guides/Capabilities cross-links (those pages do not exist yet; lint:links would fail on dead internal links). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
…examples The cache and authoring pages registered the full lints/budgets/cache chain in their setup snippets; each page now registers only the middleware it documents, with composition and ordering covered in prose pointing at the how-middleware-works chain example. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Two new ConceptAnimation flow scenes, using the same stepper/autoplay engine as the Compute docs: - middleware-pipeline (How middleware works): one query travelling app -> cache -> lints -> budgets -> database, with a step for the pre-driver hooks, the cache intercept short-circuit (chain edges drop out, dashed "cached rows" path returns early), and the onRow/afterExecute return lane - extension-planes (Using extensions): one package forking into the /control registration (schema types, baseline migration) and the /runtime registration (query ops, codecs), converging on PostgreSQL via db init and queries Both scenes have matching Code Hike text fallbacks in presets.ts. Verified in the dev server: light and dark themes, step transitions toggle the right nodes/edges, and every label fits its box (checked programmatically via getBBox against the box rects). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Lets the Claude Code preview tooling start the docs app (pnpm --filter docs exec next dev) on port 3105, leaving the default 3001 free for other local processes. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
ankur-arch
left a comment
There was a problem hiding this comment.
Ran the middleware examples against @prisma-next 0.14.0 on a live Postgres database (create-db) before reviewing, since these pages make strong behavioral claims. Everything substantive checks out:
lints()blocksDELETEwithoutWHERE(DELETE without WHERE clause blocks execution...) and lets an unboundedSELECTrun with a warning, as documented.budgets({ maxRows: 2 })rejects an unboundedSELECTbefore the driver runs; a bounded query within budget passes.createCacheMiddleware+cacheAnnotation({ ttl })on the SQL builder serves the second identical read withresult.source === 'middleware', exactly as the cache page describes.- A custom
afterExecutemiddleware receivesplan.sql,result.rowCount,result.latencyMs, andresult.source, and ORM queries flow through the same chain. - The ORM meta-callback opt-in works too (details inline).
- All five extension packages exist on npm at 0.14.0, and
@default(uuid())in the extensions schema example emits a valid contract.
The v0.14 honesty notes (severities.latency accepted but not read, unindexedPredicate never emitted) are a great touch. Two inline suggestions plus one optional consistency note below.
Optional: the Fundamentals pages (#8011) now end with a "Prompt your coding agent" section (copyable prompts referencing the scaffolded skills), and the docs-writer skill gained references/prisma-next.md codifying the shared conventions for the parallel section PRs, including keeping any Prisma 7 cutover redirects commented out in next.config.mjs until /orm/next becomes /orm. These sections are net new so no redirects apply, but the agent-prompt ending would fit these pages well.
| }); | ||
| ``` | ||
|
|
||
| Every query then passes through the chain: the ORM client, the SQL query builder, and raw SQL all execute through the same runtime, so one `middleware` array covers all of them. On MongoDB, pass the same option to `mongo(...)` from `@prisma-next/mongo/runtime`. |
There was a problem hiding this comment.
"raw SQL" here points at a surface readers cannot find from these docs. In 0.14 the user-facing raw surface is fns.raw fragments inside the SQL query builder (verified working, and now documented on the Fundamentals Advanced queries page). A standalone raw statement built with the db.raw tag is not executable through db.runtime().execute(...) today; I tested it and it throws inside parameter collection. Suggest either rephrasing to "raw SQL fragments (fns.raw)" or linking to the surface you mean, so readers do not go looking for a raw statement API that is not there yet.
|
|
||
| const user = await models.User.first({ id }, (meta) => | ||
| meta.annotate(cacheAnnotation({ ttl: 60_000 })), | ||
| ); |
There was a problem hiding this comment.
The simpler facade path supports the meta callback as well, verified against 0.14.0 with a cache hit on the second call:
const user = await db.orm.public.User.first({ id }, (meta) =>
meta.annotate(cacheAnnotation({ ttl: 60_000 })),
);Suggest using that form here instead of the manual db.connect() + orm({ runtime, context }) wiring, for two reasons. First, it matches the db.orm.public.<Model> surface every other Prisma Next page teaches, so readers do not meet a second wiring style on a built-in page. Second, the current example has a footgun: db.connect() throws Postgres client already connected if any query has already run on the client, which is likely when someone pastes this into an existing app. If the manual wiring is intentional (for example to show the runtime handle), a one-line caveat about the connect-once behavior would save readers a confusing error.
| { latencyMs: 2481, maxLatencyMs: 1000 } | ||
| ``` | ||
|
|
||
| In permissive mode, the same information is emitted through the runtime logger as a warning. To fix an unbounded-select violation, add a `LIMIT` to the query (`take(...)` on the ORM client, `.limit(...)` on the SQL query builder) or raise the budget deliberately. |
There was a problem hiding this comment.
Small cross-link opportunity: "add a LIMIT to the query (take(...) on the ORM client, .limit(...) on the SQL query builder)" can link to the Fundamentals pagination section (/orm/next/fundamentals/reading-data#sort-and-paginate) so the reader who just got blocked lands on the page that shows how to paginate properly.
…ing guide Revision per review feedback, with the middleware behavior re-validated against @prisma-next 0.14.0 on a live database: - Fix the pipeline animation geometry: all chain boxes now share one vertical center so the request lane is a straight line, the endpoint boxes are sized to host the return lane inside them, and the empty band that read as broken layout is gone. Step 1 no longer mentions raw SQL (there is no standalone raw statement surface; raw exists as fns.raw fragments inside the SQL query builder). - Replace the dense text lifecycle line with a stepped Code Hike animation (middleware-lifecycle) that walks beforeCompile -> lowering -> beforeExecute -> encoding -> intercept -> driver -> onRow -> afterExecute, one concern per step. Mermaid source in the PR discussion. - Rewrite how-middleware-works plainly: a what-you-can-do opener, the five hooks as short subsections instead of one dense table, ordering rules pulled out, and "runtime family" explained in plain words (SQL family vs document family, what familyId buys you). - Rewrite authoring-custom-middleware as a hand-holdy numbered guide in the house guide style: build a query logger, register it, run a query, see the real output (captured from a live run), then add an option. The hook and context reference follows the working example. Includes the registration-order note (logger before budgets, per CodeRabbit) and an honest note that ctx.log has no visible sink through postgres(...) yet, so the guide logs via its own logger. - built-in-cache: the ORM opt-in now uses the facade path (db.orm.public.User.first with the meta callback, verified with a cache hit), replacing the manual orm() wiring and its already-connected footgun. Addresses CodeRabbit's collections finding as well. - built-in-lints: note that warn severities are not printed anywhere today because the client does not accept a log sink yet; error severities still block. - built-in-budgets: cross-link the take() fix to the Fundamentals pagination section; drop the em dash. - using-extensions: catalog links labeled README and described as GitHub links (CodeRabbit). - Add "Prompt your coding agent" endings per the docs-writer skill conventions. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
Pushed a revision (c33b786) applying the review feedback from this thread plus the session feedback on tone and teaching. Summary: Animations
Writing
Validated fixes
Validation: |
|
Re-validated 2026-07-07 on a fresh Prisma Postgres database: lints blocks DELETE without WHERE, budgets blocks an unbounded SELECT and passes a bounded one, the cache serves the second annotated read with source 'middleware' through both the SQL-builder and the facade ORM path, and the authoring guide's query logger produces the exact output shown on the page. Also verified the family-agnostic claim on a local MongoDB replica set: createCacheMiddleware registers on the mongo client without a family mismatch and queries run through it. |
What this PR does
Adds the Middleware and Extensions sections to the Prisma Next ORM docs at
/docs/orm/next, per the middleware + extensions Linear tickets and section 5 ofprisma-next-user-docs-spec.md. The goal for this round is accuracy and crawlability: every package name, import path, option default, and error code was verified against theprisma/prisma-nextsource at v0.14.0.New pages
Middleware (
/docs/orm/next/middleware/*, new section, 5 pages)beforeCompile,beforeExecute,intercept,onRow,afterExecute), the lifecycle, registration order semantics, what ships built in, error behavior, and family compatibility.@prisma-next/sql-runtime(BUDGET.ROWS_EXCEEDED,BUDGET.TIME_EXCEEDED), with the three enforcement checkpoints and defaults.LINT.DELETE_WITHOUT_WHERE,LINT.UPDATE_WITHOUT_WHERE,LINT.NO_LIMIT,LINT.SELECT_STAR), severity configuration, and the raw-SQL fallback heuristics.@prisma-next/middleware-cacheviacacheAnnotation({ ttl }), key derivation, scope behavior, and hit observability.prisma/prisma-nextexamples/prisma-next-demo, see the companion PR there), the full hook/context reference, abeforeCompilequery-rewriting variation, and gotchas.Extensions (
/docs/orm/next/extensions/*, new section, 1 page)/controlregistration inprisma-next.config.ts,/runtimeregistration on the client, contract types, baseline migrations runningCREATE EXTENSION), a capabilities explainer, and the catalog table (pgvector, PostGIS, ParadeDB, Supabase, arktype-json) with honest maturity notes and a link to the call for extension authors.Both sections are wired into the sidebar via
orm/next/meta.json. "Middleware" is used throughout; the retired "plugin" term does not appear (verified it is also gone from the product's public API).Notes and deliberate deviations
@prisma-next/middleware-telemetry), but no telemetry middleware package exists in the product today; the only telemetry surface is theruntime.telemetry()accessor, which is not middleware. The built-in that actually ships from a separate package is the cache, documented instead. Flagging so the spec owner can reconcile./docs/orm/prisma-client/client-extensions. That URL (and children) still serves live Prisma 7 GA content; redirecting it to the Next section now would remove reachable docs. It maps cleanly to/docs/orm/next/extensions/using-extensionswhen the broader IA/redirect work (DR-8687) lands./docs/orm/prisma-schema/postgresql-extensionsis likewise left in place, flagged for SEO review (different concept now).$usepages exist in the current docs (confirmed by search)./docs/next/*and were moved to/docs/orm/next/*in a follow-up commit on this branch; the previously flagged(index)/meta.jsonconflict withfeat/prisma-next-referenceno longer applies (this branch no longer touches that file).Validation
pnpm --filter docs run lint:links— 0 errorspnpm --filter docs run lint:spellcheck— 0 issues (addedparadedbto the dictionary)pnpm --filter docs run types:checkprisma/prisma-nextv0.14.0 source; the authoring example is committed and tested in the companion prisma-next PR🤖 Generated with Claude Code
Summary by CodeRabbit