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
- The page, a server component in
app/(console)/<module>/page.tsx, checks access and renders the screen. - The client screen requests
/api/<module>with SWR:useModuleData()inlib/hooks/use-module-data.tscallsfetchModule()fromlib/modules/client.tsand refetches at the module cadence (MODULE_REFRESH_MSinlib/modules/shared.ts). Polling pauses while the tab is hidden. - 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:
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-storeand anX-Request-Idheader. - Error:
{ "error": "<code>", "message": "<text for people>", "requestId": "<id>" }with the same header. Technical details go to the server log only.
| Status | error | When |
|---|---|---|
| 400 | bad_request | The query or the body failed its Zod schema |
| 401 | auth | No session |
| 403 | forbidden | Signed in, but the permission or the section is missing |
| 4xx | your code | A ModuleError(status, code, message, headers) thrown by the handler, such as 404, or 429 with Retry-After |
| 500 | internal | Anything 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.
| Piece | In the template | Replace with |
|---|---|---|
| Records that people change (requests, tickets, docs, access) | lib/mock/db.ts, seeded from lib/mock/fixtures/*, one copy per demo visitor | Your 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.ts | A model call, such as streamText() from the AI SDK |
| Uploads | /api/upload checks the file signature and keeps metadata in memory | Your object storage |
| Health | /api/health/live, /api/health/ready, /api/health/deps | Real 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 examplelib/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.tsandreadSession()inlib/auth/identity.kit.tsdefine it: a cookie set by/api/auth/demo(POSTsigns in,DELETEsigns out). ReplacereadSession()with the session lookup of your auth provider andpermsOf()with your permission loader; keep the exported surface. requireUser(req, { module, action, scope })runs in every page and route handler and throwsAuthErrorwith 401 or 403.requireModuleApi(req, module)guards the report APIs: the data right<module>:view:allAND the section open for one of the user's groups.proxy.tsredirects 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.tsis the subset of the Better Auth client the sign-in screens use; swap it for the client of your provider./demoandGET /api/auth/demosign anyone in as the demo owner. A production server keeps them shut unlessOSAGI_DEMO_AUTH=on(they answer 404 and the demo cookie stops counting;OSAGI_DEMO_AUTH=offdoes the same anywhere); remove them or put them behind your own check when real sign-in replaceslib/auth/demo.ts.
The permission model is described in Permissions.
Checklist
- Pick a module and list its routes in
app/api/<module>. - Replace the mock reads with your client and keep the response shapes.
- Keep
requireUser()orrequireModuleApi()at the top of every handler. - Run
pnpm typecheckandpnpm test, open the screen and look for theX-Request-Idheader in the network tab.