Skip to content

docs: add Prisma Next Middleware and Extensions sections#8008

Open
sorenbs wants to merge 11 commits into
mainfrom
docs/prisma-next-extensions-middleware
Open

docs: add Prisma Next Middleware and Extensions sections#8008
sorenbs wants to merge 11 commits into
mainfrom
docs/prisma-next-extensions-middleware

Conversation

@sorenbs

@sorenbs sorenbs commented Jul 3, 2026

Copy link
Copy Markdown
Member

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 of prisma-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 the prisma/prisma-next source at v0.14.0.

New pages

Middleware (/docs/orm/next/middleware/*, new section, 5 pages)

  • How middleware works: the hook model (beforeCompile, beforeExecute, intercept, onRow, afterExecute), the lifecycle, registration order semantics, what ships built in, error behavior, and family compatibility.
  • Built-in: budgets: row-count and latency ceilings from @prisma-next/sql-runtime (BUDGET.ROWS_EXCEEDED, BUDGET.TIME_EXCEEDED), with the three enforcement checkpoints and defaults.
  • Built-in: lints: structural query checks (LINT.DELETE_WITHOUT_WHERE, LINT.UPDATE_WITHOUT_WHERE, LINT.NO_LIMIT, LINT.SELECT_STAR), severity configuration, and the raw-SQL fallback heuristics.
  • Built-in: cache: opt-in per-query caching from @prisma-next/middleware-cache via cacheAnnotation({ ttl }), key derivation, scope behavior, and hit observability.
  • Authoring custom middleware: a complete slow-query-warning middleware (implemented and unit-tested in prisma/prisma-next examples/prisma-next-demo, see the companion PR there), the full hook/context reference, a beforeCompile query-rewriting variation, and gotchas.

Extensions (/docs/orm/next/extensions/*, new section, 1 page)

  • Using extensions: end-to-end pgvector setup (install, /control registration in prisma-next.config.ts, /runtime registration on the client, contract types, baseline migrations running CREATE 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

  • "Built-in: telemetry" is not written. The docs spec lists it (via @prisma-next/middleware-telemetry), but no telemetry middleware package exists in the product today; the only telemetry surface is the runtime.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.
  • No redirect from /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-extensions when the broader IA/redirect work (DR-8687) lands. /docs/orm/prisma-schema/postgresql-extensions is likewise left in place, flagged for SEO review (different concept now).
  • Middleware needs no v7 redirects: no old middleware/$use pages exist in the current docs (confirmed by search).
  • Cross-links: the per-extension "guide" links point at the GitHub package READMEs until the Guides section (DR-8689) exists, and capability detail is prose until the Capabilities page (DR-8680) exists. Swap those links when the sections land.
  • The pages first landed under /docs/next/* and were moved to /docs/orm/next/* in a follow-up commit on this branch; the previously flagged (index)/meta.json conflict with feat/prisma-next-reference no longer applies (this branch no longer touches that file).

Validation

  • pnpm --filter docs run lint:links — 0 errors
  • pnpm --filter docs run lint:spellcheck — 0 issues (added paradedb to the dictionary)
  • pnpm --filter docs run types:check
  • All runtime examples verified against prisma/prisma-next v0.14.0 source; the authoring example is committed and tested in the companion prisma-next PR

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Documentation
    • Added new ORM Next Middleware docs, including how middleware works, how to author custom middleware, and reference guides for built-in cache, budgets, and lints.
    • Added new ORM Next Extensions docs, including installation/registration instructions, capability requirements, and a first-party extensions catalog (e.g., pgvector, PostGIS, ParadeDB, Supabase, arktype-json).
    • Updated ORM Next documentation navigation to include the new Middleware and Extensions sections.
  • Chores
    • Updated spell-check terms to include “paradedb”.

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>
@vercel

vercel Bot commented Jul 3, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
blog Ready Ready Preview, Comment Jul 6, 2026 11:08pm
docs Ready Ready Preview, Comment Jul 6, 2026 11:08pm
eclipse Ready Ready Preview, Comment Jul 6, 2026 11:08pm
site Ready Ready Preview, Comment Jul 6, 2026 11:08pm

Request Review

@coderabbitai

coderabbitai Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It 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 reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review

Walkthrough

This PR adds Prisma Next docs for middleware and extensions, plus navigation metadata and a cspell entry.

Changes

Middleware and Extensions Documentation

Layer / File(s) Summary
Docs navigation wiring
apps/docs/content/docs/orm/next/meta.json, apps/docs/content/docs/orm/next/extensions/meta.json, apps/docs/content/docs/orm/next/middleware/meta.json
Registers the Middleware and Extensions sections and their page entries in the Prisma Next docs navigation.
Authoring custom middleware guide
apps/docs/content/docs/orm/next/middleware/authoring-custom-middleware.mdx
Adds a slowQueryWarning example and documents hook behavior, AST rewriting, short-circuiting, cross-family use, and gotchas.
Built-in budgets middleware page
apps/docs/content/docs/orm/next/middleware/built-in-budgets.mdx
Documents budgets registration, configuration, enforcement points, error shapes, and mitigation guidance.
Built-in lints and cache middleware pages
apps/docs/content/docs/orm/next/middleware/built-in-lints.mdx, apps/docs/content/docs/orm/next/middleware/built-in-cache.mdx
Documents lint rules, severities, raw-SQL fallback, and cache annotations, cache keys, runtime scope, and options.
Extensions documentation
apps/docs/content/docs/orm/next/extensions/using-extensions.mdx, apps/docs/cspell.json
Describes extension installation, control/runtime registration, capabilities, supported extensions, related links, and adds paradedb to spellcheck.

Estimated code review effort: 2 (Simple) | ~15 minutes

Possibly related PRs

  • prisma/web#7999: Also updates the Prisma Next docs navigation and related docs surface.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: adding Prisma Next Middleware and Extensions docs sections.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Jul 3, 2026

Copy link
Copy Markdown
Contributor

🍈 Lychee Link Check Report

35 links: ✅ 10 OK | 🚫 0 errors | 🔀 0 redirects | 👻 25 excluded

✅ All links are working!


Full Statistics Table
Status Count
✅ Successful 10
🔀 Redirected 0
👻 Excluded 25
🚫 Errors 0
⛔ Unsupported 0
⏳ Timeouts 0
❓ Unknown 0

@argos-ci

argos-ci Bot commented Jul 3, 2026

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Argos notifications ↗︎

Build Status Details Updated (UTC)
default (Inspect) ✅ No changes detected - Jul 6, 2026, 11:15 PM

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

📥 Commits

Reviewing files that changed from the base of the PR and between d406817 and 612f6b4.

📒 Files selected for processing (10)
  • apps/docs/content/docs/(index)/meta.json
  • apps/docs/content/docs/(index)/next/extensions/meta.json
  • apps/docs/content/docs/(index)/next/extensions/using-extensions.mdx
  • apps/docs/content/docs/(index)/next/middleware/authoring-custom-middleware.mdx
  • apps/docs/content/docs/(index)/next/middleware/built-in-budgets.mdx
  • apps/docs/content/docs/(index)/next/middleware/built-in-cache.mdx
  • apps/docs/content/docs/(index)/next/middleware/built-in-lints.mdx
  • apps/docs/content/docs/(index)/next/middleware/how-middleware-works.mdx
  • apps/docs/content/docs/(index)/next/middleware/meta.json
  • apps/docs/cspell.json

Comment thread apps/docs/content/docs/orm/next/extensions/using-extensions.mdx Outdated
Comment on lines +47 to +60
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 })],
});

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 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.mdx

Repository: 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.

Comment thread apps/docs/content/docs/orm/next/middleware/built-in-cache.mdx Outdated
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>
sorenbs and others added 2 commits July 3, 2026 16:11
- 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>
sorenbs and others added 2 commits July 3, 2026 16:48
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 ankur-arch left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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() blocks DELETE without WHERE (DELETE without WHERE clause blocks execution...) and lets an unbounded SELECT run with a warning, as documented.
  • budgets({ maxRows: 2 }) rejects an unbounded SELECT before the driver runs; a bounded query within budget passes.
  • createCacheMiddleware + cacheAnnotation({ ttl }) on the SQL builder serves the second identical read with result.source === 'middleware', exactly as the cache page describes.
  • A custom afterExecute middleware receives plan.sql, result.rowCount, result.latencyMs, and result.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`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

"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 })),
);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@ankur-arch

Copy link
Copy Markdown
Contributor

Pushed a revision (c33b786) applying the review feedback from this thread plus the session feedback on tone and teaching. Summary:

Animations

  • The pipeline scene's geometry is fixed: every box in the chain now shares one vertical center, so the request lane is a straight line and the tall-box empty band that read as broken layout is gone. The return lane and the cache-hit shortcut run through a clear band inside the endpoint boxes.

  • The dense text lifecycle line is now a stepped Code Hike animation (middleware-lifecycle), one concern per step. Designed from this Mermaid sketch:

    flowchart LR
      A[beforeCompile] --> L[SQL lowering] --> B[beforeExecute] --> E[param encoding] --> I[intercept] --> D[(driver)] --> R[onRow, per row] --> F[afterExecute]
      I -. cached rows, driver skipped .-> F
    
    Loading

Writing

  • how-middleware-works opens with what you can do in plain words, and the five-hook table is now five short subsections with a micro example where it helps.
  • "Runtime family" is explained in plain language: SQL family vs document family, and what familyId buys you (a startup error instead of a production query error).
  • authoring-custom-middleware is rewritten as a numbered hand-holdy guide in the house guide style: build a query logger, register it, run a query, see the output, then add a threshold option. The terminal output shown is captured from a live run against 0.14.0.

Validated fixes

  • The cache page's ORM opt-in now uses the facade path, verified with a cache hit on the second call:
    db.orm.public.User.first({ id }, (meta) => meta.annotate(cacheAnnotation({ ttl: 60_000 }))). This also resolves CodeRabbit's collections: {} finding and removes the db.connect() already-connected footgun.
  • Registration-order note added (logger before budgets), per CodeRabbit.
  • One finding from testing: ctx.log events are invisible today because postgres(...) accepts no log sink and does not forward one to the runtime. The authoring guide says so and logs via its own logger; the lints page notes that warn severities are therefore not observable yet, while error severities still block (verified: lints() blocks DELETE without WHERE, budgets({ maxRows }) blocks an unbounded SELECT).
  • Extension catalog links relabeled README and described as GitHub links, per CodeRabbit.

Validation: types:check clean, cspell 0 issues, both animations confirmed rendering (new viewBox present, lifecycle preset server-rendered). A heads-up for merge order: this branch and #8011 both touch concept-animation/flow-presets.ts, presets.ts, and index.tsx, so whichever lands second gets a small conflict; the index.tsx lookup fix here matches the shape #8011 uses.

@ankur-arch

Copy link
Copy Markdown
Contributor

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants