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 Report37 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
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.
…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. |
Per review: the diagrams carried too much text and did not land the concept. All three are redesigned from minimal Mermaid sketches (in the PR discussion) and rebuilt as three-to-five-box flow scenes with one-sentence captions: - middleware-pipeline: three boxes (Your app -> Middleware -> Database) and four steps: pass through, block, answer from cache, observe results. The middleware internals are one sub-line, not boxes. - middleware-lifecycle: the dense eight-row token table is replaced by a five-box flow of just the hooks in order (rewrite -> guard -> answer early -> per row -> observe), with the driver as an edge label between intercept and onRow. - extension-planes: four plain boxes (package -> config/db.ts -> PostgreSQL) with the migrations and queries as edge labels; the rows/chips text is gone. using-extensions now teaches by doing first: five numbered steps (install, register in config, register on client, use the type, apply and query), then the diagram as "How the pieces fit", then a rewritten plain-language Capabilities section (what the keys are for: failing at client construction and at db init, not mid-query). The catalog table drops the Status column and the long feature prose; names link to the READMEs and one line covers maturity. authoring-custom-middleware was re-run end to end on a fresh create-prisma project against a live Prisma Postgres database and the guide now mirrors that run exactly: complete file listings for both files a reader touches, the real two-line logger output (INSERT and SELECT with latency), a what-if-you-see-nothing line, the tested threshold behavior, and family selection folded in as step 5. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
Pushed 7357f84 addressing the diagram and guide feedback. Diagrams: redesigned from minimal Mermaid sketches, then rebuilt as small flow scenes with one-sentence captions. The pipeline is now three boxes and one idea: flowchart LR
app[Your app] --> mw["Middleware (cache · lints · budgets)"] --> db[(Database)]
mw -. cached rows .-> app
Steps: pass through, block (the arrow into the database disappears), answer from cache (dashed return, database skipped), observe results. The lifecycle replaces the eight-row text table with just the five hooks in order: flowchart LR
bc[beforeCompile<br/>rewrite] --> be[beforeExecute<br/>guard] --> ic[intercept<br/>answer early]
ic -- driver --> orow[onRow<br/>each row] --> ae[afterExecute<br/>observe]
The extensions diagram is four plain boxes, and it now comes after a concrete five-step example (install, register in config, register on client, use the type in the schema, apply and query): flowchart LR
pkg[extension package] --> cfg[prisma-next.config.ts] -- db init --> pg[(PostgreSQL)]
pkg --> rt[db.ts] -- queries --> pg
Wording: the Capabilities section is rewritten in plain language (the keys exist so failure happens at client construction and at db init, never mid-query), and the catalog table drops the Status column and the long feature prose; extension names link to the READMEs and one line covers maturity. Authoring guide, proven end to end: re-ran the whole guide on a fresh Validation: types clean, cspell clean. The concept-animation typing change here matches #8011's shape so the eventual merge stays trivial. |
…merged Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
|
Synced with main now that Fundamentals (#8011) is merged: the concept-animation conflict is resolved by combining both scene sets (the relationship diagrams from Fundamentals plus the simplified middleware, lifecycle, and extensions scenes from this PR) in one registry, and the sidebar orders Fundamentals before Middleware and Extensions. Added cross-links into the now-merged Fundamentals section (writing-data from the middleware overview, advanced-queries from the extensions page); the budgets page's pagination link now resolves too. Types clean, link check 0 errors. Merge-ready. |
CodeRabbit: bind endContractJson to the raw end-contract.json import in the filled editing example (verified the variant self-emits with identical hashes); restore the extensions cross-link now that #8008 is merged; re-add the closing braces the merge common-suffix folding dropped between the migration and middleware presets. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
* docs: add Prisma Next Migrations section Six pages under /docs/orm/next/migrations covering the full migration workflow: how migrations work, the migration graph, generating, editing, applying, and rollbacks/recovery. All commands, file layouts, and CLI outputs verified against prisma-next origin/main by running the flows end-to-end (plan, placeholder backfill, self-emit, apply, status, log, rollback, failure/atomicity behavior). Adds three ConceptAnimation presets (migration-loop, migration-graph, migration-rollback), temporary redirects from the Prisma 7 migrate pages that have clean equivalents, and cspell entries for migration terms. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: first review pass on migrations pages Fresh-eyes review as two personas (newcomer, evaluating expert); applied the top findings: define contract/emit/marker/attestation on first use, explain operation classes, de-jargon codecRef, standardize on "migration directory", fix a timestamp inconsistency, and stabilize the db-ref heading anchor. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: verification pass and full review of migrations pages Verified every runnable example against prisma-next origin/main (remaining fixtures, ref list, migrate --show, hash-prefix targeting, db verify, migration new, the rawSql sample compiled in a real scaffold). Two fixes from verification: softened the db verify claim to match its actual output, and added the real migrate --show path preview. Full review per house docs style: removed prose em dashes and filler, standardized terminology, added a MongoDB data-transform section with a link to the working retail-store example, moved the wiring-ceremony note next to the code it excuses, consolidated CI guidance (commit both files, check exit codes), and linked the db-ref explanation to one canonical home. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: address review; fix preset merge seam CodeRabbit: bind endContractJson to the raw end-contract.json import in the filled editing example (verified the variant self-emits with identical hashes); restore the extensions cross-link now that #8008 is merged; re-add the closing braces the merge common-suffix folding dropped between the migration and middleware presets. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: five-minute path, forward-reference pass, backlog polish The overview page now runs the whole loop inline: three commands with the verified plan and apply output and an explicit success signal, so a newcomer is productive before leaving page one. Swept all six pages for forward references: terms like ledger, marker, and contract space are now glossed or linked at first use instead of assuming later sections. Also links the graph page from the Prisma Next index bullet, links the contract to Data Modeling, and straightens the branch/merge lanes in the migration-graph animation. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: fix two list-count mismatches from later additions Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: fix animation color bleed and narrow step-1 emphasis User-reported: the migration-loop diagram intermittently painted "User {" in the accent color. Two causes: WAAPI fill-both animations persist on token spans React reuses across steps, so a wrap from the last step back to the first could keep painting the previous color onto a new token (fixed by cancelling subtree animations before each transition), and the step-1 emphasis spanned the whole contract line, reading as broken syntax highlighting (narrowed to the annotation arrow). Verified mid-transition and settled colors in the browser. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: make migration-loop step 3 self-explanatory User-reported: "# edited? recompile:" was too terse to parse. Step 3 now reads as review-the-pair (migration.ts = intent, ops.json = exact SQL) with an explicit conditional: only if you edit migration.ts, run it once to regenerate ops.json so the two stay in sync. Caption rewritten to match. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: clearer wording for the three-command walkthrough plan prepares SQL but does not run it; migrate applies and confirms; the closing note reads as one plain paragraph. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: explain why the graph matters, and that it is ignorable Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: add 30s migration-loop video to How migrations work Composed and rendered with HeyGen HyperFrames (HTML/CSS/GSAP, local render): idea → contract change → plan → review/apply → the new column in Prisma Studio → autocomplete against the new schema. CLI output in the video matches the verified outputs used across the section. Served from public/ (2.6 MB, same-origin per CSP media-src) and embedded at the bottom of "The commands". Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs: link Agent Skills from the coding-agent sections Every migrations page now opens its "Prompt your coding agent" section with the same line, linking /ai/tools/skills and phrased as "Ask your agent to:". Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(migrations): one concept per diagram, teachable file anatomy, skills catalog Per review: - The three migration animations are rebuilt as single-concept flow scenes with one-sentence captions, replacing the dense token animations: the loop is four boxes in a cycle (change, plan, review, apply), the graph teaches exactly one idea (states are nodes, migrations are edges, shown through a branch and merge), and rollback shows one thing (a new forward edge back to a previous state, history grows). The token-preset duplicates that FLOW_SCENES already shadowed (migration trio, middleware-pipeline, extension-planes) are removed, addressing the CodeRabbit shadowing note for the entries this stack introduced. - "What a migration is" becomes "What a migration contains": a three-file table first (the file you edit, the file Prisma runs, the history marker), then one short subsection per file with the package.json/package-lock.json analogy and the Git-commit-range reading of from/to. Less jargon, one idea per paragraph. - /ai/tools/skills gains an "Available skills for Prisma Next" section cataloging the twelve skills create-prisma installs (verified against a scaffolded project's skills-lock.json), with the install command for existing projects. Every migration page's "Prompt your coding agent" section now deep-links that anchor. - CodeRabbit: the editing example's raw-JSON import is renamed startContractJson so the deserialized/raw pair reads consistently. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(migrations): fold in live-validation findings Validated the whole section end to end on a fresh create-prisma app against a live Prisma Postgres database and a local MongoDB replica set. Everything documented works as written: the three-command loop, the file shapes (migration.json fields, ops.json precheck/execute/ postcheck with operation classes), every command in the tables, rollback with --from/--to and the destructive warning, the placeholder flow for backfills, and full MongoDB parity (same commands, same layout, marker in _prisma_migrations). Three findings from the runs are now on the pages: - The migration directory listing includes the *-contract.d.ts snapshot types, which are what type-check migration.ts. - After a rollback, the contract source still holds the change, so db verify reports a hash mismatch until you revert and re-emit; and the resulting cycle makes the next migration plan require an explicit --from (MIGRATION.NO_TARGET names the reachable states). - Adding an extension to an existing project can hit a contract-space layout violation on db init; one migration plan run materializes the extension's baseline migration and db init proceeds (verified with pgvector on Prisma Postgres, CREATE EXTENSION included). Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * docs(migrations): terminology aligned with the data contract page Style and coherence pass across the Prisma Next tree: - The intro no longer says "your contract is your schema", which contradicted the contract-authoring definition (contract = what you author, schema = the database's actual structure). Both sections now use the same distinction. - The generating tutorial drops a mislabeled link (the word "contract" pointed at the data modeling section) and a "we'll" opener. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Ankur Datta <64993082+ankur-arch@users.noreply.github.com> Co-authored-by: Nurul Sundarani <sundarani@prisma.io>
…risma#912) ## Linked issue n/a — companion example for the Prisma Next user docs **Middleware** section. The docs PR that embeds this example is [prisma/web#8008](prisma/web#8008); tracking for the docs work lives in the docs Linear project, and there is no framework ticket for this change. ## At a glance ```ts // examples/prisma-next-demo/src/prisma/slow-query-warning.ts export function slowQueryWarning(options?: SlowQueryWarningOptions): SqlMiddleware { const thresholdMs = options?.thresholdMs ?? 250; return { name: 'slow-query-warning', familyId: 'sql', async afterExecute(plan, result, ctx) { if (result.latencyMs <= thresholdMs) return; ctx.log.warn({ code: 'APP.SLOW_QUERY', message: `Query took ${result.latencyMs}ms (threshold: ${thresholdMs}ms)`, details: { sql: plan.sql, rowCount: result.rowCount, latencyMs: result.latencyMs, source: result.source, planExecutionId: ctx.planExecutionId, }, }); }, }; } ``` Before this PR, `prisma-next-demo` registered only built-in middleware (`cache`, `lints`, `budgets`); the repo had no example of authoring a middleware from scratch. ## Summary This PR ships the canonical custom-middleware example: a `slowQueryWarning` observer in `prisma-next-demo`, registered on the demo runtime and covered by offline unit tests. The new Prisma Next docs page "Authoring custom middleware" ([prisma/web#8008](prisma/web#8008)) embeds this file verbatim, so the doc example is code that compiles and has tests behind it. ## How it fits together 1. **The example** ([examples/prisma-next-demo/src/prisma/slow-query-warning.ts](examples/prisma-next-demo/src/prisma/slow-query-warning.ts)) is a plain object literal typed as `SqlMiddleware`, so contextual typing infers every hook's parameters and the example needs no deep type imports. It implements only `afterExecute` and warns through `ctx.log` when `result.latencyMs` crosses the threshold. 2. **The wiring** ([examples/prisma-next-demo/src/prisma/db.ts](examples/prisma-next-demo/src/prisma/db.ts)) registers it at the end of the existing chain, with a comment noting that cache hits flow through it too, reporting `source: 'middleware'`. 3. **The tests** ([examples/prisma-next-demo/test/slow-query-warning.test.ts](examples/prisma-next-demo/test/slow-query-warning.test.ts)) drive `afterExecute` directly, no database required: a real DSL `build()` supplies the plan's `ast` and `meta`, and a hand-built `SqlMiddlewareContext` captures `log.warn` events. Three cases: warns above the threshold, silent at the threshold, and the 250ms default. ## Reviewer notes - The built-ins wrap their middleware in `Object.freeze(...)` and annotate hook parameters explicitly; this example deliberately returns a plain literal instead, because the docs page teaches the minimal authoring shape and contextual typing from the `SqlMiddleware` return type keeps it fully typed. - The test constructs the context and result objects structurally (no casts); `db.contract` supplies a real contract and the plan's `ast`/`meta` come from a real DSL build, so the shapes stay honest to what the runtime passes. - The docs page in prisma/web#8008 embeds `slow-query-warning.ts` verbatim. If this file changes shape later, the docs page needs the same edit. ## Behavior changes & evidence - The demo runtime now logs an `APP.SLOW_QUERY` warning for any execution slower than 250ms, whichever surface issued it ([slow-query-warning.ts](examples/prisma-next-demo/src/prisma/slow-query-warning.ts), [db.ts](examples/prisma-next-demo/src/prisma/db.ts)). Evidence: [test/slow-query-warning.test.ts](examples/prisma-next-demo/test/slow-query-warning.test.ts). No behavior change outside `examples/prisma-next-demo`. ## Testing performed - `pnpm --filter prisma-next-demo typecheck` - `pnpm --filter prisma-next-demo exec vitest run slow-query-warning` — 3 passed - `biome check` on the three touched files (also enforced by lint-staged on commit) ## Skill update n/a — example-only change; no CLI, public API, config, or error-code surface changed. ## Alternatives considered - **Throwing on slow queries instead of warning.** The `budgets` built-in already demonstrates enforcement (`BUDGET.TIME_EXCEEDED`); the example's job is to show a pure observer, which is the more common authoring starting point, so it warns and never fails the query. - **Placing the example next to the rewriting-middleware integration test.** Kept in `examples/prisma-next-demo` instead, so the docs can link one runnable app that shows built-ins, an extension, and a custom middleware together, where users actually look first. ## Checklist - [x] All commits are signed off (`git commit -s`) per the [DCO](../CONTRIBUTING.md#developer-certificate-of-origin-dco). - [x] I read [CONTRIBUTING.md](../CONTRIBUTING.md) and the change is scoped to one logical concern. - [x] Tests are updated. - [ ] The PR title is in `TML-NNNN: <sentence-case title>` form — no framework Linear ticket exists for this companion-example work, so the title names the deliverable directly. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Added slow-query warning middleware to the Prisma Next demo. * Warnings are emitted when observed query latency exceeds a configurable threshold, with a built-in default. * **Tests** * Added offline unit tests covering warning emission, exact-threshold behavior, and the default threshold. * **Documentation** * Updated the Prisma Next upgrade instructions to note this example-only addition and that it requires no action from consumers. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Søren Bramer Schmidt <sorenbs@gmail.com> Signed-off-by: Alexey Orlenko's AI Agent <robot@aqrln.net> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> Co-authored-by: Alexey Orlenko's AI Agent <robot@aqrln.net>
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