Other frameworks
createAuthHandlers returns Web-standard objects: handlers.handle(request: Request) resolves to a Response, or to null when the path is not one of its routes. Fastify gets a ready-made adapter; for anything else you write a thin bridge. There is no Next.js adapter in version 0.x.
http bridge is type-checked against the SDK.The contract your bridge must honour
- Call
handlers.handle(request)for every request. When it returnsnull, continue with your own routing. - Build the
RequestURL from the registered origin,handlers.origin, followed by the path and query of the incoming request. The SDK does not read theHostheader, and your bridge should not either. - Forward every
Set-Cookieheader: useresponse.headers.getSetCookie(), because iterating headers merges them. - Give
POST /auth/backchannel-logoutits form body as a string (application/x-www-form-urlencoded, at most 16 KiB). Mount it outside any CSRF or session middleware: auth-service calls it with no cookies. - Protect your own routes with
handlers.getSession(request)orhandlers.requireSession(request), and answer failures witherr.toPublicJSON().
Hono
import { Hono } from "hono";
import type { AuthHandlers } from "@circle-rd/auth-ai/web";
import { ERR } from "@circle-rd/auth-ai";
declare const handlers: AuthHandlers;
const app = new Hono<{ Variables: { userId: string } }>();
app.all("/auth/*", async (c) => (await handlers.handle(c.req.raw)) ?? c.notFound());
app.use("/api/*", async (c, next) => {
const session = await handlers.getSession(c.req.raw);
if (!session) return c.json({ error: ERR.SES_001().toPublicJSON() }, 401);
c.set("userId", session.userId);
await next();
});
Hono's c.req.raw is already a Web Request, and the response is returned as is, with its cookies.
Express
import express from "express";
import type { AuthHandlers } from "@circle-rd/auth-ai/web";
declare const handlers: AuthHandlers;
const app = express();
app.use(
"/auth",
express.text({ type: "application/x-www-form-urlencoded", limit: "16kb" }),
async (req, res, next) => {
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
}
const response = await handlers.handle(
new Request(`${handlers.origin}${req.originalUrl}`, {
method: req.method,
headers,
...(typeof req.body === "string" ? { body: req.body } : {}),
}),
);
if (!response) return next();
res.status(response.status);
for (const [name, value] of response.headers) {
if (name !== "set-cookie") res.setHeader(name, value);
}
const cookies = response.headers.getSetCookie();
if (cookies.length > 0) res.setHeader("set-cookie", cookies);
res.send(await response.text());
},
);
Node http
This bridge uses nothing but node:http and the SDK.
import { createServer } from "node:http";
import type { IncomingMessage, ServerResponse } from "node:http";
import { AuthAiError } from "@circle-rd/auth-ai";
import type { AuthHandlers } from "@circle-rd/auth-ai/web";
declare const handlers: AuthHandlers;
const MAX_BODY_BYTES = 16_384;
async function readBody(req: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
let size = 0;
for await (const chunk of req as AsyncIterable<Buffer>) {
size += chunk.length;
if (size > MAX_BODY_BYTES) throw new RangeError("Request body too large");
chunks.push(chunk);
}
return Buffer.concat(chunks).toString("utf8");
}
async function toWebRequest(req: IncomingMessage): Promise<Request> {
const headers = new Headers();
for (const [name, value] of Object.entries(req.headers)) {
if (value !== undefined) headers.set(name, Array.isArray(value) ? value.join(", ") : value);
}
const method = req.method ?? "GET";
const hasBody = method !== "GET" && method !== "HEAD";
return new Request(`${handlers.origin}${req.url ?? "/"}`, {
method,
headers,
...(hasBody ? { body: await readBody(req) } : {}),
});
}
async function send(res: ServerResponse, response: Response): Promise<void> {
const headers: Record<string, string | string[]> = {};
for (const [name, value] of response.headers) {
if (name !== "set-cookie") headers[name] = value;
}
const cookies = response.headers.getSetCookie();
if (cookies.length > 0) headers["set-cookie"] = cookies;
res.writeHead(response.status, headers);
res.end(await response.text());
}
createServer(async (req, res) => {
try {
const request = await toWebRequest(req);
const auth = await handlers.handle(request);
if (auth) return await send(res, auth);
if (new URL(request.url).pathname === "/api/profile") {
const session = await handlers.requireSession(request);
return await send(res, Response.json({ sub: session.userId }));
}
res.writeHead(404).end();
} catch (err) {
if (err instanceof AuthAiError) {
// Only the code and the generic message leave the server.
return await send(res, Response.json({ error: err.toPublicJSON() }, { status: 401 }));
}
throw err;
}
}).listen(3000);
The catch block answers 401 for any AuthAiError to stay short; in a real service, map the codes you expect to the statuses in Web handlers and Fastify.
Next.js and other runtimes
The handlers need only Request, Response, fetch and Web Crypto, so a Route Handler or an edge function can call handlers.handle(request) and return its Response. The SDK has no Next.js adapter and this combination is not tested. Keep in mind that the stores must be shared by every instance (see Implement the stores), which rules out in-memory stores on serverless platforms.
Fastify backend
A complete backend-for-frontend on Fastify: sign-in, sessions, safe logging, same-origin protection, gateway and billing routes.
Protect an API
Verify auth-service Bearer tokens on your own API, require scopes, and publish protected-resource metadata so MCP and OAuth clients can find the provider.