Skip to content

Docs

Connecting your API

How each screen of OSAGI Console gets its data from a route handler, the JSON contract to keep, and a checklist for swapping the mock API for your backend.

The UI talks to the server only through the route handlers in app/api/**. Each handler keeps a JSON contract and, in the template, reads the in-memory mock store. Replace the handler bodies with calls to your back-end and the screens keep working.

How a screen gets its data

  1. The page, a server component in app/(console)/<module>/page.tsx, checks access and renders the screen.
  2. The client screen requests /api/<module> with SWR: useModuleData() in lib/hooks/use-module-data.ts calls fetchModule() from lib/modules/client.ts and refetches at the module cadence (MODULE_REFRESH_MS in lib/modules/shared.ts). Polling pauses while the tab is hidden.
  3. The route handler checks the session, validates the query, reads the data and answers with JSON.

fetchModule() sends Accept: application/json, gives up after 20 seconds (MODULE_TIMEOUT_MS) and turns an error body into an Error with status and requestId, so a screen can tell "no access" from "the network failed". postModule() does the same for actions.

The route handler contract

Module routes share the helpers of lib/modules/http.ts:

ts
import { requireModuleApi } from "@/lib/modules/guard";import { errorResponse, jsonOk, newRequestId } from "@/lib/modules/http";
export async function GET(req: Request): Promise<Response> {  const requestId = newRequestId();  try {    await requireModuleApi(req, "sla"); // 401 or 403    const query = querySchema.parse(      Object.fromEntries(new URL(req.url).searchParams)    ); // 400 on bad input    const data = await loadFromYourApi(query); // the template reads the mock store here    return jsonOk(data, requestId);  } catch (error) {    return errorResponse(error, requestId);  }}
  • Success: the payload itself as JSON, without a wrapper, with Cache-Control: no-store and an X-Request-Id header.
  • Error: { "error": "<code>", "message": "<text for people>", "requestId": "<id>" } with the same header. Technical details go to the server log only.
StatuserrorWhen
400bad_requestThe query or the body failed its Zod schema
401authNo session
403forbiddenSigned in, but the permission or the section is missing
4xxyour codeA ModuleError(status, code, message, headers) thrown by the handler, such as 404, or 429 with Retry-After
500internalAnything unexpected

Note

Show the request ID to people when something fails: it points straight at the server log line.

OSAGI Backend Starter

The ready-made back-end of this console serves the same contract: build the console with NEXT_PUBLIC_API_BASE set to it and the connected modules go there, sign-in included, while the rest stay on the mock and say so. See Backend Starter.

Demo sandboxes

In the template, every demo visitor works in a copy of the mock store of their own, named by the osagi.demo_sandbox cookie the demo sign-in sets (lib/mock/sandbox.ts). Route handlers that read the mock store are wrapped in sandboxRoute(), server actions run through runAsUser(), and pages read the store after requireUser(). Once a handler calls your back-end instead of the mock store, it no longer needs sandboxRoute().

Mock store or your HTTP client

The mock layer lives in lib/mock and is imported only by route handlers, server components and server actions. Nothing in the browser depends on it.

PieceIn the templateReplace with
Records that people change (requests, tickets, docs, access)lib/mock/db.ts, seeded from lib/mock/fixtures/*, one copy per demo visitorYour database or services
Report snapshots (sales, SLA, workload, leads, marketing)Generated by lib/mock/snapshots/*Your reporting API or warehouse
AI assistant/api/chat streams prepared turns from runScriptedTurn() in lib/mock/agent.tsA model call, such as streamText() from the AI SDK
Uploads/api/upload checks the file signature and keeps metadata in memoryYour object storage
Health/api/health/live, /api/health/ready, /api/health/depsReal checks of your dependencies

Two common ways to connect:

  • Call your service from the handler. Keep the handler and its response shape and replace the mock read with fetch() to your API (service credentials stay on the server) or a database query. Parse the answer with the module schema, for example lib/modules/sales-schema.ts, so a contract drift fails loudly instead of showing zeros.
  • Forward as is. When your API already serves the same JSON, the handler checks the session and forwards the request. Keep the permission check in the console: a hidden menu item is not protection.

Move one route at a time: the others keep running on the mock.

Session and permissions

  • Demo session. lib/auth/demo.ts and readSession() in lib/auth/identity.kit.ts define it: a cookie set by /api/auth/demo (POST signs in, DELETE signs out). Replace readSession() with the session lookup of your auth provider and permsOf() with your permission loader; keep the exported surface.
  • requireUser(req, { module, action, scope }) runs in every page and route handler and throws AuthError with 401 or 403.
  • requireModuleApi(req, module) guards the report APIs: the data right <module>:view:all AND the section open for one of the user's groups.
  • proxy.ts redirects signed-out page visits to /login, answers API calls with 401 and refuses cross-site API writes. Keep it, and make it read your real session cookie instead of the demo one.
  • lib/auth-client.ts is the subset of the Better Auth client the sign-in screens use; swap it for the client of your provider.
  • /demo and GET /api/auth/demo sign anyone in as the demo owner. A production server keeps them shut unless OSAGI_DEMO_AUTH=on (they answer 404 and the demo cookie stops counting; OSAGI_DEMO_AUTH=off does the same anywhere); remove them or put them behind your own check when real sign-in replaces lib/auth/demo.ts.

The permission model is described in Permissions.

Checklist

  1. Pick a module and list its routes in app/api/<module>.
  2. Replace the mock reads with your client and keep the response shapes.
  3. Keep requireUser() or requireModuleApi() at the top of every handler.
  4. Run pnpm typecheck and pnpm test, open the screen and look for the X-Request-Id header in the network tab.