@intelligo-dev/next
The Next.js adapter: the one Intelligo package that imports next/*, binding request context, auth routes and Route Handler guards.
Install
pnpm add @intelligo-dev/nextnext and better-auth are peers: the adapter binds into the copies your
application already has.
Use
Tell the framework where a request’s headers come from — once, from the composition root:
// lib/intelligo.ts
import {
setBackgroundTaskRunner,
setRequestContextSource,
} from "@intelligo-dev/core/request-context";
import { nextBackgroundTasks, nextRequestContext } from "@intelligo-dev/next";
setRequestContextSource(nextRequestContext);
setBackgroundTaskRunner(nextBackgroundTasks);nextBackgroundTasks hands the work the framework starts without awaiting it
— auth emails, a new workspace’s bootstrap, notification emails — to Next’s
after(), so a serverless host keeps the function alive until it finishes.
Mount Better-Auth’s HTTP handlers:
// app/api/auth/[...all]/route.ts
export { GET, POST } from "@intelligo-dev/next/auth";Guard a Route Handler. The wrapper resolves the caller first and answers a
failed check itself — 401 without a session, 403 without a workspace or
the role, with { "error": <code> } as the body. What the handler throws
propagates unchanged:
// app/api/invoices/route.ts
import { withRole } from "@intelligo-dev/next/route";
export const GET = withRole(
["owner", "admin"],
async (request, { workspace }) =>
Response.json(await listInvoices(workspace.id))
);withAuth needs only a session, withWorkspace an active workspace. Next’s
own second argument — a dynamic segment’s params — arrives third, typed by
the wrapper’s parameter (Next’s generated RouteContext<"/api/invoices/[id]">
fits there too):
// app/api/invoices/[id]/route.ts
export const DELETE = withWorkspace<{ params: Promise<{ id: string }> }>(
async (request, { workspace }, { params }) => {
const { id } = await params;
await deleteInvoice(workspace.id, id);
return new Response(null, { status: 204 });
}
);errorResponse(error) ends a handler’s catch for an error the route has no
answer of its own for. A typed error of the framework’s (a service’s
not_found, forbidden, invalid_input, a guard’s refusal) becomes its
status and { "error": <code> }; anything else is logged whole and answered
as a 500 whose body is { "error": "internal_error" }. The error’s message
never reaches the response:
import { errorResponse, withWorkspace } from "@intelligo-dev/next/route";
export const GET = withWorkspace(async (request, { workspace, user }) => {
try {
return Response.json(await conversations.getConversation(actor, id));
} catch (error) {
return errorResponse(error);
}
});A route that begins an execution answers a refused one with
executionRefusalResponse(run): 402 QUOTA_EXCEEDED for what the workspace
can fix by paying, 503 for what only the deployment can (MODEL_UNAVAILABLE,
BILLING_NOT_CONFIGURED, and SPEND_CAP_REACHED with Retry-After when a
daily cap resets). The engine’s reason stays in the log.
ActionResult<T> is the shape a Server Action returns to its form —
{ success: true, data } or { success: false, error } — shared by every
registry item’s actions:
import type { ActionResult } from "@intelligo-dev/next";actionFailure(scope, error, message) ends an action’s catch for an error
it has no copy of its own for. It logs the error itself under scope (stack
and cause; the logger takes credentials out of the text) and returns
message as the failure, so the error’s own text never reaches the form. A
caller the auth guard refused is not logged:
import { actionFailure } from "@intelligo-dev/next";
try {
await orders.cancel(id);
return { success: true, data: undefined };
} catch (error) {
if (isOrderError(error)) return { success: false, error: t(error.code) };
return actionFailure("orders", error, t("errors.generic"));
}Every route under withAuth, withWorkspace, withRole or withCronSecret
runs under its request’s id — the x-request-id it arrived with, or a new
one — so each line the handler and the code below it log carries
requestId.
contentSecurityPolicy(options) from @intelligo-dev/next/csp writes a
policy for scripts, styles, images, frames and form targets as a
Content-Security-Policy-Report-Only header: the browser reports what it
would block and blocks nothing, until you send the same value under the
enforcing name. It returns the { key, value } pair headers() in
next.config.mjs takes, allows the app itself by default, and takes the
hosts your pages use (script, connect, img, frame, formAction), a
per-request nonce, a reportUri and development. A source that is not
a scheme or a host throws:
// next.config.mjs
import { contentSecurityPolicy } from "@intelligo-dev/next/csp";
const reported = contentSecurityPolicy({
development: process.env.NODE_ENV !== "production",
img: ["https://lh3.googleusercontent.com"],
});The subpaths are separate so that binding the request context does not load
the configured Better-Auth server instance, and so that /csp, which imports
nothing, loads from a config file.
Why a package
Every other @intelligo-dev/* package has to be usable from a queue worker, a
Hono API, a test, or a product built on something that is not Next. Keeping
every next/* import in one package — and having an architecture test refuse
it anywhere else — is what makes that true.
Entry points
@intelligo-dev/next@intelligo-dev/next/auth@intelligo-dev/next/csp@intelligo-dev/next/route