Backend
Fastify backend
A complete backend-for-frontend on Fastify: sign-in, sessions, safe logging, same-origin protection, gateway and billing routes.
This guide extends the Quick start into the shape of a real service. It assumes the application is registered with LiteLLM support on, a back-channel logout URI, and the machine scopes.
Configuration values
| Variable | Example | Purpose |
|---|---|---|
PUBLIC_URL | https://app.example.com | Public origin of your application. No trailing slash. |
AUTH_ISSUER | https://auth.example.com | auth-service URL. |
AUTH_CLIENT_ID | my-app | The application's client id. |
AUTH_CLIENT_SECRET | <client-secret> | Never commit it. |
AUTH_COOKIE_SECRET | <32+ random characters> | Seals the sign-in cookie. |
GATEWAY_URL | https://llm.example.com | The LiteLLM gateway, when used. |
These names are yours: the SDK reads no environment variable.
The server
import Fastify from "fastify";
import type { FastifyRequest } from "fastify";
import {
AuthAiError,
GrantManager,
MemoryGrantStore,
createAiClient,
createAuthClient,
} from "@circle-rd/auth-ai";
import { authPlugin, requireAuth } from "@circle-rd/auth-ai/fastify";
import { MemorySessionStore, createAuthHandlers } from "@circle-rd/auth-ai/web";
function env(name: string): string {
const value = process.env[name];
if (!value) throw new Error(`Missing environment variable ${name}`);
return value;
}
const publicUrl = env("PUBLIC_URL");
const origin = new URL(publicUrl).origin;
const auth = createAuthClient({
issuer: env("AUTH_ISSUER"),
clientId: env("AUTH_CLIENT_ID"),
clientSecret: env("AUTH_CLIENT_SECRET"),
redirectUri: `${publicUrl}/auth/callback`,
postLogoutRedirectUri: `${publicUrl}/auth/logout/callback`,
gatewayUrl: env("GATEWAY_URL"),
});
// In memory: fine for a demo or one instance. Use database stores in production.
const grants = new GrantManager({ auth, store: new MemoryGrantStore() });
const ai = createAiClient({ auth, grants });
const app = Fastify({
trustProxy: true,
logger: {
// The authorization code travels in the callback query string: log paths only.
serializers: {
req: (request: FastifyRequest) => ({
method: request.method,
path: request.url.split("?")[0],
}),
},
},
});
const handlers = await createAuthHandlers({
auth,
grants,
sessions: new MemorySessionStore(),
secret: env("AUTH_COOKIE_SECRET"),
ai, // adds /auth/wallet, /auth/wallet/stats and /auth/models for the frontend
onError: (error) => {
// Details belong in logs, never in responses.
app.log.warn(
{ error: error instanceof AuthAiError ? error.toJSON() : String(error) },
"auth handler error",
);
},
onSessionsEnded: (sessions) => {
app.log.info({ count: sessions.length }, "sessions ended");
},
});
await app.register(authPlugin, { handlers });
// State-changing API calls must come from this site.
app.addHook("preHandler", async (request, reply) => {
const mutating = request.method !== "GET" && request.method !== "HEAD";
if (!mutating || !request.url.startsWith("/api/")) return;
const requestOrigin = request.headers.origin;
if (requestOrigin !== undefined && requestOrigin !== origin) {
return reply.status(403).send({
error: { code: "SES_004", message: "Cross-origin request refused" },
});
}
});
const protect = requireAuth(handlers);
app.get("/api/models", { preHandler: protect }, async (request) => {
const { userId } = request.authSession!;
return ai.forUser(userId).gateway.listModels();
});
await app.listen({ host: "0.0.0.0", port: 3000 });
What each piece does
trustProxyonly matters for your own logging and client IPs: the SDK never reads theHostorX-Forwarded-*headers to build URLs. It builds them on the origin ofredirectUri.onErrorreceives the cause of every failed callback, every unexpected failure, and a failed grant revocation. The browser only ever sees the generic code. See Security model.onSessionsEndedfires after a sign-out or a back-channel logout: close WebSockets, drop per-user caches.- The
preHandlerhook applies theOrigincheck the SDK enforces only on/auth/logoutto your own state-changing routes.
Protecting routes
| Hook | Effect |
|---|---|
requireAuth(handlers) | 401 SES_001 when signed out; sets request.authSession otherwise. |
loadSession(handlers) | Sets request.authSession when signed in; null otherwise. |
Check entitlements on the server, in the route that does the work:
import { hasPermission } from "@circle-rd/auth-ai";
app.post("/api/reports", { preHandler: protect }, async (request, reply) => {
const { claims } = request.authSession!;
if (!hasPermission(claims, "reports", "write")) {
return reply.status(403).send({ error: { code: "FORBIDDEN" } });
}
return { created: true };
});
FORBIDDEN is an example of your own application's error code: the SDK registry has no authorisation code of that kind.
Serving the frontend
authPlugin only answers below basePath (/auth by default). Serve your static frontend however you like (for example @fastify/static); the browser calls /auth/me to learn who is signed in. See React app, Vue app and Vanilla browser.
Next
- Call the LiteLLM gateway and read billing.
- Implement the stores on your database.
- The Production checklist.