Next.js
permdock/next wires one explicit server factory into Server Components, Server Actions, Route Handlers and the client, built for Next.js 16.4 Cache Components and Instant Navigations.
Purpose
permdock/next is the full-stack adapter for Next.js 16.3 and later (the next peer range is >=16.3); its client half, permdock/next/client, holds PermissionBoundary. One createPermDock call in a server-only file returns the async server API (getPermDock, getPermission, requirePermission), a Server Component provider that serialises the snapshot for permdock/react, and a Route Handler for the batched decision endpoint. The design goals come from Next.js 16.3 Instant Navigations: permission-gated UI must arrive with the prefetch, never block a navigation, and refresh when roles change. The end-to-end pattern for a multi-org app is the Next.js Cache Components guide.
API
// src/permdock/server.ts (server-only)
import "server-only";
import { cookies } from "next/headers";
import { createPermDock } from "permdock/next";
import { policy } from "@/policy";
export const {
getPermDock,
getPermission,
requirePermission,
PermDockProvider,
permdockHandler,
} = createPermDock(policy, {
subject: async () => getUser(await cookies()),
tenant: async () => (await cookies()).get("org")?.value, // active tenant; accepted only when a membership matches
onDenied: () => redirect("/forbidden"), // runs on assert and requirePermission refusals
});The active tenant usually comes from the URL (app/[org]/...); a Server Component or Route Handler passes it explicitly with getPermDock({ tenant: params.org }), and the resolver above is the fallback for requests without a segment. Either way the value is a request, not a fact: core keeps it only when principal.memberships holds that tenant, otherwise tenant-scoped checks are denied with no-membership (tenancy).
// app/[org]/layout.tsx: never awaits; hooks under it answer pending until the snapshot streams in
import { PermDockProvider } from "@/permdock/server";
export default function Layout({ children }) {
return (
<PermDockProvider include={[permissions.post, permissions.billing]}>
{children}
</PermDockProvider>
);
}
// app/posts/[id]/page.tsx (RSC), a Server Action or a Route Handler
import { getPermDock, getPermission } from "@/permdock/server";
const permdock = await getPermDock();
permdock.assert(permissions.post.update, post);
const { allowed } = await getPermission(permissions.post.update, post);
await requirePermission(permissions.post.update, post, { tenant: org }); // forbidden() / unauthorized() on a denial
// app/api/permdock/route.ts: decision endpoint for closure grants
import { permdockHandler } from "@/permdock/server";
export const { POST } = permdockHandler();
// Client components import from permdock/react, never from permdock/next
import { usePermission, useTenant, useFilter, Protected } from "permdock/react";| Export | Role |
|---|---|
getPermDock | Async. Resolves the subject once per request through React.cache, awaits io(), builds the request-scoped PermDock, returns it. A redirect(), notFound() or other Next.js interrupt thrown by the subject or tenant resolver propagates (unstable_rethrow); any other throw makes the subject anonymous. Accepts { tenant } to set the active tenant from a route segment; (await getPermDock()).tenant(id) derives another instance without re-resolving. Safe to call from layouts, pages, Server Actions and Route Handlers; concurrent calls in one render share the same instance. |
getPermission | Async counterpart of usePermission: returns allowed, status: 'ready' and the Decision. getPermission(permission, data, { tenant }) checks in one tenant, as getPermDock({ tenant }) does. The server counterparts of the other hooks are methods on the instance: .tenants(), .memberships(), .heldRoles(), .assignableRoles(), .filter(), .actions(). |
requirePermission | Async guard for pages, Server Actions and Route Handlers; never a layout (where a check runs): requirePermission(permission, data?, { tenant?, intent?, version?, onDenied? }) resolves to the granted Decision. A refusal first runs onDenied, the call's or else the factory's, which may redirect() or throw to replace the default; then a denial calls unauthorized() when the subject is anonymous and forbidden() otherwise, so app/unauthorized.tsx or app/forbidden.tsx renders (both need experimental.authInterrupts). approval-required throws PermDockApprovalRequiredError with the replay-safe token, and a boundary failure throws PermDockValidationError, as assert does. on('denied') hooks and the sink still see the decision. Call it in the render path and await it: a try/catch around it swallows the interrupt unless the catch calls unstable_rethrow. |
protectAction | protectAction(permission, { input, args?, data?, tenant? })(handler, { after?, result? }?) wraps a Server Action that validates its argument, loads the row, decides and runs the handler, and resolves to { ok: true, value } or { ok: false, problem } (Server Actions). |
PermDockProvider | Server Component that never awaits. snapshot takes the promise from the app's 'use cache: private' loader around getSnapshot, so a prefetch carries it; without it the provider starts an uncached snapshot (optionally scoped with include, with tenant for the active tenant and tenants: 'all' to ship every membership's grants), and include or tenants next to snapshot is a type error. It renders the client PermDockProvider from permdock/react with snapshotPromise and every other React provider prop except the functions refreshOn, onSnapshot, onClear, fetch and verifier, which cannot cross from a Server Component to the client: snapshotUrl, approvals, tenant, headers, maxAge, approvalInterval and suspend pass through. defaults and messages pass as nodes and message records only (provider defaults). Add refresh triggers from a client component with useRefreshOn (refresh on events). endpoint on the factory or the provider defaults to /api/permdock; endpoint: false is snapshot-only: no permdockHandler route, and checks the snapshot cannot answer are denied with reason server-only (snapshot-only mode). The static shell renders around it, and hooks and <Protected> under it answer status: 'pending' instead of suspending, so they stay in the shell; suspend makes them suspend until the snapshot resolves. A subject resolver that throws yields the anonymous subject. Any other failure rejects the snapshot promise: hooks answer server-only, and with suspend the error reaches the nearest error boundary, so a redirect() from subject still redirects. Without snapshot it is not cached: for prefetchable permission UI, pass snapshot from the private-cache pattern below. |
getPermissions | await getPermissions({ edit: [permissions.post.update, post], publish: permissions.post.publish }, { tenant? }) decides every named check on one instance and returns frozen plain JSON, { [name]: { allowed, outcome, reason? } }, so an island can return it from 'use cache: private'. A check that throws denies its entry; an instance that cannot be built denies every entry. |
getSnapshot | await getSnapshot({ tenant?, include?, tenants?, omitAssignable?, omitStatic?, tags?, cacheLife? }) inside an app-owned 'use cache: private' function: builds the session's snapshot, then calls cacheLife(cacheLifeFor(snapshot, cacheLife)) and cacheTag(snapshotTag(sub), ...tags) in that scope. The app still writes the directive. Outside a cache scope it throws an error that names the directive. |
cacheLifeFor | cacheLifeFor(snapshot, { min, max, capToToken, now }) returns { stale } for cacheLife(): max (300). The proxy refreshes the session on every request, so the token stays ahead of the entry. capToToken: true caps it at the seconds until expiresAt, clamped to min (30), as bsb.cached() does; below min it returns the real remainder, so Next.js leaves a nearly expired snapshot out of prefetches. It reads issuedAt from the snapshot, not the clock. getSnapshot warns once in development when the result is under 300 seconds, and once more under 30 seconds, where Next.js leaves the entry out of every prefetch (a capToToken remainder under min is that case). |
permdockHandler | Returns POST (and GET for .well-known discovery) implementing the AuthZEN-shaped decision endpoint on top of the same subject resolver; also serves refresh({ tenant }) snapshot requests, answering from the subject's memberships. A batch over 256 evaluations is a 413 (Problem Details). |
tenant, memberships, customRoles, store, sink | The shared adapter options: how the active tenant is resolved, a MembershipSource, a CustomRoleSource, an ApprovalStore and a DecisionSink (adapters, extension interfaces). Every sink.write that returns a promise, and one sink.flush() per render, are handed to after(), so a serverless function stays alive until decision events are delivered; outside a request scope (tests, scripts) the sink behaves as in core. |
otel, wrap | otel takes (permdock) => withOtel(permdock, options) from permdock/otel. wrap is a PermDockWrap applied to each instance after otel and before the factory onDenied; build it with wrapPermDock so tenant(), team() and derive() stay wrapped (extend PermDock). pdp and webBotAuth are not options here: getPermDock has no Request to verify and no protect to decide remotely. A Route Handler that needs them uses permdock/server. |
Server Actions
protectAction(permission, { input, args?, data?, tenant? })(handler, { after?, result? }?) returns a Server Action that resolves to an ActionResult: { ok: true, value } or { ok: false, problem }, where problem is Problem Details. Use it when the client renders the refusal; use requirePermission when a refusal should render app/forbidden.tsx.
// app/[org]/quotes/actions.ts
"use server";
import * as v from "valibot";
import { protectAction } from "@/permdock/server";
export const approveQuote = protectAction(permissions.quote.approve, {
input: v.object({ org: v.string(), id: v.string() }),
data: ({ id }) => db.quote.find(id),
tenant: ({ org }) => org,
})(async ({ id }, { data }) => {
await db.quote.approve(id);
updateTag(`quote:${id}`);
return { total: data.total };
});
// client component
const result = await approveQuote({ org, id });
if (!result.ok) toast.error(result.problem.detail);The action runs these steps in order and stops at the first refusal:
| Step | Refusal |
|---|---|
args and input validate the arguments | 400 with issues and boundary: "action-input"; a symbol in an issue path becomes a string |
getPermDock with tenant(input, args) | 403 no-grant when a resolver throws |
data(input, args) loads the row | 404 for null or undefined; 403 validation when the loader throws |
The decision, resumed by { approval } | 401 for an anonymous subject, 403 for a denial, 403 approval-required with a token |
handler(input, { permdock, decision, data, args }), after, result | 500 with the permission key; the thrown error stays on the server |
args is a tuple of Standard Schemas, one per leading argument, validated before input: protectAction(permission, { args: [v.string()], input }) returns an action called as (org, input, { approval }?). An issue in an argument has the argument's position first in its path. The handler receives the validated tuple as context.args. after(decision, { …context, result }) runs once the handler returned, for an audit write or a cache tag; a throw from it is a 500. result(handlerResult, context) maps what the handler returned to the value the client receives. Both sit in the second argument of the applied wrapper because they take the handler's result type.
Next.js interrupts (redirect(), notFound(), request-time bailouts) from a resolver, the loader or the handler pass through unstable_rethrow; nothing else throws. An approval-required result carries problem.token; once an approver grants it, the client calls the action again with approveQuote(input, { approval: token }). The token is bound to the permission, the subject and the row, as on every adapter (approvals). On the client, useProtectedAction from permdock/react keeps the result, the approval handle and the retry.
Read and write intents
Every instance the factory builds has an intent. getPermDock, getPermission, getSnapshot, requirePermission and PermDockProvider default to read; protectAction always uses write. The intent matters only with claimsFirst(…, { onStale: 'reread', versions }): a read instance may judge the token from the shared version cache, at most maxStaleMs stale, and a write instance reads the version live (freshness and the version cache).
"use server";
export async function removeMember(input: FormData) {
const permdock = await getPermDock({ intent: "write" });
permdock.assert(permissions.member.remove);
// ...write, then evict and bust the caches
}React.cache keys the instance by tenant, intent and known version, so a page that renders with read and then checks with write builds two instances. await io() still runs before the subject is resolved, so the version cache never reads the clock during prerendering.
Known version
When the request has already read the user's authorization version, such as authzVersion from bsb.bootstrap(), pass it as version so a read instance skips the version read:
export const { getPermDock, protectAction } = createPermDock(policy, {
subject: async () => subjectFromBetterSupabase(await bsb.getClaims()),
version: async () => (await loadBootstrap()).authzVersion,
...permdock.sources(versions),
});loadBootstrap is the app's own bsb.bootstrap(options) call, the one its layout already awaits. version runs once per request through React.cache. getPermDock({ version }), getSnapshot({ version }) and requirePermission(…, { version }) override it for one call. Only read instances use it: protectAction and getPermDock({ intent: "write" }) read the version live, so a known version never lets a revoked role write. A reader that throws or answers anything but a non-negative integer reads the version as usual. tests/next/private-scopes.test.ts pins both.
PermissionBoundary
requirePermission replaces a whole segment with forbidden.tsx. When only part of a page is gated, and the rest should keep rendering, let the check throw and catch it with PermissionBoundary from permdock/next/client, a 'use client' entry built on catchError from next/error:
// app/[org]/quotes/[id]/page.tsx (Server Component)
import { PermissionBoundary } from "permdock/next/client";
<PermissionBoundary
denied={<p>Only staff can delete quotes.</p>}
approval={<ApprovalNotice />}
>
<Suspense fallback={null}>
{/* awaits getPermDock(), then permdock.assert(permissions.quote.delete, quote) */}
<DeleteZone params={params} />
</Suspense>
</PermissionBoundary>;
// approval-notice.tsx
("use client");
import { usePermissionBoundary } from "permdock/next/client";
export function ApprovalNotice() {
const state = usePermissionBoundary(); // { outcome, permission, token?, retry }
if (state?.outcome !== "approval-required") return null;
return (
<button onClick={() => state.retry()}>I have approval, try again</button>
);
}- It recognises
PermDockDeniedErrorandPermDockApprovalRequiredErrorby theirdigest(errors), which is the only part of a Server Component error that reaches the client in production. Every other error, andforbidden(),notFound()andredirect(), passes to the next boundary up. deniedrenders for a denial;approvalfor an approval request, defaulting todenied. Each is a React node, which a Server Component can pass, or, from a Client Component, a function of theusePermissionBoundary()state:approval={(state) => <RequestAccess token={state.token} />}.usePermissionBoundary()inside a fallback returns the permission key, the approvaltokenfor a request-access flow, andretry(), which re-fetches and re-renders the boundary's children, for example after the approval is granted or a role changes.- Put a
Suspenseinside the boundary: during server rendering an error goes to the nearestSuspense, and the boundary catches it when the client renders. - The boundary never decides; the check that threw did. Keep the enforcement in the Server Action as well.
Active tenant from a root segment
When the organization is the root segment (app/[org]/layout.tsx is the root layout), the getter next/root-params generates for it is already a tenant resolver, so deep components need neither props nor getPermDock({ tenant }):
import { org } from "next/root-params";
export const { getPermDock, getPermission, requirePermission } = createPermDock(
policy,
{ subject: async () => getUser(await cookies()), tenant: org },
);Root parameters are readable only in Server Components: in a Server Action or Route Handler the getter throws, the resolver yields no tenant, and tenant-scoped checks deny. Pass { tenant } explicitly there. With Cache Components, the root layout also needs generateStaticParams returning at least one value.
Active tenant from a slug
When the segment holds a slug (app/orgs/[org], /orgs/acme) and memberships hold tenant ids, tenantFromPath({ param, resolve }) reads the slug from the route's params and resolves it through the application's own store:
import { tenantFromPath } from "permdock/next";
export const orgTenant = tenantFromPath({
param: "org",
resolve: async (slug) => (await db.orgs.bySlug(slug))?.id,
});
// app/orgs/[org]/projects/route.ts
export async function POST(request: Request, { params }: RouteContext) {
const permdock = await getPermDock({ tenant: await orgTenant(params) });
permdock.assert(permissions.project.create);
}The id becomes the active tenant only when the subject holds a live membership there. A slug that resolve answers with null, a value that is not an id or a throw, a missing segment and a catch-all segment all ask for a tenant no membership holds: the instance has no tenant, never the factory's tenant, and tenant-scoped checks deny with no-membership. resolve is the only lookup; the slug itself is never used as an id.
Keeping the instance on the server
When the bundled React exposes experimental_taintObjectReference (Next.js with experimental.taint: true), createPermDock taints its options and every instance it builds, so a Server Component that passes either to a Client Component fails at render instead of leaking policy closures. Without the function the calls are skipped. createNextConfig() and both example configs set experimental.taint.
snapshot.subject.context reaches the browser as the instance holds it. getSnapshot({ context: ["plan"] }) and <PermDockProvider context={["plan"]}> keep only the named keys, and in development one warning names each key it dropped.
Measure the snapshot with permdock snapshot size: it prints bytes and gzip bytes for grants, static, conditions, vocabulary, tenants, assignable and subject, and doctor PD112 warns above 65,536 bytes for the role with the most grants. Each rendered PermDockProvider serialises its snapshot into the Flight stream (snapshot size). Providers and getSnapshot calls with equal options in one request share one snapshot promise, so nested providers write one copy: three nested providers without a snapshot prop wrote three copies before this memo and write one now (tests/next/provider-flight.flight.test.tsx counts copies in a real Flight stream). Options that differ in tenant, include, tenants, omitAssignable, omitStatic or context still write one copy each. Two snapshot props that hold separate promises write separate copies even when the snapshots are equal; pass one promise to nested providers. In development one warning reports an equal snapshot that came from a second promise in the same request. omitAssignable drops assignable on a page with no role editor, and omitStatic drops the grants of declared roles.
A PermDockProvider with no snapshot prop resolves the subject outside any cache scope and warns once in development; pass the snapshot from a 'use cache: private' loader. evaluator="lazy" renders the provider that loads the evaluator when a check needs it (14.5 KB initial instead of 21 KB gzip, tests/bundle/src/consumers.json).
useOffline retries only navigation, prefetch and Server Action requests; the snapshot store's own fetch settles to stale or server-only with no retry. Add onlineRefresh() from permdock/react to useRefreshOn to refresh the snapshot when the browser regains its connection.
Where a check runs
A layout does not re-render on navigation, and it does not stop the segments and parallel slots below it from rendering or from appearing in the RSC Payload (Next.js authentication guide). A layout therefore fetches and never decides: it renders PermDockProvider or calls getPermDock.
| Place | Check |
|---|---|
| A page | requirePermission |
| A leaf Server Component | getPermission, or assert under PermissionBoundary |
| A loader (the data access layer) | permdock.can and permdock.filter inside 'use cache: private', so rows the subject may not read never leave it |
| A Server Action or Route Handler | protectAction or requirePermission, on every call |
<Protected> and PermissionBoundary hide UI. Whatever a Server Component child renders is already in the RSC Payload, so filter rows in the loader, not behind a client <Protected>.
Segment configs and links
| Where | What | Why |
|---|---|---|
next.config.ts | cacheComponents: true, partialPrefetching: true, experimental.authInterrupts: true | A per-link prefetch carries the private-cached snapshot; requirePermission needs the interrupts |
| A synchronous layout whose shell must not render per request | export const ensureStatic = 'shell' | The build fails when a later change adds request-time rendering to the App Shell |
| Pages whose gated UI must paint on click | export const instant = true | Next.js validates in development that nothing on the way blocks; the gates come from the private cache |
| A shared layout that must block (it awaits request data outside a private cache) | export const instant = false on the layout, true on the pages below | Navigation between the pages stays validated while entry into the layout may block |
A rarely visited admin page that calls requirePermission at the top | export const prefetch = 'force-disabled' (and instant = false) | A runtime prefetch costs a server render per page view; the page checks access at request time anyway |
| Links to a resource page | <Link prefetch={true}> with the page's check in a 'use cache: private' function keyed on the resource id | The per-link prefetch resolves params and the private cache, so the gated actions render before the click |
A capability token in the URL (?token=) is URL data: a <Link prefetch={true}> resolves it in the prefetch, so every such link costs a server render, and a shared 'use cache' scope must never read it, because its output would be served to everyone. Verify the token inside 'use cache: private' or at request time, and link to token pages with the default prefetch.
Ship less client JavaScript
getPermission and requirePermission resolve in a Server Component and send no PermDock code to the browser. A page that only gates server-side needs no PermDockProvider. Client components under PermDockProvider answer every check on the first render, including Decision and row data, because permdock/next ships the evaluator with the provider (client weight).
Ship the role grants once
getSnapshot({ omitStatic: true }) and <PermDockProvider omitStatic> leave the grants of declared roles out of the snapshot. Generate bundle.ts with permdock generate (gen: { kinds: ["bundle"] }) and pass it as the bundle prop. The module starts with "use client", so the server component passes a client reference and the grants never enter the Flight stream of the page (static roles). apps/examples/next does this in both organisation layouts.
import { clientBundle } from "../permdock/bundle.ts";
<PermDockProvider snapshot={snapshot} bundle={clientBundle}>
{children}
</PermDockProvider>;Why an explicit factory file and not a Next plugin
The next.config.ts plugin (createPermDockPlugin) exists only as a build hook for permdock collect; it never wires runtime API. Runtime wiring lives in src/permdock/server.ts because:
- The file is the single import boundary between server and client. It can carry
import 'server-only', so a client component importinggetPermDockfails at build time (permix issue 49 leaked Prisma and Better Auth into the browser bundle through a middleware callback). - Types flow from the returned object, not from module augmentation. Two policies, or a test double, can coexist.
- Same shape in Vite, Expo and Hono: one file, one
createPermDock. See Next.js plugin.
warm
warm(policy) builds one anonymous instance, runs one can and answers { ok, ms }; it never rejects. Call it in instrumentation.ts after importing the policy, so the first request pays neither. See Shared cache.
import { warm } from "permdock/next";
import { policy } from "./src/policy";
export async function register() {
await warm(policy);
}Request lifecycle
-
A request or RSC render starts. The first call to
getPermDock,getPermissionorPermDockProviderruns thesubjectresolver insideReact.cache; the result is memoised for the rest of the render. Server Actions and Route Handlers get their own instance per invocation. -
Snapshot. For permission UI that should be prefetched, the app owns the cache directive. PermDock never adds
'use cache'and never readsheaders()orcookies()itself;getSnapshotruns the factory'ssubjectresolver and sets the lifetime and tag inside the app's private cache:// src/permdock/snapshot.ts import { getSnapshot } from "./server"; export async function loadSnapshot(org: string) { "use cache: private"; // cacheLife(cacheLifeFor(snapshot)): 300 s, so the App Shell and a per-link prefetch carry it // cacheTag(snapshotTag(sub), ...tags): permdock:<sub>, or permdock:anon return getSnapshot({ tenant: org, include: [permissions.post] }); } // app/[org]/layout.tsx: synchronous, so the layout itself is static import { PermDockProvider } from "./server"; export default function Layout({ children, params }) { return ( <PermDockProvider snapshot={params.then(({ org }) => loadSnapshot(org))}> {children} </PermDockProvider> ); }Without the factory, call
snapshotFor(policy, user, { tenant })and setcacheLife(cacheLifeFor(snapshot))andcacheTag(snapshotTag(user?.id))yourself, asgetSnapshotdoes. The tenant is part of the cache key because it is an argument, so/acmeand/globexshells carry different snapshots; a subject that does not belong to the segment's tenant gets an empty tenant scope, never another tenant's grants.'use cache: private'caches per browser session, so session-derived output may join a prefetch.paramsis URL data, which the shared App Shell never holds, so a snapshot keyed on[org]arrives through a<Link prefetch={true}>. Anything that readscookies()without it must render behind aSuspenseboundary or the navigation blocks. -
Guards resolve from the shell. Client
ProtectedandusePermissionanswer from the prefetched snapshot, so a link to an admin page paints on click. Data-dependent checks (getPermission(permissions.post.update, post)wherepostcomes from the database) sit underSuspenseand stream. -
Mutations. A Server Action calls
protectAction,(await getPermDock({ intent: 'write' })).assert(...)orawait requirePermission(..., { intent: 'write' }), performs the write, thenupdateTag(snapshotTag(user))(the tag your loader set) if the write changed roles, memberships or custom roles, which invalidates the private cache and the client refetches. A Route Handler, such as a billing webhook, an entitlement webhook or a revocation-counter bump, usesrevalidateTag(tag, { expire: 0 })instead, becauseupdateTagworks only in Server Actions. NotrevalidateTag(tag, 'max'): stale-while-revalidate would keep serving the revoked grant for one more visit.refresh()is for a Server Action that changed nothing cached but must repaint the acting browser. A role-assignment action additionally checkspermissions.member.assignRoleand that the new role is inpermdock.assignableRoles()before writing (tenancy). -
Closure grants.
usePermissionposts batchedevaluationstoapp/api/permdock/route.ts;permdockHandlerresolves the same subject, validates the posted data at the boundary and answers. -
Segments that must not be prefetched with permission UI export
instant = false(see segment configs).
OpenAPI
Next.js has no built-in spec generator, so permdock/next has no in-process OpenAPI hook. The recipe is a producer plus PermDock's Overlay:
- next-openapi-gen scans
app/api/**/route.ts, generates anoperationIdper handler, and scaffolds Scalar as the docs UI. permdock openapi emit --kind overlaywritespermdock.overlay.jsonwithsecuritySchemes, per-operationsecurityandx-permdock-*for every handler that callsgetPermDock().assert(...)or is wrapped bypermdockHandler(CLI: openapi).- next-openapi-gen's
overlay.applymerges the Overlay before writing the spec, so Scalar, any Arazzo files it compiles, and SDK generators such as@hey-api/openapi-tssee the applied description.
// openapi-gen.config.ts
export default defineConfig({
openapi: "3.2.0",
overlay: { apply: ["./permdock.overlay.json"] },
});permdock openapi emit --doc public/openapi.json --kind overlay --out permdock.overlay.json --check # CI
pnpm exec openapi-gen generatenext-openapi-gen accepts Overlay 1.0 to 1.2, so this recipe is where --overlay 1.2 (the pinned Overlay 1.2 draft with reusable actions, OpenAPI Overlay) can be used first; the default 1.1 output works identically.
Rules: operationId is the join key, and --check fails on a handler without one. Do not use next-openapi-gen's @auth JSDoc tag or authPresets on handlers PermDock covers; two sources of security on one operation is the failure mode the recipe exists to avoid. PermDock owns security; the producer owns paths and schemas. The Overlay is the documented default here because the description is generated on every build (Overlay).
MCP route
A Next.js app exposes an MCP server as a route handler through mcp-handler; permdock/mcp guards it with the same policy and the same subject resolver the rest of the app uses (MCP adapter, Hosting). This is the route the PermDock Cloud template on the Vercel Marketplace exposes (Cloud adapter).
// app/api/mcp/route.ts
import { createMcpHandler, withMcpAuth } from "mcp-handler";
import { createPermDock } from "permdock/mcp";
import { jwtSubjectResolver } from "permdock/jwt";
import { policy, permissions } from "@/permissions";
import { store } from "@/permdock"; // the same ApprovalStore the server components use
const verify = jwtSubjectResolver({
issuer: process.env.AUTH_ISSUER!,
audience: process.env.MCP_RESOURCE!,
});
const { protectServer } = createPermDock(policy, {
subject: (authInfo) => authInfo.extra?.subject ?? null,
store,
});
const handler = createMcpHandler((server) => {
const guarded = protectServer(server);
guarded.registerTool(
"delete_post",
{ permission: permissions.post.delete, inputSchema, data: loadPost },
deletePost,
);
});
const authed = withMcpAuth(
handler,
async (_req, token) => {
const subject = await verify(token);
if (!subject.principal) return undefined;
return {
token,
clientId: subject.claims.client_id,
scopes: subject.claims.scope?.split(" ") ?? [],
expiresAt: subject.expiresAt,
extra: { subject },
};
},
{ required: true },
);
export { authed as GET, authed as POST };Three rules. The subject comes from the verified bearer token, never from the app session: an MCP client is not a browser and carries no cookie. store must be durable on Vercel because each invocation is stateless (memoryApprovalStore() would drop a pending approval; permdock doctor warns). And the route is unrelated to permdockHandler(), which serves the client decision endpoint for the React side; the two can share one policy file and nothing else. mcp-handler also mounts on Nuxt, SvelteKit and Hono with the same file, so the recipe is not Next-specific.
What it validates and how denials surface
The shared adapter contract applies; the Next.js specifics:
includemust reference groups or resources from the policy's definition; unknown references are a type error.permdock/nextis server-only:createPermDockthrows when it runs wheredocumentexists. Keep it in a server-only file; the definition module stays client-safe.assertruns the layered handlers: the per-call handler, instanceon('denied')hooks, thenonDeniedfrom the factory. PermDock picks no default page behaviour: the app'sonDeniedcallsredirect()ornotFound(), and without oneassertthrowsPermDockDeniedError.PermDockApprovalRequiredErrorcarries the replay-safetokenso an approval page can call the action again.getPermissionnever throws a PermDock error; a failure to build the instance returns ano-grantdenial. Next.js interrupts fromsubjectortenant(redirect(),notFound(), request-time bailouts) pass through, as fromgetPermDock.requirePermissionthrows only the Next.js interrupts and the twoasserterrors above.- Route Handlers using
permdockHandleranswer with Problem Details; client components behave as in React. - The subject always comes from the factory's
subjectresolver;getPermDockandrequirePermissionaccept only atenant, anintentand a knownversion. A Route Handler authenticated by a bearer token instead of cookies usespermdock/serverwith a token resolver. The active tenant stays explicit (getPermDock({ tenant }), thetenantprop, or thetenantresolver); PermDock never reads a[org]segment on its own. Only the App Router is supported.
Next.js 16.4 functions
How permdock/next relates to each function in the Next.js functions reference. "Adapter" means permdock/next calls it; "app" means the app calls it next to PermDock.
| Function | Who | Use |
|---|---|---|
io | adapter | Awaited before the instance is created, because decisions read the clock (membership and token expiry). It suspends a prerender without blocking prefetches and resolves at once inside a cache scope |
connection | never | It would hold every permission check until a real request, which blocks prefetches |
prefetch(), navigation() | app | Defer an expensive private island out of the App Shell (prefetch()) or out of every prefetch (navigation()); a gated region whose snapshot must paint on click stays above both |
after | adapter | Keeps sink writes and flush() alive after the response |
unstable_rethrow | adapter | Lets redirect() and other interrupts from the subject and tenant resolvers through |
forbidden, unauthorized | adapter | requirePermission on a denial |
cookies, headers | app | Read by the app's subject resolver or inside the app's 'use cache: private' loader; PermDock never calls them |
cacheLife, cacheTag | app | cacheLife(cacheLifeFor(snapshot)) and cacheTag(snapshotTag(sub)) inside the app's private cache |
updateTag | app | In the Server Action that changed roles, memberships or custom roles |
revalidateTag | app | In Route Handlers (webhooks), with { expire: 0 } |
refresh | app | Server Actions only; other members' browsers need an app signal that calls router.refresh() |
next/root-params | app | The generated getter is a tenant resolver (above) |
generateStaticParams | app | Required for a root segment under Cache Components |
notFound, redirect, permanentRedirect | app | notFound() hides a row the subject may not read; redirect() from onDenied |
catchError | adapter | PermissionBoundary in permdock/next/client (above) |
useOffline | app | An offline badge; snapshot-backed <Protected> and usePermission keep answering offline |
useRouter, useParams, usePathname, useSearchParams, useSelectedLayoutSegment(s), useLinkStatus | app | Plain navigation UI; never a source of subject or tenant facts |
unstable_cache, unstable_noStore, revalidatePath, fetch, draftMode | not relevant | 'use cache' and tags replace them; no decision makes a network call |
generateMetadata, generateImageMetadata, generateSitemaps, generateViewport, ImageResponse, NextRequest, NextResponse, userAgent, useReportWebVitals | not relevant | No permission surface; permdockHandler speaks the standard Request and Response |
Plain Node
permdock/next and permdock/next/client also load without a bundler: in Vitest, which runs dependencies as plain Node ES modules, and in Node scripts. next publishes no exports map, so the entries import next/cache.js, next/server.js and next/error.js with their file extension. next/navigation goes through the package import #next/navigation: under the react-server condition it stays the bare next/navigation, which Next.js maps to its server build, and elsewhere it resolves to next/navigation.js. Turbopack and webpack builds are unchanged.
Example app
apps/examples/next is a field-service app on named scopes: organizations (acme, globex) with staff roles, and customers inside them whose portal contacts see only their own quotes. It turns on cacheComponents, partialPrefetching, experimental.authInterrupts and experimental.useOffline.
src/permdock/server.tscallscreatePermDockfrompermdock/next. Code lives insrc/features/<domain>/, each with<domain>-queries.ts(starts withimport "server-only"),<domain>-actions.ts(starts with"use server"),<domain>-cache.ts(tags and invalidation, so queries and actions import one identity) andcomponents/.features/organizationhasloadSnapshot(private,cacheLifeFor),features/quotehasvisibleQuotes(private,permdock.filter) andquoteAccess(private, keyed on the quote id), andfeatures/memberhas the staff reads andchangeRole.lib/keepsstore.ts,latency.tsand theLoadedtype.- Feature components take ids, not
params: a page resolves the route at the boundary with{props.params.then(({ org }) => <QuoteList organization={org} />)}and types itself with the generatedPageProps<"/[org]/quotes">andLayoutProps<"/[org]">. A skeleton is the last export of its component's file. Reads that every write invalidates withupdateTagusecacheLife("max"). - The staff quote page wraps a request-time delete check in
PermissionBoundary: a member sees an approval notice with a retry button, a contact sees the denied fallback, and the quote itself keeps rendering. /[org]pages and the portal exportinstant = true;/[org]/settingsexportsprefetch = 'force-disabled'andinstant = falseand callsrequirePermission.- Quote links use
<Link prefetch={true}>; Server Actions callrequirePermissionand thenupdateTag. typedRoutesis on: a linkhrefis a template-literal type, not astring.
To check a route by hand, open the Next.js DevTools in next dev, select Navigation Inspector, turn on Pause on navigations, then refresh (the static shell) or click a link (the prefetched UI) and confirm the gated nav and actions are already there. Prefetching happens only under next start, so confirm the result with pnpm --filter @permdock/example-next build and start.
apps/examples/next-better-supabase is the same shape on Supabase sessions from better-supabase: /[locale]/[orgSlug]/... routes, staff roles in memberships, portal contacts through contacts.user_id, and the PermDock access-token hook and RLS helpers generated from one set of sources. The portal layout keeps endpoint={false}. Staff routes load the snapshot through getSnapshot with a subject that reads bsb.cached(), load the RLS-filtered rows through bsb.cached(), and tag both with snapshotTag(sub) (the recipe). src/proxy.ts refreshes the session. Quotes pages register WebMCP tools. pnpm --filter @permdock/example-next-better-supabase serve starts the native Supabase stack, not Docker.
Why
- The app owns every cache directive. Whether a value may be shared (
'use cache') or only per session ('use cache: private'), how long it lives and which tags bust it depend on where the app reads the session and what it mutates. A directive inside the package would hide those choices. Sopermdock/nextreturns plain values (cacheLifeFor,snapshotFor), and the example shows where'use cache: private'goes. io(), neverconnection(). Both keep the clock read out of the static shell, butconnection()waits for a real request and so blocks every prefetch of a gated page.io()suspends only the prerender and resolves at once inside a cache scope, which is where prefetchable permission UI lives.{ expire: 0 }, not'max', for revocations.'max'is Next.js's recommended stale-while-revalidate default for content; for a permission it means one more visit with the revoked grant.- No
scopeFromRootParams()export.next/root-paramsgenerates one getter per root segment, named after the folder, so a library cannot import it. The getter is already atenantresolver. PermissionBoundaryreads a digest. A client boundary sees a Server Component error in production only through itsdigest, and Next.js keeps a digest the error already carries. So the denial and approval errors set a stable one in core, where every adapter throws them, and the boundary parses it instead of matching messages or class names. It is an error boundary, not a gate: a second way to hide UI on a client-side check would compete with<Protected>.endpoint: false, not a missing route. Without the option, a closure grant read byusePermissionposts to/api/permdock, and an app that never added the route gets a 404 per check and apendingthat resolves to a denial over the network.falsemakes the choice explicit, keeps the browser from making the request at all, and gives the denial its own reason so a test can assert it.permdock doctorPD044 warns when a hook reads such a grant and neither a route nor an endpoint exists.protectActionreturns a result instead of throwing. A Server Action cannot set a status or a header, and an error thrown from one reaches the client in production as a digest without its message. A returnedActionResultkeeps the Problem Details body intact, so the client shows the samedetailandissuesan HTTP adapter would send. The approval token travels as the last argument for the same reason: there is noPermDock-Approvalheader to read.- Rendering reads, actions write. A page with Cache Components builds one instance per private cache scope, so a live version check per instance multiplies with every island. Rendering only decides what UI to show, and the write behind it is checked again, so the read entries accept a version up to
maxStaleMsold andprotectActionnever does. The entry picks the intent, not the permission, because the samepost.updateis a hint on a button and a gate in the action. requirePermissiontakesgetPermission's arguments. It is the interrupting member of theusePermission/getPermissionset, so moving between a soft check and a hard one changes the name only. A collection permission passesundefinedas the row before its options, aspermdock.can(permission, undefined, { scope })does.
Related standards
- AuthZEN: decision endpoint shapes served by
permdockHandler. - Problem Details: Route Handler denials.
- Standard Schema: boundary validation.
- OpenAPI 3.2 and OpenAPI Overlay: the next-openapi-gen recipe above.
- Design rationale: Next.js 16.3 Instant Navigations, the collect extraction model, explicit factory over a plugin, composing with the OpenAPI toolchain and the ecosystem index.
Last updated on