# Access Control
Source: /docs/access-control
---
title: Access Control
description: Declare the roles callers hold and say who may call each route. Kizuna checks the caller's role before the handler runs.
---
The least settled part of kizuna. `Kizuna.roles` and `Kizuna.permissions` may change shape or be removed while v2 is in beta. Pin your version, and expect to rewrite what you build on them.
[Authentication](/docs/authentication) turns a credential into the caller. This page decides what that caller may do.
There are three levels, and each one adds to the one before it:
| Level | The route says | Enough when |
| ---------------------- | ----------------------------------- | -------------------------------------------------- |
| Identity only | `auth: 'member'` | Logged in is the whole question. |
| Roles | `roles: 'owner'` | Some routes are for some kinds of member. |
| Roles with permissions | `requires: { project: ['delete'] }` | What a role may do changes, or differs per member. |
Pick one and the examples follow:
## Declare who can call
An identity with a `context` and nothing else. Its guard, which you attach below, says who the caller is, and every route under it is open to every caller it accepts:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
})
.guard(/* below */);
```
```ts title="src/roles.ts"
export const roles = Kizuna.roles(['member', 'admin', 'owner']);
```
List every permission that exists, grouped by what it acts on, and build the roles from them. Anything not listed is denied, and `'all'` is every permission declared:
```ts title="src/permissions.ts"
export const permissions = Kizuna.permissions({
workspace: ['read', 'update', 'delete'],
project: ['create', 'read', 'update', 'delete', 'share'],
invite: ['send', 'cancel', 'accept'],
});
```
```ts title="src/roles.ts"
export const roles = Kizuna.roles(permissions, {
member: {
workspace: ['read'],
project: ['read', 'update'],
},
admin: {
workspace: ['read', 'update'],
project: ['create', 'read', 'update', 'share'],
invite: ['send', 'cancel'],
},
owner: 'all',
});
```
Put the roles on the identity whose callers hold them:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
roles,
})
.guard(/* below */);
```
That adds `role` to what the guard returns and what handlers receive, typed as `'member' | 'admin' | 'owner'`.
Put the roles on the identity whose callers hold them:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
roles,
})
.guard(/* below */);
```
That adds `role` to what the guard returns and what handlers receive, typed as `'member' | 'admin' | 'owner'`.
## Say who may call each route
Every route carries its own `auth`, so a route cannot be added without stating its rule, and public is an explicit `false`.
A route names the identity it accepts:
```ts title="src/routes/projects.ts"
export const projects = k.routes.projects({
listProjects: k
.route({
method: 'GET',
path: '/projects',
auth: 'member',
responses: {
200: z.array(ProjectSchema),
},
})
.handler(/* ... */),
deleteProject: k
.route({
method: 'DELETE',
path: '/projects/:id',
auth: 'member',
responses: {
204: z.void(),
},
})
.handler(/* ... */),
});
```
A route names the identity, and the roles it accepts:
```ts title="src/routes/projects.ts"
export const projects = k.routes.projects({
listProjects: k
.route({
method: 'GET',
path: '/projects',
auth: 'member',
responses: {
200: z.array(ProjectSchema),
},
})
.handler(/* ... */),
deleteProject: k
.route({
method: 'DELETE',
path: '/projects/:id',
auth: {
identity: 'member',
roles: 'owner',
},
responses: {
204: z.void(),
},
})
.handler(/* ... */),
});
```
A route names the identity, and the permission it requires. Who may call it follows from what each role holds:
```ts title="src/routes/projects.ts"
export const projects = k.routes.projects({
listProjects: k
.route({
method: 'GET',
path: '/projects',
auth: {
identity: 'member',
requires: {
project: ['read'],
},
},
responses: {
200: z.array(ProjectSchema),
},
})
.handler(/* ... */),
deleteProject: k
.route({
method: 'DELETE',
path: '/projects/:id',
auth: {
identity: 'member',
requires: {
project: ['delete'],
},
},
responses: {
204: z.void(),
},
})
.handler(/* ... */),
});
```
Members read, admins create projects and cancel invites, and only the owner deletes. Letting admins delete is one edit in `roles.ts`, and every route follows.
A public route says so:
```ts title="src/routes/health.ts"
export const health = k.routes.health({
getHealth: k
.route({
method: 'GET',
path: '/health',
auth: false,
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
A role or permission a route names must be one the identity declares, so a typo does not compile.
## Return the caller from the guard
The guard resolves the credential and returns the context:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
})
.guard(async ({ apiKey, params, deny }) => {
const membership = apiKey ? await findMembership(apiKey.value, params.workspaceId) : undefined;
if (!membership) {
return deny({
status: 403,
body: {
detail: 'Forbidden',
},
});
}
return {
userId: membership.userId,
workspaceId: membership.workspaceId,
};
});
```
The guard denies, here with `403`, before the handler. The handler reads the context under `auth.member`.
The role is a column on the membership row or a claim in the token. The guard reads it:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
roles,
})
.guard(async ({ apiKey, params, deny }) => {
const membership = apiKey ? await findMembership(apiKey.value, params.workspaceId) : undefined;
if (!membership) {
return deny({
status: 403,
body: {
detail: 'Forbidden',
},
});
}
return {
userId: membership.userId,
workspaceId: membership.workspaceId,
role: membership.role,
};
});
```
Kizuna answers `403` before the handler when the role is not one the route accepts. The handler reads it under `auth.member.role`.
A caller with several roles returns them as an array, and passes when any of them is accepted.
The role is a column on the membership row or a claim in the token. The guard reads it:
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
userId: z.string(),
workspaceId: z.string(),
}),
roles,
})
.guard(async ({ apiKey, params, deny }) => {
const membership = apiKey ? await findMembership(apiKey.value, params.workspaceId) : undefined;
if (!membership) {
return deny({
status: 403,
body: {
detail: 'Forbidden',
},
});
}
return {
userId: membership.userId,
workspaceId: membership.workspaceId,
role: membership.role,
};
});
```
Kizuna answers `403` before the handler when the role does not hold what the route requires. The handler reads the role under `auth.member.role` and everything it holds under `auth.member.permissions`, typed to the catalog.
A caller with several roles returns them as an array, and holds all of them.
## What an auth can say
| Value | Meaning |
| --------------------------------- | ---------------------------------------- |
| `false` | Public |
| `'member'` | Requires the `member` identity, any role |
| `['user', 'member']` | Either identity |
| `{ identity, roles?, requires? }` | The same, narrowed |
`'member'` is shorthand for `{ identity: 'member' }`. `roles` checks who the caller is and `requires` checks what they hold, so a route with only `roles` does not look at permissions.
## Permissions
Roles built from a catalog give the handler everything the caller holds under `auth.member.permissions`, typed to the catalog.
The verbs are yours. Naming them after what the route does, `send` for an invite rather than `create`, tends to read best in the map.
### Permissions per member
A role says what a member can be given. Which of them one member has is a row, and the guard returns it as `permissions`:
```ts title="src/identities.ts"
return {
userId: membership.userId,
workspaceId: membership.workspaceId,
role: membership.role,
permissions: membership.permissions,
};
```
Kizuna treats the list as what the caller holds, and fails the guard if it names something the role cannot hold. A guard that returns no list hands over the whole role, which is what an `'all'` role wants.
The route that saves the list validates each entry against the catalog:
```ts title="src/routes/members.ts"
setPermissions: k
.route({
method: 'PUT',
path: '/members/:userId/permissions',
auth: {
identity: 'member',
roles: ['owner'],
},
body: z.object({
permissions: z.array(permissions.schema),
}),
responses: {
200: MemberSchema,
},
})
.handler(/* ... */),
```
A permission outside the catalog is a `400` before the handler runs:
```json title="PUT /members/usr_7/permissions"
{
"permissions": ["project:read", "project:archive"]
}
```
```json title="400 Bad Request"
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request validation failed",
"errors": [
{
"code": "invalid_value",
"path": ["permissions", "1"],
"message": "Invalid option: expected one of \"workspace:read\"|\"workspace:update\"|...|\"invite:accept\""
}
]
}
```
## Rows
The map says whether the caller may call the route. Which rows are theirs is a second question, answered in the handler with the row in hand, and row-level security says which rows a query may see at all:
| Layer | Runs | Answers |
| ------------------ | --------------------------------- | -------------------------------------- |
| The map | In the guard, before the handler | May this caller call this route |
| The handler | With the row it loaded | Is this row the caller's |
| Row-level security | In the database, inside the query | Which rows this request may see at all |
Kizuna runs the first. You write the second, with the row and `auth` in hand. The third is the database's.
### One row
A member updates the projects they own. The map lets members in, and the handler settles whose project it is with the row in hand:
```ts title="src/routes/projects.ts"
updateProject: async ({ params, body, auth }) => {
const project = await db.query.projects.findFirst({
where: eq(projects.id, params.projectId),
});
if (!project) {
return {
status: 404,
body: {
detail: 'Project not found',
},
};
}
if (project.ownerId !== auth.member.userId) {
return {
status: 403,
body: {
detail: 'Not your project',
},
};
}
return {
status: 200,
body: await saveProject(project.id, body),
};
},
```
The `403` is the one every guarded route already declares, so the handler answers it without declaring it.
An archived project that cannot be updated reads the row and never the caller. That is a `409` from the handler, since no role could
ever get past it.
### Every row
It runs before the query, never inside it. A list that forgets its `where` returns every tenant's rows.
The database can. Postgres row-level security applies a filter to every query on the table:
```sql title="migrations/0007_projects_rls.sql"
alter table projects enable row level security;
alter table projects force row level security;
create policy "own workspace" on projects
using (workspace_id = current_setting('app.workspace_id', true));
```
Set the workspace per request, inside a transaction, so it ends with the request:
```ts title="src/db/with-workspace.ts"
export const withWorkspace = (workspaceId: string, run: (tx: Transaction) => Promise) =>
db.transaction(async (tx) => {
await tx.execute(sql`select set_config('app.workspace_id', ${workspaceId}, true)`);
return run(tx);
});
```
```ts title="src/routes/projects.ts"
listProjects: async ({ auth }) => ({
status: 200,
body: {
projects: await withWorkspace(auth.member.workspaceId, (tx) => tx.query.projects.findMany()),
},
}),
```
## OAuth
An OAuth token's scopes are permissions. The guard returns them as `permissions`, and `requires` checks them like any other. See [OAuth](/docs/oauth).
## What it drives
`defineConfig` puts `401` and `403` on every route this map guards, as [Problem Details](/docs/reference/problem-details-schema), both `no-store`. A public route gets neither:
```ts title="delete-project.ts"
const result = await apiClient.projects.deleteProject({
params: {
projectId: 'prj_42',
},
});
if (result.status === 403) {
console.log(result.body.detail);
}
```
[`generateOpenApi`](/docs/reference/generate-openapi) emits each route's `security`, the roles it accepts under `x-kizuna-roles`, and the permissions it requires under `x-kizuna-requires`:
```yaml title="openapi.yaml"
# generated
paths:
/projects/{projectId}:
delete:
security:
- member: []
x-kizuna-roles: [owner]
```
## Reference
- [`Kizuna.roles`](/docs/reference/kizuna-roles)
- [`Kizuna.permissions`](/docs/reference/kizuna-permissions)
- [`k.route`](/docs/reference/k-route)
- [`defineConfig`](/docs/reference/define-config)
- [Authentication](/docs/authentication)
---
# Authentication
Source: /docs/authentication
---
title: Authentication
description: Say who can call your API. An identity is a credential you accept, a guard turns it into the caller, and the handler receives them typed.
---
Authentication is still settling. `k.identity` and an identity's `guard` may change while v2 is in beta, so pin your version if you depend on them.
An **identity** is a credential your API accepts. A **guard** turns it into the caller. What that caller may do is [Access Control](/docs/access-control).
## Pick your credential
An identity and its guard go together:
A token in the `Authorization` header.
```ts title="src/identities.ts"
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny }) => {
const session = bearer ? await verifySession(bearer.token) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
A value in a header, a query parameter or a cookie. A browser session is `in: 'cookie'`.
```ts title="src/identities.ts"
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
workspaceUserId: z.string(),
}),
})
.guard(async ({ apiKey, deny }) => {
const membership = apiKey ? await findMembership(apiKey.value) : undefined;
if (!membership) {
return deny({
status: 403,
body: {
detail: 'Forbidden',
},
});
}
return {
workspaceUserId: membership.userId,
};
});
```
The browser attaches it to any request, including ones another site triggers. Set `SameSite` on the cookie and check the `Origin` header
on unsafe methods.
A username and password, decoded from the `Authorization` header.
```ts title="src/identities.ts"
export const operator = k.identity
.basic({
context: z.object({
operatorId: z.string(),
}),
})
.guard(async ({ basic, deny }) => {
const operator = basic ? await verifyOperator(basic.username, basic.password) : undefined;
if (!operator) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
operatorId: operator.id,
};
});
```
A credential no OpenAPI scheme describes, such as a token in a path segment. The guard reads it itself.
```ts title="src/identities.ts"
export const inviteToken = k.identity
.custom({
context: z.object({
inviteId: z.string(),
}),
params: z.object({
token: z.string(),
}),
})
.guard(async ({ params, deny }) => {
const invite = await findInvite(params.token);
if (!invite) {
return deny({
status: 404,
body: {
detail: 'Not found',
},
});
}
return {
inviteId: invite.id,
};
});
```
`oauth2` and `openIdConnect` are on [OAuth](/docs/oauth).
An identity with no `context` only proves the caller is known. Its guard returns nothing and handlers get no argument for it.
## Name it on your config
The identity carries its own guard, so naming it is all there is:
```ts title="kizuna.config.ts"
import { user } from './src/identities';
export default defineConfig({
adapter: expressAdapter(),
routes,
auth: {
identities: {
user,
},
},
});
```
The key is the name everything else uses: a route's `auth`, and the handler's `auth.user`. An identity a route names has to carry a guard, or the config refuses to assemble.
## Say which routes need it
Every route states its rule, so public is an explicit `false` and a forgotten route is a type error:
```ts title="src/routes/users.ts"
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
auth: 'user',
responses: {
200: z.array(UserSchema),
},
})
.handler(/* ... */),
});
```
The rest of what an `auth` can say is on [Access Control](/docs/access-control).
## Read the caller
Every guarded route hands its handler what the guard returned, typed, under `auth`:
```ts title="src/routes/users.ts"
listUsers: k
.route({
method: 'GET',
path: '/users',
auth: 'user',
responses: {
200: z.array(UserSchema),
},
})
.handler(async ({ auth }) => ({
status: 200,
body: {
users: await findUsersExcept(auth.user.userId),
},
})),
```
A guard returns the identity's `context`, field for field. Whether that caller may call the route is decided from it before the handler runs, in [Access Control](/docs/access-control). Which rows are theirs is the handler's question.
## Denying
`deny({ status, body, headers })` answers with [Problem Details](/docs/reference/problem-details-schema), the same shape `throwError` takes in a handler. A `401` carries the `WWW-Authenticate` challenge RFC 9110 requires, named after the identity that denied it. A cookie or API key has no challenge to send, so those answer `403`.
### What a refusal says
A refusal carries `detail` alone until `guardSchema` widens it:
```ts title="kizuna.config.ts"
export const GuardSchema = Kizuna.model({
title: 'GuardDenial',
schema: ProblemDetailsSchema.extend({
code: z.enum(['unauthenticated', 'expired_token', 'forbidden']).default('forbidden'),
}),
});
export default defineConfig({
adapter: expressAdapter(),
routes,
auth: {
identities: {
user,
member,
},
guardSchema: GuardSchema,
},
});
```
```ts title="src/identities.ts"
return deny({
status: 401,
body: {
detail: 'Unauthorized',
code: 'expired_token',
},
});
```
Every field you add must be optional or carry a `.default()`, since Kizuna sends this body itself when [Access Control](/docs/access-control) refuses a caller. `defineConfig` throws when it cannot.
## What else a guard gets
The route's path `params`, the adapter's native request objects, and any [request context](/docs/request-context) your config declares. A request-scoped value that gates nothing, such as a logger, is a [request context](/docs/request-context) rather than an identity.
## What it drives
`defineConfig` puts `401` on every guarded route, as [Problem Details](/docs/reference/problem-details-schema), with `WWW-Authenticate` required when every identity on the route has a challenge and optional when only some do. Declaring a `401` yourself is an error.
[`generateOpenApi`](/docs/reference/generate-openapi) emits your identities as `components.securitySchemes`. A `custom` identity has no scheme, so its routes carry an `x-kizuna-guarded` extension instead.
The [fetch client](/docs/clients/fetch) sends the credential in `baseHeaders`, and [MCP endpoints](/docs/mcp) run the same guards per tool call.
## Reference
- [`k.identity`](/docs/reference/k-identity)
- [`defineConfig`](/docs/reference/define-config)
- [Access Control](/docs/access-control)
- [OAuth](/docs/oauth)
---
# Breaking Changes
Source: /docs/breaking-changes
---
title: Breaking Changes
description: Catch a change that breaks callers before it ships.
---
[`kizuna diff`](/docs/cli#kizuna-diff) compares two versions of your API and reports what each change costs the people already calling it. It reads the declarations, so route keys, MCP tool names and job keys are all in view, and every Zod schema is compared field by field.
## Run it against a ref
```bash
kizuna diff --against main
```
```
BREAKING POST /users body.organisationId is now required
CHANGED users.patchUser renamed to users.updateUser
the generated client method changes name, the HTTP surface does not
CHANGED GET /users/:id can now answer 410
ADDED POST /users/:id/archive added
```
Routes are always compared: the method, the path, every status, and every request and response schema. The rest is opt-in.
```ts title="kizuna.config.ts"
export default defineConfig({
diff: {
dottedKeys: true,
jobs: true,
tools: true,
},
});
```
| Option | Fails the gate on |
| ------------ | --------------------------------------------------------------------------------- |
| `dottedKeys` | a renamed route key, which names the method when you publish the client as an SDK |
| `jobs` | a job key gone, which `POST /jobs/run` addresses by name |
| `tools` | an MCP tool a model can no longer call |
All of it is recorded in `.kizuna/snapshot.yaml` either way, so switching one on later still compares against what you already committed.
## Gate it in CI
`fetch-depth: 0` is there because `diff` reads the base out of git. `generate --check` runs first, so a snapshot nobody regenerated fails the build instead of answering from a stale file. `continue-on-error` keeps the job alive past a breaking change, which is the only way the label step runs.
```yaml title=".github/workflows/breaking-changes.yml"
name: Breaking Changes
on:
pull_request:
branches: [main]
jobs:
breaking-changes:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- name: Check the snapshot is current
run: pnpm kizuna generate --check
- name: Compare against main
id: diff
continue-on-error: true
run: pnpm kizuna diff --against ${{ github.event.pull_request.base.sha }}
- name: Require a label for breaking changes
if: steps.diff.outcome == 'failure'
run: |
if [[ "${{ contains(github.event.pull_request.labels.*.name, 'breaking changes') }}" == "true" ]]; then
echo "Breaking changes acknowledged via label."
else
echo "::error::Breaking changes detected. Add the 'breaking changes' label to acknowledge."
exit 1
fi
```
A breaking change blocks the pull request until someone adds the `breaking changes` label.
## The route surface
| Change | Level |
| ------------------------------------ | -------- |
| A route removed | breaking |
| A route renamed | breaking |
| A method or path changed | breaking |
| A declared status no longer answered | breaking |
| A job key removed | breaking |
| An MCP tool removed or renamed | breaking |
| A new status | changed |
| A new deprecation or sunset | changed |
| A route added | added |
A rename is spotted by matching a departed key against an arrived one on the same method and path, so it reads as one breaking change rather than a removal and an addition. Renaming `users.patchUser` to `users.updateUser` leaves the method, the path and every schema alone, and still changes the client method, the MCP tool name, and the method names in the generated Swift and Kotlin clients.
## Schemas, where direction decides everything
A caller sends requests and reads responses, so tightening an input and dropping an output are the two that hurt.
| Change | Request | Response |
| ------------------------------ | ------------ | ------------ |
| A required field added | **breaking** | changed |
| An optional field added | quiet | changed |
| A field removed | changed | **breaking** |
| An optional field required | **breaking** | changed |
| A required field optional | changed | **breaking** |
| A field made nullable | changed | **breaking** |
| A nullable field made non-null | **breaking** | changed |
| A type changed | **breaking** | **breaking** |
| An enum value removed | **breaking** | **breaking** |
| An enum value added | changed | **breaking** |
That last row catches people out. Adding a value to a response enum breaks any client that generated a closed enum for it, which is what [`unknownEnumCase`](/docs/clients/swift) exists for in the Swift and Kotlin clients.
Bodies, query parameters, headers and every response body are compared, reported by path and followed into arrays:
```
BREAKING POST /users body.address.postcode is now required
BREAKING GET /users 200.items[].id is number instead of string
```
**What it cannot read** is the rule inside a `.refine()` or `.superRefine()`, because a predicate is a function rather than a declaration. It does see one arrive or leave, so adding a refinement is reported as tightened validation, but a rewritten predicate that accepts less than it did passes quietly.
## Reference
- [Deprecations](/docs/deprecations), for retiring a route rather than removing it
- [Configuration](/docs/config)
---
# Caching
Source: /docs/caching
---
title: Caching
description: Declare on a response how it may be cached, and have Kizuna send the Cache-Control and Vary headers and document them in OpenAPI.
---
Caching is new and still settling, so `cache` and `etag` may change while v2 is in beta. A policy is also hard to take back once callers hold a response, so reach for it deliberately rather than by default.
Declare a cache policy on the response it describes, and every adapter sends it:
```ts title="src/routes/users.ts"
export const users = k.routes.users({
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: {
body: UserSchema,
cache: {
scope: 'private',
maxAge: 300,
vary: ['authorization'],
},
},
404: ProblemDetailsSchema,
},
})
.handler(/* ... */),
});
```
The 200 goes out with `Cache-Control: private, max-age=300` and `Vary: Authorization`. The 404 declares no policy, so it sends no cache headers, which is what you want almost every time.
## When you should cache
**An avatar, a badge, a generated chart.** Large, changes rarely, and the browser fetches it through `` where the HTTP cache actually applies. Put the version in the path and cache it forever:
```ts
userBadge: k
.route({
method: 'GET',
path: '/users/:id/badge/:version',
responses: {
200: {
body: BinarySchema,
contentType: 'image/png',
cache: {
scope: 'public',
maxAge: 31536000,
immutable: true,
},
},
},
})
.handler(/* ... */),
```
Give `:version` whatever changes when the image does, an upload timestamp or a content hash, and hand callers the URL alongside the user. A new image is a new URL, so nothing is ever stale and nothing needs invalidating.
Without that, the image lives at one URL forever and every cache holding it is beyond your reach. `noCache` with an `etag` is the safe fallback, since the browser checks before every reuse and gets a few hundred bytes back when nothing changed, but a page listing fifty users then makes fifty conditional requests. Prefer the version in the path.
**A public catalogue in front of a CDN.** Put the lifetime on `sharedMaxAge` rather than `maxAge` and only the CDN holds it. That is the difference between a mistake you can fix and one you cannot: a CDN has a purge API, a million browsers do not.
```ts
200: {
body: z.array(ProductSchema),
cache: {
scope: 'public',
maxAge: 0,
sharedMaxAge: 600,
staleWhileRevalidate: 60,
},
},
```
**A report that costs real work to build.** The same `sharedMaxAge`, and `staleIfError` so callers keep getting yesterday's numbers while the warehouse is down rather than a 500.
**Anything behind authentication.** Here the policy is about correctness, not speed. `scope: 'private'` keeps a corporate proxy from storing one caller's data and handing it to the next, and `vary` names the request headers that shaped it:
```ts
200: {
body: z.array(InvoiceSchema),
cache: {
scope: 'private',
noCache: true,
vary: ['authorization'],
},
etag: true,
},
```
Declaring `public` on a route behind `security` throws when the config is assembled, so the version of this that leaks data cannot ship.
## When it does nothing
A React app on TanStack Query or SWR. Those keep their own cache with their own `staleTime` and do not make conditional requests, so neither `maxAge` nor `etag` reaches them. Your generated Swift and Kotlin clients are the opposite: `URLSession` and OkHttp honour all of this with no code on your side.
## Two policies, and the trap between them
`maxAge` is the one thing here you cannot take back. Once a response goes out with `max-age=86400`, every cache holding it may serve that copy for a day, and no deploy reaches them. That leaves two policies worth writing, and the choice is decided by one question: **does the URL change when the content does?**
If it does, cache it forever. A fingerprinted URL can never serve the wrong thing, because new content is a new URL:
```ts
200: {
body: BinarySchema,
contentType: 'image/png',
cache: {
scope: 'public',
maxAge: 31536000,
immutable: true,
},
},
```
If it does not, revalidate every time. `noCache` tells the cache to check before every reuse, and an [`etag`](#revalidating) makes the check cost a few hundred bytes instead of the whole body. It can never serve something stale:
```ts
200: {
body: UserSchema,
cache: {
scope: 'private',
noCache: true,
},
etag: true,
},
```
The trap is the middle: a modest `maxAge` on content that changes at a stable URL. It looks reasonable and passes testing, then serves a stale response to somebody for as long as you set, with no way to recall it.
A response that declares no `cache` sends no cache headers, so nothing is cached until you say so.
## Caching a miss
A lookup that gets hammered with requests for things that do not exist can cache the miss too, so the flood stops at the CDN instead of your database. A thousand requests a second for one missing id become one request per lifetime, so even a minute is worth a great deal:
```ts
responses: {
200: {
body: UserSchema,
cache: {
scope: 'public',
maxAge: 300,
},
},
404: {
body: ProblemDetailsSchema,
cache: {
scope: 'public',
maxAge: 60,
},
},
},
```
The number trades origin protection against how long a newly created resource keeps answering 404. A minute or two is the usual band, and it is what the CDNs pick when you say nothing: Cloudflare holds a 404 for three minutes, Google Cloud CDN for two. Declaring the policy is how you set that number yourself rather than inheriting theirs.
Reach for this when a hot path is spending real work on misses, not as a habit.
## Directives
| Declaration | Type | Sends |
| ---------------------- | ----------------------- | ------------------------ |
| `scope` | `'public' \| 'private'` | `public` / `private` |
| `maxAge` | `number`, seconds | `max-age` |
| `sharedMaxAge` | `number`, seconds | `s-maxage` |
| `staleWhileRevalidate` | `number`, seconds | `stale-while-revalidate` |
| `staleIfError` | `number`, seconds | `stale-if-error` |
| `noCache` | `true` | `no-cache` |
| `mustRevalidate` | `true` | `must-revalidate` |
| `immutable` | `true` | `immutable` |
| `vary` | `string[]` | the `Vary` header |
`scope: 'private'` is the caller's own browser, `'public'` is every cache in between, including CDNs and corporate proxies. `defineConfig` throws when a route behind `security` declares `'public'`, since that lets a shared cache hand Alice's response to Bob. It also rejects a policy that declares nothing, a number of seconds that is not a whole number of zero or more, and an empty `vary`.
`'no-store'` replaces the object rather than sitting inside it, because it rules out every other directive.
`defineConfig` also rejects the combinations that cannot mean anything. `noCache` alongside a `maxAge`, since RFC 9111 lets `no-cache` override the lifetime and it never applies. `immutable` with no lifetime, since RFC 8246 applies it only while a response is fresh. `staleWhileRevalidate` or `staleIfError` with no lifetime, since there is nothing to go stale.
The declaration is the only place a policy comes from. A `cache-control` header returned by a handler does not overrule it, so what the OpenAPI document publishes is what callers receive.
## Revalidating
`maxAge` answers "how long may this be reused". It cannot answer "has this changed", because nothing in HTTP lets you recall a response once it is out. `etag` answers the second question:
```ts
200: {
body: UserSchema,
cache: {
scope: 'private',
noCache: true,
},
etag: true,
},
```
Kizuna hashes the response body and sends it as `ETag`. The caller's cache stores that, and `no-cache` tells it to check before every reuse. On the next request it sends `If-None-Match`, and when the body still hashes the same Kizuna answers `304 Not Modified` with the headers and no body.
The saving is the body, not the work: your handler still runs, because the tag comes from what it returned. Reach for it when responses are large and change rarely.
`noCache` means the caller waits for that check on every request. If you would rather it did not, give the response a short `maxAge` instead and let the tag serve the requests that come after the lifetime runs out.
`etag` applies to successful responses, since `304` says the representation the caller holds is still current.
`Last-Modified` and `If-Modified-Since` are not here. `etag` is the stronger validator and covers the same ground.
---
# CLI
Source: /docs/cli
---
title: CLI
description: Write your types and clients, print the routes your config serves, and compare an API against a git ref.
---
`@kizunajs/cli` is the `kizuna` command. It reads your [config](/docs/config) and answers three questions: what should be generated, what does this API serve, and what did this change cost a caller.
| Command | What it does |
| ----------------- | ---------------------------------------------------------------------------- |
| `kizuna generate` | Writes `kizuna.types.ts`, every client the config declares, and the snapshot |
| `kizuna routes` | Prints every route the config serves |
| `kizuna diff` | Compares the config against the same config at a git ref |
`--config ` points any of them at a config other than `kizuna.config.ts`.
## `kizuna generate`
See [Configuration](/docs/config#kizuna-generate) for what it writes and where.
`--check` writes nothing and exits `1` when anything on disk has fallen behind the config:
```sh title="Terminal"
kizuna generate --check
```
It covers `kizuna.types.ts`, every client under `clients`, and `.kizuna/snapshot.yaml`, so one command answers whether everything generated matches today's config.
```yaml title=".github/workflows/kizuna-checks.yml"
name: Kizuna Checks
on: pull_request
jobs:
kizuna-checks:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v6
- uses: pnpm/action-setup@v6
- uses: actions/setup-node@v6
with:
node-version: 24
cache: pnpm
- run: pnpm install --frozen-lockfile
- run: pnpm kizuna generate --check
```
[Configuration](/docs/config#kizuna-generate---check) has what each file is and where it lands.
In a monorepo, build the other packages your config imports before generating. The config reads their built output, and an out-of-date build loads without complaint.
## `kizuna routes`
Every route, with what it asks of a caller, the group it is filed under, and what it publishes:
```sh title="Terminal"
kizuna routes
```
```text
GET /users users.listUsers auth: public group: users
POST /users users.createUser auth: user group: users
DELETE /users/:id users.deleteUser auth: member, requires workspace:delete group: users deprecated, use `archiveUser` instead sunset 2027-01-01
GET /forecast/:city weather.getForecast auth: public group: weather tool: weather_get_forecast
```
The path is the one the server matches. A route's `auth` reads as `public`, an identity name, or the identity with the roles and permissions it requires. A route publishing a [tool](/docs/tools) shows the name a model calls it by, resolved the same way the MCP endpoint resolves it.
`--json` prints the same map as an array, for something other than a person to read:
```sh title="Terminal"
kizuna routes --json
```
```json
[
{
"key": "weather.getForecast",
"method": "GET",
"path": "/forecast/:city",
"auth": "public",
"groups": ["weather"],
"tool": "weather_get_forecast"
}
]
```
### Group problems
Once your config declares [groups](/docs/reference/k-groups), `kizuna routes` also checks that every route is in one, and exits 1 when they are not, so a pipeline can fail on it:
```text
2 group problems:
getHealth is in no group. Declare it with k.routes.(...).
The group billing holds no routes. Remove it, or file a route in it.
```
It reports two things:
- A route in no group, which would sit at the top of every client beside your groups, and under a "default" heading in the documentation.
- A group with no route in it or below it.
A route's key always comes from its group, so the two cannot disagree. Hidden routes and plugin routes are left out, because neither reaches the OpenAPI document. With `--json`, the problems go to stderr and the map stays parseable.
## `kizuna diff`
What a change costs the people already calling your API, against a git ref:
```sh title="Terminal"
kizuna diff --against main
```
```text
BREAKING POST /users body.organisationId is now required
CHANGED users.patchUser renamed to users.updateUser
the generated client method changes name, the HTTP surface does not
CHANGED GET /users/:id can now answer 410
ADDED POST /users/:id/archive added
```
It exits `1` when a change breaks callers, so a pipeline fails on one. `--against` defaults to `main`, and `--json` prints the changes as an array. See [Breaking changes](/docs/breaking-changes) for what counts as breaking and how to gate a pull request on it.
`kizuna generate` writes `.kizuna/snapshot.yaml` beside your config, and `diff` compares two of those. The base version is read straight out of git, so nothing is checked out, installed or run for the other side, and a comparison against a commit from a year ago costs the same as one against yesterday.
The head version is whatever is on disk, so run `kizuna generate --check` first. A snapshot nobody regenerated compares cleanly against a base it no longer describes.
Two snapshots can also be compared directly, with no git and no config:
```bash
kizuna diff --from base.yaml --to .kizuna/snapshot.yaml
```
## Scripts
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate",
"kizuna:check": "kizuna generate --check"
}
}
```
## Reference
- [Configuration](/docs/config)
- [Breaking changes](/docs/breaking-changes)
---
# Config
Source: /docs/config
---
title: Config
description: Assemble your API in kizuna.config.ts, mount it, and say where its generated clients go.
---
`kizuna.config.ts` sits at the root of your app, beside `package.json`. It assembles everything the API is made of, hands back the `api` you mount, and says where each generated client is written. The tooling looks for it by name.
## The file
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { swiftClient } from '@kizunajs/swift';
import { routes } from './src/routes';
import { user } from './src/identities';
export default defineConfig({
adapter: expressAdapter(),
routes,
auth: {
identities: {
user,
},
},
clients: [
swiftClient({
output: './ios/MyApp/Generated/APIClient.swift',
namespace: 'API',
}),
],
});
```
It default-exports two things: `api`, which you mount and which every generator reads, and `clients`, which the CLI writes.
```ts title="src/index.ts"
import kizuna from '../kizuna.config';
kizuna.api.mount(app);
```
`adapter` decides what every handler receives beside its validated inputs. Express here puts `req` and `res` in scope for all of them, typed.
See [`defineConfig`](/docs/reference/define-config) for every field it takes.
## What each key brings
| Key | What it brings |
| ---------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `auth` | The identities a route's `auth` can require. Each carries its own guard, so this is all the config needs. An identity used without a guard refuses to assemble. See [Authentication](/docs/authentication). |
| `requestContext` | Values every handler receives, resolved once per request. Resolvers run on every route, before the guards, and never deny. See [Request Context](/docs/request-context). |
| `jobs` | Scheduled work. `api.mount` serves the two [job endpoints](/docs/jobs#the-two-job-endpoints) unless `jobRunner.mode` is `'in-process'`, and every handler receives a typed `jobs` runner so a route can run one in process. |
| `plugins` | Routes, jobs and helpers installed beside your own, as a list. See [below](#using-what-a-plugin-offers), and [Create a Plugin](/docs/extend/create-plugin) to write one. |
| `validation` | The `code` values [`k.issue`](/docs/reference/k-issue) may emit beyond Zod's own. |
| `groups` | The groups routes are filed under, each an OpenAPI tag. See [`k.groups`](/docs/reference/k-groups). |
## Using what a plugin offers
A plugin can hand your handlers functions to call, under `plugins`:
```ts title="src/routes/users.ts"
updateUser: k
.route({
method: 'PATCH',
path: '/users/:id',
body: UpdateUserSchema,
responses: {
200: UserSchema,
},
})
.handler(async ({ params, body, plugins }) => {
const user = await db.users.update(params.id, body);
await plugins.email.send({
to: user.email,
subject: 'Your profile was updated',
html: '
Your profile was updated.
',
});
return {
status: 200,
body: user,
};
}),
```
Destructure it for the short form:
```ts
.handler(async ({ params, body, plugins: { email } }) => {
```
Job handlers receive `plugins` the same way.
### Renaming one
Each plugin picks the slug handlers reach it under. When two want the same one, `defineConfig` throws and names both, and you rename one:
```ts title="kizuna.config.ts"
plugins: [
pushNotificationsPlugin(),
webPushPlugin({
slug: 'webPush',
}),
],
```
## Middleware
Rate limiting, multipart parsing, and the rest go in your framework's own middleware (`app.use`, Fastify hooks). Authentication belongs in [guards](/docs/authentication), request-scoped values in [`requestContext`](/docs/request-context).
## Clients
Each client comes from the package that generates it, so its options are typed there and a generator you have not installed cannot be configured by accident. The list is not closed: any package that exports a client built with [`defineClient`](/docs/extend/create-client) drops into `clients` the same way.
| Client | Import from | Writes |
| -------------- | ------------------ | ------------------------- |
| `fetchClient` | `@kizunajs/fetch` | A typed TypeScript client |
| `swiftClient` | `@kizunajs/swift` | A native Swift client |
| `kotlinClient` | `@kizunajs/kotlin` | A native Kotlin client |
```ts title="kizuna.config.ts"
clients: [
fetchClient({
output: './web/src/api.generated.ts',
}),
swiftClient({
output: '../ios/MyApp/Generated/APIClient.swift',
}),
],
```
Every route reaches every client. A route no app calls, like a health check or a webhook, is [hidden](/docs/routes#hidden-routes) and stays out of them.
Files that aren't clients, like the OpenAPI document, come from plugins. [`openApiPlugin`](/docs/openapi) writes `openapi.yaml` when you give it an `output`.
The generated client holds the route shapes and the schemas, and is what a browser imports. An `output` is resolved against the config's own directory, so in a repository holding both, `../ios/MyApp/Generated/APIClient.swift` writes into the app beside it.
## Client options
| Option | Applies to | Description |
| --------------------- | -------------------- | ------------------------------------------------------------------------- |
| `output` | all | Path the generated file is written to |
| `namespace` | Fetch, Swift, Kotlin | Name of the generated namespace, `API` by default |
| `package` | Kotlin | Package the generated file declares |
| `camelCaseProperties` | Swift, Kotlin | Convert wire field names to camelCase, mapping the wire name back |
| `unknownEnumCase` | Swift, Kotlin | Give every enum an `unknown` case, so an unrecognised value still decodes |
## Two clients of one language
Add two entries.
```ts title="kizuna.config.ts"
clients: [
swiftClient({
output: './ios/MyApp/Generated/APIClient.swift',
namespace: 'API',
}),
swiftClient({
output: './ios/MyApp/Generated/OpenEnumAPIClient.swift',
namespace: 'OpenEnumAPI',
unknownEnumCase: true,
}),
],
```
## More than one API
One config is one API. A second config is a second API, with its own routes, its own identities and its own generated clients.
### When to split
Split when the two have different callers. A public API versioned for outside integrators and an internal admin API answer to different people, change on different schedules, and want different clients, so one OpenAPI document describing both serves neither.
Split when they are deployed apart. A config has one `adapter`, so an API on Express and an API on Next.js are already two configs.
Split when the surfaces should not mix. Everything in one config shares a namespace: every route reaches every plugin's exports, one `guardSchema` shapes every refusal, and every route lands in the same generated client. Two configs keep those apart.
Stay with one config when the routes differ only by prefix. A `/admin` group under the same identities is a [route group](/docs/routes), not a second API, and splitting it costs you the shared types.
### Two configs
Give each one a file, and each its own clients:
```
my-repo/
├── kizuna.config.ts # the public API
├── kizuna.admin.config.ts # the admin API
└── src/
├── k.ts # typed by the public Config
├── admin/
│ └── k.ts # typed by the admin Config
└── routes/
```
```ts title="kizuna.admin.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { fetchClient } from '@kizunajs/fetch';
import { operator } from './src/admin/identities';
import { admin } from './src/admin/routes';
export default defineConfig({
adapter: expressAdapter(),
routes: [admin],
auth: {
identities: {
operator,
},
},
typescript: {
outputFile: './src/admin/kizuna.types.ts',
},
clients: [
fetchClient({
output: './src/admin/api-client.generated.ts',
}),
],
});
```
Each config writes its own `Config`, so each gets its own `k`:
```ts title="src/admin/k.ts"
import { Kizuna } from 'kizunajs';
import type { Config } from './kizuna.types';
export const k = new Kizuna();
```
A route declared against the admin `k` sees the admin identities and nothing else, so a public identity on an admin route is a type error rather than a runtime surprise.
### Running them
`kizuna generate` reads one config, so point it at each in turn:
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate && kizuna generate --config kizuna.admin.config.ts"
}
}
```
Each config declares its own clients, so the Swift and Kotlin clients for the admin API come out of `kizuna.admin.config.ts` along with its types.
### Sharing between them
What both APIs need lives in a module they both import: schemas, [models](/docs/reference/kizuna-model), an identity, or a whole route group. `Kizuna.model` keeps a shared schema's name, so `User` is one named type in both generated clients rather than two shapes that happen to match.
```ts title="src/schemas.ts"
export const UserSchema = Kizuna.model({
title: 'User',
schema: z.object({
id: z.string(),
name: z.string(),
}),
});
```
Serving both from one process is ordinary mounting. On Express, `mount` takes anything with a `use`, so a router mounted under a path keeps the admin API off the public one:
```ts title="src/index.ts"
import express from 'express';
import publicApi from '../kizuna.config';
import adminApi from '../kizuna.admin.config';
const app = express();
publicApi.api.mount(app);
const adminRouter = express.Router();
adminApi.api.mount(adminRouter);
app.use('/admin', adminRouter);
```
On Next.js each API is its own catch-all route file, and `mount({ basePath })` is what tells it which prefix it answers on.
## `kizuna generate`
```sh title="Terminal"
kizuna generate
```
It writes four things from `kizuna.config.ts`: the `Config` in `kizuna.types.ts`, every client under `clients`, the files plugins generate, like `openApiPlugin`'s `openapi.yaml`, and the `.kizuna/snapshot.yaml` that [`kizuna diff`](/docs/breaking-changes) compares. A file that already matches is left alone, so watchers and build tools see no change.
| Option | Default | Description |
| ---------- | ------------------ | --------------------------------------------------------------------------------------- |
| `--check` | off | Report what would be rewritten and write nothing. See [below](#kizuna-generate---check) |
| `--config` | `kizuna.config.ts` | The config to read |
| `--types` | the config's own | Where the `Config` is written, overriding `typescript.outputFile` |
Where the types land is usually the config's business rather than the command's:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
typescript: {
outputFile: './src/kizuna.types.ts',
},
});
```
### Wire it into your scripts
Two scripts cover everywhere it needs to run:
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate",
"kizuna:check": "kizuna generate --check"
}
}
```
Run `kizuna:generate` after changing a route, an identity, or the config. Run `kizuna:check` in CI, where it fails on anything nobody regenerated.
Whoever changes your routes needs to know about that first script, and a coding agent working in the repository reads the same files your team does. Say it where they look:
```md title="AGENTS.md"
After changing a route, run `pnpm kizuna:generate`.
```
### `kizuna.types.ts`
The `Config` interface is read from your config's syntax, not by running it. That is what lets `k` be typed by the config that serves your routes without the routes waiting on a config that loads.
```ts title="kizuna.types.ts"
/**
* This file was automatically generated by kizuna.
* DO NOT MODIFY IT BY HAND. Instead, modify your source kizuna config,
* and re-run `kizuna generate` to regenerate this file.
*/
import type { expressAdapter } from '@kizunajs/express';
import type { groups, user } from '@my-repo/api';
export interface Config {
adapter: ReturnType;
groups: typeof groups;
auth: {
identities: {
user: typeof user;
};
};
}
```
It carries `adapter`, `groups`, `auth`, `requestContext`, `validation`, `jobs` and `plugins`. Your `routes` stay out: they are read at runtime, and typing against them would make the config a prerequisite for declaring the routes it serves.
Point `new Kizuna()` at it once and every name you write is checked against it:
```ts title="src/k.ts"
import { Kizuna } from 'kizunajs';
import type { Config } from '../kizuna.types';
export const k = new Kizuna();
```
### `kizuna generate --check`
```sh title="Terminal"
kizuna generate --check
```
The same work without writing. It names whatever has fallen behind and exits `1`, so a pipeline fails on a file nobody regenerated:
```text
2 generated files are out of date:
src/lib/api-client.generated.ts is behind the config
.kizuna/snapshot.yaml is behind the config
Run `kizuna generate` and commit the result.
```
Commit what `kizuna generate` writes. The check compares the files on disk against the config, so a generated client that is gitignored reads as missing on every clean checkout and the pipeline fails on it.
Run it in CI, where [the CLI page](/docs/cli#kizuna-generate) has the workflow. [`kizuna diff`](/docs/breaking-changes) reads the snapshot this writes, so the two belong in the same pipeline: the check proves the snapshot matches today's config, and the diff compares it against the base.
`writeClients` and `checkClients` from `@kizunajs/cli` are the same two steps as functions, for a script that does more than the command does.
## Reference
- [`defineConfig`](/docs/reference/define-config)
- [Routes](/docs/routes) for what you put under `routes`
- [Fetch client](/docs/clients/fetch), [Swift](/docs/clients/swift), [Kotlin](/docs/clients/kotlin)
---
# Deprecations
Source: /docs/deprecations
---
title: Deprecations
description: Declare deprecations and sunset dates on a route and have them reach your editor, OpenAPI, Swift, Kotlin, and the Deprecation and Sunset response headers.
---
## Routes
| Declaration | Type |
| ------------ | ------------------------------------------------- |
| `deprecated` | `boolean \| string \| { message?, date?, link? }` |
| `sunset` | `string \| { date, link? }` |
Dates are ISO 8601, a date alone meaning midnight UTC. On the wire, `Deprecation` is Unix seconds and `Sunset` an HTTP date.
Set `deprecated` on the route, either `true`, a migration message, or the object form with a date and a documentation link:
```ts title="src/routes/users.ts"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: true,
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
```ts title="src/routes/users.ts"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: 'use `archiveUser` instead',
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
```ts title="src/routes/users.ts"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: {
message: 'use `archiveUser` instead',
date: '2026-03-01', // or '2026-03-01T12:00:00Z'
link: 'https://example.com/changelog/delete-user',
},
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
With a `date`, every response from the route announces it:
```
Deprecation: @1772323200
Link: ; rel="deprecation"
```
`true` or a message alone sends no header. The date may sit in the future, announcing a deprecation before it takes effect.
### Sunset
A route scheduled for removal declares when. The object form adds a link to the retirement policy:
```ts title="src/routes/users.ts"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: 'use `archiveUser` instead',
sunset: '2027-01-01', // or '2027-01-01T12:00:00Z'
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
```ts title="src/routes/users.ts"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: 'use `archiveUser` instead',
sunset: {
date: '2027-01-01', // or '2027-01-01T12:00:00Z'
link: 'https://example.com/retirement-policy',
},
responses: {
200: z.object({
ok: z.boolean(),
}),
},
})
.handler(/* ... */),
});
```
Every response from the route then announces it:
```
Sunset: Fri, 01 Jan 2027 00:00:00 GMT
Link: ; rel="sunset"
```
`sunset` stands on its own, a route can sunset without being deprecated. `defineConfig` rejects a `sunset` or `deprecated.date` that does not parse as ISO 8601.
## Fields
| Declaration | Type |
| ---------------------------- | ------------------- |
| `.meta({ deprecated: ... })` | `boolean \| string` |
Fields declare it in their [Zod metadata](https://zod.dev/metadata):
```ts
const UserSchema = z.object({
id: z.string(),
email: z.string().meta({
deprecated: 'use `email_address` instead',
}),
email_address: z.string(),
});
```
## What each output emits
- OpenAPI marks the operation and the field's schema with `deprecated: true` (the spec has no message field), and documents the `Deprecation`, `Sunset`, and `Link` headers on every response of a route that sends them.
- The [TypeScript client](/docs/clients/fetch) emits ``@deprecated use `email_address` instead`` on the method and on the field, which strikes them through in your editor whether or not the extension is installed.
- Swift emits ``@available(*, deprecated, message: "use `email_address` instead")``, so the message reaches autocomplete and compiler warnings.
- Kotlin emits ``@Deprecated("use `email_address` instead")``, reaching the same places.
- The headers themselves are sent by the server, so every client sees them at runtime.
---
# ESLint
Source: /docs/eslint
---
title: ESLint
description: Catch Kizuna mistakes in your editor with the official ESLint plugin.
---
`@kizunajs/eslint-plugin` catches Kizuna mistakes in your editor, as you type. These are things the type system can't express on its own.
## Setup
Add the recommended config to your `eslint.config.js`, alongside whatever else you already run:
```js title="eslint.config.js"
import js from '@eslint/js';
import tseslint from 'typescript-eslint';
import kizuna from '@kizunajs/eslint-plugin';
export default [js.configs.recommended, ...tseslint.configs.recommended, kizuna.configs.recommended];
```
## Turning a rule off
Override it after the recommended config:
```js title="eslint.config.js"
import kizuna from '@kizunajs/eslint-plugin';
export default [
kizuna.configs.recommended,
{
rules: {
'@kizunajs/no-unsupported-schema': 'off',
},
},
];
```
Or silence a single line inline:
```ts
query: z.object({
// eslint-disable-next-line @kizunajs/no-unsupported-schema
page: z.coerce.number(),
}),
```
## `no-unsupported-schema`
Flags anything no generated client can produce a type for: `body`, `query`, `pathParams`, `headers`, and response schemas in your routes, plus `Kizuna.model` schemas, inline or imported. It follows imports, so the error lands on the offending field when it's local, or on the reference when the schema comes from another file.
### `z.coerce`
Kizuna already coerces query, path, and header params to their declared types ([see Coercion](/docs/routes#query-path-and-header-coercion)), so `z.coerce` is redundant, and `k.routes` throws on it. Use the plain schema:
```ts
// flagged
query: z.object({
page: z.coerce.number(),
});
// good, kizuna coerces the string for you
query: z.object({
page: z.number(),
});
```
### `z.set` and `z.map`
JSON has neither, so `JSON.stringify(new Set(['a']))` is `{}` and the value never reaches the caller. The generated clients cannot name a type for something the wire does not carry:
```ts
// flagged
body: z.object({
tags: z.set(z.string()),
counts: z.map(z.string(), z.number()),
});
// good, both survive the round trip
body: z.object({
tags: z.array(z.string()),
counts: z.record(z.string(), z.number()),
});
```
### A union of objects with no discriminator
Two object branches with overlapping fields cannot be told apart from the JSON, so a decoder picks whichever matches first, and which one that is depends on the order you declared them. [`z.discriminatedUnion`](/docs/zod) puts the answer on the wire:
```ts
// flagged
body: z.union([CircleSchema, SquareSchema]);
// good, `kind` says which branch arrived
body: z.discriminatedUnion('kind', [CircleSchema, SquareSchema]);
```
A union of different kinds is untouched, so the one-or-many query param that accepts a single value or a list still works:
```ts
query: z.object({
ids: z.union([z.array(z.string()), z.string()]),
});
```
### A transform on a response body
A transform's output is whatever the function returns, which no generator can read, so the client would be typed from the input and be wrong about what it receives. Declare the response as the shape it sends:
```ts
// flagged
responses: {
200: z.object({
length: z.string().transform((value) => value.length),
}),
}
// good
responses: {
200: z.object({
length: z.number(),
}),
}
```
A transform on the way in is fine, since the caller sends the input and the server parses it.
### A nullable query, path, header or form field
A query string, a path, a header and a form field have no `null`, so every client leaves a `null` out, and the server rejects the missing key of a `.nullable()` field. Declare it `.optional()`:
```ts
// flagged
query: z.object({
cursor: z.string().nullable(),
});
// good, a caller leaves it out
query: z.object({
cursor: z.string().optional(),
});
```
JSON bodies and responses can carry `null`, so `.nullable()` there is untouched. See [Optional and null fields](/docs/zod#optional-and-null-fields).
### A field its part of the request cannot carry
A path parameter and a header carry one value, a query carries values and lists of values, and a form carries those plus files. An object anywhere in those, a list in a header, or `BinarySchema` in a form can't be sent:
```ts
// flagged
query: z.object({
filter: z.object({
status: z.string(),
}),
});
// good, a field of its own
query: z.object({
status: z.string(),
});
```
`k.routes` throws on the same fields when the config loads, so the rule shows it in the editor first. See [What each part can carry](/docs/routes#what-each-part-can-carry).
### Across files
A schema defined elsewhere, such as a shared `PaginationQuery` in its own `zod`-only module, is still caught, and the error lands on the reference:
```ts title="pagination.ts"
import { z } from 'zod';
export const PaginationQuery = z.object({
page: z.coerce.number(),
});
```
```ts title="users.ts"
import { PaginationQuery } from './pagination.js';
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: PaginationQuery, // flagged here, PaginationQuery uses z.coerce
responses: {
200: UserListSchema,
},
})
.handler(/* ... */),
});
```
---
# What is Kizuna.js?
Source: /docs
---
title: What is Kizuna.js?
description: A spec-driven framework for building fully typed REST APIs in TypeScript, where your route declarations produce the validation, the documentation, the clients, and the AI tools.
---
You write routes, each a method, a path, the Zod schemas it takes and returns, and the handler that serves it:
```ts title="src/routes/users.ts"
export const getUser = k
.route({
method: 'GET',
path: '/users/:id',
auth: 'user',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params, throwError }) => {
const user = await db.users.find(params.id); // the `:id` in the path above
if (!user) {
return throwError({
status: 404,
body: {
detail: 'User not found',
},
});
}
return {
status: 200,
body: user, // { id: string; name: string }
};
});
```
That route answers exactly what it declared:
```http title="GET /users/1"
HTTP/1.1 200 OK
content-type: application/json
{
"id": "1",
"name": "Ada"
}
```
```http title="GET /users/999"
HTTP/1.1 404 Not Found
content-type: application/problem+json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "User not found"
}
```
`kizuna.config.ts` collects your routes into the API you mount on your adapter. It validates every request against those schemas and answers failures as [Problem Details](/docs/reference/problem-details-schema).
The same declaration is what everything else is written from:
## Runs on your framework
The adapter is one line of your config. Handlers get that framework's own typed request and response.
`req` and `res` in every handler.
`request` and `reply` in every handler.
`c` in every handler.
`request` in every handler.
Running somewhere else? [Write your own adapter](/docs/extend/create-adapter).
## Spec-driven
Kizuna follows the RFCs instead of inventing conventions, so your API behaves the way the web already expects. [See every spec it follows](/docs/standards).
Every error body is RFC 9457, sent as `application/problem+json`.
`401` carries the `WWW-Authenticate` challenge the identity declares.
`Cache-Control`, `Vary` and `ETag` from what the response declares.
`Deprecation` and `Sunset` headers from the route that announces them.
Errors are hard to get right, so Kizuna starts from Problem Details. Add your own fields and anything that speaks the standard still reads it:
```ts title="src/routes/users.ts"
responses: {
200: UserSchema,
429: ProblemDetailsSchema.extend({
retryAfter: z.int(),
}),
},
```
## Iterate without breaking your apps
Kizuna treats a breaking change as a decision you make, not one you discover in production. `kizuna diff` compares your routes against a git ref and reports what a change costs, from a renamed route down to a single field that became required. Breaking ones exit 1, so CI fails until someone labels the pull request.
## Easy to extend
Anything Kizuna ships, you can extend yourself with the same tools we used.
Package code you reuse, with routes and jobs that reach every handler and client.
Serve on a runtime Kizuna has never heard of.
Generate a client for a language Kizuna doesn't ship.
Write documents and other files from your routes.
Put your jobs on any queue or scheduler.
## Start here
Declare a route, serve it, and call it from a typed client in 8 minutes.
`kizuna.config.ts` names the framework you serve on and what the API is made of.
A method, a path, its schemas, and the handler that serves it.
Express, Fastify, Hono, or the Next.js App Router.
A credential you accept, and the guard that turns it into the caller.
Write your types and clients, print your routes, and diff an API against a git ref.
---
# Jobs
Source: /docs/jobs
---
title: Jobs
description: Declare background and scheduled jobs next to their handlers, run them or queue them from your own code, and connect any queue you already run.
---
Jobs are new and still settling. The shape of `k.jobs`, the handler signature, and the job endpoints may change while v2 is in beta, so pin your version if you depend on them.
`k.jobs` declares background work beside your routes, each job carrying the handler that runs it.
## Declare the jobs
`k.job` takes what the job is, `.handler()` takes what runs it, and `k.jobs` groups them under the identity every one of them requires.
```ts title="src/jobs.ts"
import { z } from 'zod';
import { cron } from 'kizunajs';
import { k } from './k';
export const jobs = k.jobs('scheduler', {
sendDigests: k
.job({
schedule: cron.daily('05:00'),
summary: 'Send the daily digest to every user',
result: z.object({
sent: z.int(),
}),
})
.handler(async () => ({
status: 200,
body: {
sent: await sendPendingDigests(),
},
})),
indexUser: k
.job({
retry: 3,
input: z.object({
userId: z.string(),
}),
})
.handler(async ({ input, throwError }) => {
const user = await db.users.findById(input.userId);
if (!user) {
throwError({
status: 422,
body: {
detail: `No user with id ${input.userId}`,
},
});
}
await search.index(user);
}),
});
```
A handler receives `input`, `throwError`, `jobs`, and the `plugins` your config installs. A job with no declared `result` can return nothing.
A job with a `schedule` runs on a clock; one without is only ever queued. A job can have both.
Jobs nest in groups:
```ts title="src/jobs.ts"
export const jobs = k.jobs('scheduler', {
billing: {
reconcileInvoices: k
.job({
schedule: cron.every('15m'),
})
.handler(async () => ({
status: 200,
body: {
reconciled: await reconcile(),
},
})),
},
});
```
## Name them on your config
```ts title="kizuna.config.ts"
import { jobs } from './src/jobs';
import { scheduler } from './src/identities';
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
},
auth: {
identities: {
scheduler,
},
},
});
```
The identity `k.jobs` names carries its own guard, so nothing else is wired here. `mode` says how the jobs run, and [Setting it up](#setting-it-up) walks through each.
## Schedules
A five-field cron expression, read as UTC, or an object to read it in a time zone:
```ts
schedule: '0 5 * * *';
schedule: {
cron: '0 3 * * *',
timezone: 'Europe/Oslo',
}
```
Helpers return plain cron strings:
| Helper | Expression |
| ----------------------------- | -------------- |
| `cron.every('15m')` | `*/15 * * * *` |
| `cron.every('2h')` | `0 */2 * * *` |
| `cron.hourly(30)` | `30 * * * *` |
| `cron.daily('05:00')` | `0 5 * * *` |
| `cron.weekly('mon', '09:00')` | `0 9 * * 1` |
| `cron.monthly(1, '05:00')` | `0 5 1 * *` |
An invalid expression throws when the config is assembled, naming the field.
## Return status and retries
| Return | Status | Read as |
| ------------------- | -------------------------------- | -------------------------- |
| success | `200`, or `204` with no `result` | done |
| transient failure | `503` | retry me |
| permanent failure | `422` | do not retry; page a human |
| an unexpected throw | `500` | retry me |
Job handlers must be idempotent. Delivery is at least once everywhere, so a retry runs your handler again.
## Running and queueing
Every handler receives a `jobs` runner shaped like the declaration, with two methods per job:
```ts title="src/routes/users.ts"
createUser: k
.route({
method: 'POST',
path: '/users',
body: CreateUserSchema,
responses: {
201: UserSchema,
},
})
.handler(async ({ body, jobs }) => {
const user = await db.users.create(body);
await jobs.indexUser.queue({
input: {
userId: user.id,
},
});
return {
status: 201,
body: user,
};
}),
```
```ts
// Run it now, block, get the result.
const result = await jobs.billing.reconcileInvoices.run({ since });
// Put it in line and answer the request.
await jobs.search.reindex.queue();
```
`queue` takes a message:
```ts
await jobs.chargeInvoice.queue({
input: {
invoiceId,
},
dedupeKey: `charge:${invoiceId}`,
runAt: threeDaysFromNow,
});
```
Input is validated against the job's `input` schema either way.
A job's handler receives the same runner, so a scheduled job can queue one job per unit of work rather than doing all of it inline.
## Setting it up
No queue. `startJobs` watches the clock, and a queued job runs right here.
Nothing outside the process calls the [job endpoints](#the-two-job-endpoints), so the jobs take no identity:
```ts title="src/jobs.ts"
export const jobs = k.jobs({
sendDigests: k
.job({
schedule: cron.daily('05:00'),
})
.handler(async () => {
await mailer.sendDigests();
}),
});
```
`mode: 'in-process'` leaves the endpoints unmounted. A job that fails after the response has gone needs somewhere to report:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'in-process',
onError: (job, error) => Sentry.captureException(error, { tags: { job } }),
},
});
```
```ts title="src/index.ts"
import { startJobs } from 'kizunajs/jobs';
import kizuna from '../kizuna.config';
kizuna.api.mount(app);
startJobs(kizuna.api);
```
Run one instance. Every replica ticks its own schedule, and no `dedupeKey` is honoured, so two replicas mean two runs.
The same `startJobs`, plus a queue holding the jobs you call `queue()` on, so a restart does not lose them.
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'in-process',
transport: bullmq(connection),
},
});
```
```ts title="src/index.ts"
kizuna.api.mount(app);
startJobs(kizuna.api);
```
If your queue hands work back rather than calling your job's URL, run a worker to pull from it:
```ts title="worker.ts"
import { startJobWorker } from 'kizunajs/jobs';
import kizuna from '../kizuna.config';
const worker = await startJobWorker(kizuna.api);
process.on('SIGTERM', () => void worker?.stop());
```
A queue that calls your job's URL instead delivers to `/jobs/run`, so it needs `mode: 'http'` and an identity. More than one instance is fine, as long as the queue drops repeated keys. You can also drop `startJobs` and hand the schedules to the queue's own scheduler with [`register`](/docs/extend/create-job-transport#register).
Vercel, Lambda, Cloudflare. Platform cron ticks the dispatch endpoint and that covers every schedule:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: nextAdapter(),
routes,
jobs,
auth: {
identities: {
scheduler,
},
},
jobRunner: {
mode: 'http',
method: 'GET',
},
});
```
```json title="vercel.json"
{
"crons": [
{
"path": "/jobs/dispatch",
"schedule": "* * * * *"
}
]
}
```
One entry covers every job you ever add: the endpoint works out which are due. `method: 'GET'` is there because Vercel Cron issues `GET`.
`queue` needs a transport here, because the function can be frozen the moment it answers. Use a queue that delivers over HTTP, like QStash, Cloud Tasks, or SQS. It posts to the run endpoint, which the same identity guards.
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: nextAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
transport: qstash({
token: process.env.QSTASH_TOKEN,
baseUrl: 'https://api.example.com',
schedulerSecret: process.env.CRON_SECRET,
}),
},
});
```
## Transports
A transport carries a queued job out of this process to whatever runs it. Name one under `jobRunner` and your existing `queue` calls become as durable as it is:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
transport: myQueue,
},
});
```
Kizuna ships no transports. QStash, BullMQ, pg-boss, Cloud Tasks, SQS, or a table in your own database all fit the same interface: see [Create a job transport](/docs/extend/create-job-transport).
A job is addressed by its dotted key, so a transport carries the name and the input. Queues come in two shapes, and the shape decides whether you run anything extra:
| Shape | Examples | You run |
| ------------------- | ---------------------------------- | ------------------------------------------ |
| Delivers over HTTP | QStash, Cloud Tasks, SQS to Lambda | nothing, the run endpoint is already there |
| Hands the work back | BullMQ, pg-boss, your own table | `startJobWorker(api)` |
`startJobWorker` returns `undefined` against a queue that needs no worker. Run it in the API's process or its own.
`retry: 3` on a job says how many attempts a failure deserves; your transport does the retrying. Kizuna warns when a job asks for something its transport will drop, at startup for `retry` and at the `queue` call for `runAt` and `dedupeKey`.
## The two job endpoints
`api.mount` serves two endpoints for every job. Both mount as ordinary routes, so the jobs' identity guards them and failures render as Problem Details.
| Endpoint | Called by | Body | Answers |
| --------------------- | -------------- | ---------------- | ------------------------------------------------------------ |
| `POST /jobs/dispatch` | platform cron | none | `200`, or `503` with the names that failed |
| `POST /jobs/run` | your transport | `{ job, input }` | whatever the job answered, `404` for a name it does not know |
`POST /jobs/dispatch` runs whichever jobs the elapsed window belonged to. Point platform cron at it.
`POST /jobs/run` runs the one job the body names, validating `input` against that job's schema and answering `422` when it does not fit. It answers with the job's own status, which a queue reads as the [retry signal](#return-status-and-retries).
Configure both under `jobRunner` on [`defineConfig`](/docs/reference/define-config), beside the `transport` and `onError` above:
| Option | Default | Description |
| ---------- | -------- | -------------------------------------------------- |
| `mode` | required | `'http'` serves both, `'in-process'` neither |
| `path` | `/jobs` | The namespace both are mounted under |
| `method` | `POST` | `/jobs/dispatch`'s method. `'GET'` for Vercel Cron |
| `windowMs` | `60000` | How far back a tick looks for due jobs |
| `only` | none | Dispatch only these jobs |
| `exclude` | none | Never dispatch these |
`method` moves `/jobs/dispatch` only: `/jobs/run` takes a body, so it is always `POST`. Nothing is served on `/jobs` itself.
`mode: 'in-process'` serves neither, for a long-running server whose schedules `startJobs` ticks. It takes none of the options below `mode`, and its jobs need no identity. Served endpoints do need one, so `defineConfig` throws when jobs without an identity would be reachable. Use `'http'` when a transport delivers to `/jobs/run` or platform cron ticks `/jobs/dispatch`.
A tick runs each due job inline, in the request the scheduler made, so the function's timeout is the budget for all of them. Keep the tick short by having a scheduled job queue one job per unit of work:
```ts title="src/jobs.ts"
export const jobs = k.jobs('scheduler', {
sendDigests: k
.job({
schedule: cron.daily('05:00'),
result: z.object({
queued: z.int(),
}),
})
.handler(async ({ jobs }) => {
const due = await db.users.needingDigest();
for (const user of due) {
await jobs.sendOneDigest.queue({
input: {
userId: user.id,
},
dedupeKey: `digest:${user.id}:${today()}`,
});
}
return {
status: 200,
body: {
queued: due.length,
},
};
}),
sendOneDigest: k
.job({
input: z.object({
userId: z.string(),
}),
})
.handler(async ({ input }) => {
await mailer.sendDigest(input.userId);
}),
});
```
## Local development
When you deploy to platform cron and want `pnpm dev` to exercise the real HTTP path, `startJobsDevRunner` ticks the dispatch endpoint over the network on an interval, the way your platform cron will:
```ts title="src/index.ts"
import { startJobsDevRunner } from 'kizunajs/jobs';
if (process.env.NODE_ENV !== 'production') {
startJobsDevRunner(kizuna.api, {
baseUrl: `http://localhost:${port}`,
secret: process.env.CRON_SECRET,
});
}
```
The dev runner ticks on an interval held in memory, so a tick while the process is down is missed silently.
## What Kizuna.js does not do
Kizuna owns no database and no queue, so it does not:
- **Store your jobs.** Durability, dead-lettering, and a dashboard come from your transport.
- **Retry.** Your transport does. Without one, nothing retries.
- **Know whether a job already ran.** It only names the run so a deduplicating transport can tell.
- **Prevent overlapping runs.** Take a lock in your own database.
- **Keep run history or backfill missed ticks.**
---
# MCP
Source: /docs/mcp
---
title: MCP
description: Install the MCP plugin so AI assistants can call your API as tools, on any adapter.
---
MCP support is new and still settling. The plugin options and the published tool surface may change while v2 is in beta, so pin your version if you depend on them.
`@kizunajs/mcp` adds an [MCP (Model Context Protocol)](https://modelcontextprotocol.io) endpoint to your API. Every route that declares [`tool`](/docs/tools) is one an AI assistant can discover and call.
## Say which routes a model may call
A route publishes itself. `tool: true` takes the route's `summary` as what a model reads before calling:
```ts title="src/routes/weather.ts"
getForecast: k
.route({
method: 'GET',
path: '/forecast/:city',
summary: 'Look up tomorrow forecast for one city',
tool: true,
responses: {
200: ForecastSchema,
},
})
.handler(/* ... */),
```
See [Tools](/docs/tools) for the rest of what `tool` takes.
## Install the plugin
MCP is a [plugin](/docs/extend/create-plugin), named on `defineConfig` and served by `api.mount`:
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { mcpPlugin } from '@kizunajs/mcp';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
mcpPlugin({
name: 'My API',
}),
],
});
```
The endpoint answers at `/mcp` by default. On Next.js it is served by the catch-all route file that already serves your routes, so with `basePath: '/api'` it lands at `/api/mcp`.
## Which routes publish
Each route decides, so the plugin takes no list. A route with no `tool` is an HTTP endpoint and nothing more.
Two shapes never publish, even when they say `tool`:
- A route whose `contentType` is `multipart/form-data` or `application/x-www-form-urlencoded`, because tool input is JSON.
- A route whose response [streams](/docs/streaming), because a tool result is one value.
A [hidden](/docs/routes#hidden-routes) route can't say `tool` at all: the two together are a type error.
### What to leave unpublished
Every published tool's name, description, and input schema sits in the model's context on every turn, called or not, and the more tools there are the more often the model picks the wrong one. So publish deliberately:
- **What an assistant cannot use.** File uploads, CSV exports, anything returning bytes.
- **What exists for your own infrastructure.** Health checks, readiness probes, webhook receivers.
- **What you do not want reached by inference.** Deleting a workspace is a person's decision, guard or no guard. If it does publish, give it [`needsApproval`](/docs/tools#say-how-it-behaves).
## What each tool looks like
| Part | Where it comes from |
| --------------- | ------------------------------------------------------------------------------------------------------------------ |
| **Name** | The route key in snake_case, so `users.getUser` becomes `users_get_user` |
| **Title** | `tool.title` |
| **Description** | `tool.description` or the route's `summary`, then its `description`, its method and path, and what it requires |
| **Input** | `{ params, query, body }`, holding only the keys the route declares |
| **Output** | The success response's schema, so an assistant knows the shape before it calls |
| **Annotations** | The method's HTTP semantics, per [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110), and anything `tool` overrides |
The [specification](https://modelcontextprotocol.io/specification/latest/server/tools) allows the dot, but Claude Code and VS Code rewrite it before the name reaches the model, so publishing the rewritten form is what keeps your docs and the model's tool name the same. Names are capped at 128 characters. A key over that throws at startup, as do two keys that converge on one name.
The annotations tell a client how careful to be with a tool before calling it:
| Method | Hints set |
| ------------------------ | ----------------------------------- |
| `GET`, `HEAD`, `OPTIONS` | `readOnlyHint`, `idempotentHint` |
| `PUT` | `idempotentHint` |
| `DELETE` | `idempotentHint`, `destructiveHint` |
| `POST`, `PATCH` | none |
An absent hint is not a neutral one. MCP defaults `destructiveHint` and `openWorldHint` to true and `readOnlyHint` to false, so a client already treats `POST` and `PATCH` as destructive calls against an open world. The hints worth setting are the ones that make a tool safer than that, which is why `GET` gets `readOnlyHint` and `POST` gets nothing. Set one on the route's `tool` to say what the method cannot.
Handlers receive the same framework context they do over HTTP, passed through from the transport request, so one reading `req` or `c` keeps working as a tool.
## What the model reads
### From each route
A route's `summary` and `description` are what the tool carries:
```ts title="src/routes/users.ts"
searchUsers: k
.route({
method: 'GET',
path: '/users/search',
summary: 'Search users by name or email',
description: 'Matches a name or email substring, case insensitive. Returns at most 25 users, best match first.',
tool: true,
query: z.object({
term: z.string(),
}),
responses: {
200: z.array(UserSchema),
},
})
.handler(/* ... */),
```
The tool that reaches the model carries both, followed by the request line and the identities the route requires:
```text
Search users by name or email
Matches a name or email substring, case insensitive. Returns at most 25 users, best match first.
HTTP: GET /users/search
Requires: user
```
These are the same two fields that become `operation.summary` and `operation.description` in your OpenAPI document, and the doc comment on your generated Swift and Kotlin methods, which uses the summary and falls back to the description. Write them once for every reader. OpenAPI wants a short summary and a verbose account of the behaviour, which is what a model wants too, so naming the limit, the ordering, and the matching rule costs nothing and serves all three.
When the wording a model needs differs from the wording your API reference needs, `tool.description` overrides the summary for the model alone:
```ts title="src/routes/users.ts"
tool: {
description: 'Find a user before creating anything that belongs to one. Prefer this over listing every user.',
},
```
### From the whole server
`instructions` is a single string clients put in front of the model before it picks any tool. Kizuna builds one from your [groups](/docs/reference/k-groups), so the groups in your API arrive with their titles and descriptions, and your own text is appended to it:
```ts title="kizuna.config.ts"
mcpPlugin({
name: 'My API',
instructions: 'Resolve a workspace before creating members. Every timestamp is UTC.',
}),
```
Use it for what belongs to no single route: the order operations happen in, the conventions every route shares, which tool to reach for when two look alike.
## Authentication
Secured tools authenticate via the headers of the MCP transport request. The endpoint runs the [guards](/docs/authentication) that sit on your identities, exactly like the HTTP pipeline: the credential is extracted from the headers, the guard verifies it, the route's [`auth`](/docs/access-control) is checked, and the handler receives its typed identity context.
A route's identities appear in its tool description, along with the roles and permissions that go with them, so an assistant can tell it will be refused without spending a call to find out:
```text
Delete the workspace
HTTP: DELETE /workspace
Requires: member
Roles: owner
```
Configure the MCP client to send the credential as a header on the connection. For example, with Claude Code:
```sh title="Terminal"
claude mcp add --transport http my-api http://localhost:3000/mcp --header "Authorization: Bearer "
```
For an `apiKey` identity, send the header the identity names (e.g. `x-workspace-token`) instead.
When a guard denies the call, or the caller's role is not one the route accepts, the tool call returns an error result (`isError: true`) carrying the status and detail, so the assistant sees exactly why it was refused:
```json
{
"status": 401,
"body": {
"detail": "Unauthorized"
}
}
```
Routes with `auth: false` run without guards, credentials or not.
## Asking before it runs
A route with [`needsApproval`](/docs/tools#say-how-it-behaves) asks the person before the handler is reached, over MCP's elicitation:
```ts title="src/routes/workspace.ts"
tool: {
needsApproval: true,
},
```
The first call answers with the elicitation rather than a result, asking `Allow "Delete the workspace, owner only"?` from the route's `summary`, or its `title` when it has one. Approving runs the handler. Declining leaves it uncalled and answers `isError: true`.
## OAuth
Point `oauth` at your [oauth2 identity](/docs/oauth) and the endpoint serves the discovery and challenges the MCP authorization specification asks of an OAuth 2.1 resource server. MCP clients log in through your authorization server (better-auth, Auth0, Keycloak) on their own.
```ts title="kizuna.config.ts"
mcpPlugin({
oauth: {
resource: 'https://api.example.com/mcp',
scheme: 'user',
},
}),
```
`resource` is the canonical URI of the endpoint as clients reach it, and the audience your guard checks tokens against. `scheme` names the identity whose guard verifies the token on every request. The identity's `issuer` and flow scopes become the RFC 9728 metadata document, served at `/.well-known/oauth-protected-resource/mcp`.
With `oauth` configured, denials from that identity move to the HTTP level, where the specification puts them:
- No token, or a bad one, answers `401` with `WWW-Authenticate: Bearer resource_metadata="..."`.
- A token that lacks a permission its role holds answers `403` with `error="insufficient_scope"` and the permissions it is missing.
- A role that lacks a permission the route requires answers a plain `403`.
The guard runs once per request, its context reaches handlers under `auth.` as always, and every other identity keeps the in-band tool errors above.
## Options
| Option | Default | Description |
| -------------- | ---------------------- | -------------------------------------------------------------------- |
| `path` | `'/mcp'` | Path the endpoint is served from |
| `name` | `'MCP Server'` | Human-readable name shown to AI assistants |
| `version` | `'1.0.0'` | Semantic version string |
| `instructions` | built from your groups | Appended to the generated overview |
| `oauth` | off | Serve the endpoint as an OAuth 2.1 resource server ([OAuth](#oauth)) |
## Connecting clients
### Claude Code
```sh title="Terminal"
claude mcp add --transport http my-api http://localhost:3000/mcp
```
### VS Code
```json title=".vscode/mcp.json"
{
"mcp.servers": {
"my-api": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/mcp"]
}
}
}
```
### Cursor
```json title=".cursor/mcp.json"
{
"mcpServers": {
"my-api": {
"command": "npx",
"args": ["-y", "mcp-remote", "http://localhost:3000/mcp"]
}
}
}
```
## Tool input structure
Tool inputs use structured keys that mirror the Kizuna handler args:
```json
{
"params": { "id": "42" },
"query": { "page": 1, "limit": 25 },
"body": { "name": "Alice", "email": "alice@example.com" }
}
```
Only the keys the route declares are present.
## Tool responses
Every tool returns a JSON text block with the HTTP status and parsed response body:
```json
{
"status": 200,
"body": {
"id": "42",
"name": "Alice"
}
}
```
The same body is attached as `structuredContent`, matching the output schema the tool advertised, so a client can read the response as data rather than parsing the text.
Responses with status >= 400 set `isError: true` on the MCP result so the AI knows the call failed.
A route that declares `headers` reads them from the MCP request, the same headers that carry the credential.
## Standalone server
If you want to drive the transport yourself, for stdio or SSE, [`createMcpServer`](/docs/reference/create-mcp-server) returns a raw `McpServer`:
```ts title="src/mcp.ts"
import { createMcpServer } from '@kizunajs/mcp';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import kizuna from '../kizuna.config';
const server = createMcpServer(kizuna.api, {
name: 'My API',
version: '1.0.0',
});
await server.connect(new StdioServerTransport());
```
It takes one option the plugin does not: `onlyReadOnly` keeps only the methods RFC 9110 calls safe, so nothing the assistant reaches can change data.
## Reference
- [`mcpPlugin`](/docs/reference/mcp-plugin)
- [`createMcpServer`](/docs/reference/create-mcp-server)
- [Tools](/docs/tools) for what a route's `tool` declares
- [Create a Plugin](/docs/extend/create-plugin) to write your own
---
# OAuth
Source: /docs/oauth
---
title: OAuth
description: Verify tokens from an authorization server. Declare the identity, secure the routes, verify in the guard, and serve the discovery document.
---
OAuth support is new. How an identity declares its authorization server, and how the discovery document is served, will likely change while v2 is in beta, so pin your version if you depend on it.
When your tokens come from an authorization server such as better-auth, Auth0 or Keycloak, your API verifies them rather than issuing them. OAuth 2.1 calls that a resource server.
Four steps: declare the identity, secure the routes, verify in the guard, and serve the discovery document.
## Declare where tokens come from
A scope is a permission the token carries. Declare the permissions once, and the roles built from them, as on [Access Control](/docs/access-control):
```ts title="src/permissions.ts"
export const permissions = Kizuna.permissions({
users: ['read', 'write'],
});
```
```ts title="src/roles.ts"
export const roles = Kizuna.roles(permissions, {
member: {
users: ['read'],
},
admin: 'all',
});
```
The identity carries everything about the authorization server. `issuer` is the server's identifier ([RFC 8414](https://www.rfc-editor.org/rfc/rfc8414)), `flows` names its endpoints and the scopes it issues for the OpenAPI spec, and `resourceMetadata` is where your [discovery document](#serve-the-discovery-document) is served:
```ts title="src/identities.ts"
import { k } from './k';
export const user = k.identity
.oauth2({
issuer: 'https://auth.example.com',
resourceMetadata: 'https://api.example.com/.well-known/oauth-protected-resource',
flows: {
authorizationCode: {
authorizationUrl: 'https://auth.example.com/oauth2/authorize',
tokenUrl: 'https://auth.example.com/oauth2/token',
scopes: {
'users:read': 'Read users',
'users:write': 'Create and update users',
},
},
},
context: z.object({
userId: z.string(),
}),
roles,
})
.guard(/* below */);
```
Give the authorization server the same list, so a token can only carry permissions the code declares. With Better Auth:
```ts title="auth.ts"
oauthProvider({
scopes: ['openid', 'profile', 'email', 'offline_access', ...permissions.names],
});
```
For an OpenID Connect server, `k.identity.openIdConnect({ openIdConnectUrl, resourceMetadata, roles })` takes the place of `oauth2` above, and the issuer derives from the discovery URL.
## Secure the routes
A route names what it requires, as for any identity:
```ts title="src/routes/users.ts"
export const usersRoutes = k.routes.users({
createUser: k
.route({
method: 'POST',
path: '/users',
auth: {
identity: 'user',
requires: {
users: ['write'],
},
},
body: CreateUserSchema,
responses: {
201: UserSchema,
},
})
.handler(/* ... */),
});
```
`defineConfig` writes `users:write` into the route's security requirement, so the OpenAPI document lists it as the scope `createUser` needs.
## Verify in the guard
The guard receives the token as `oauth2`. Check the signature against the authorization server's JWKS, the issuer, and the audience, then return the user's role and the token's scopes as `permissions`:
The guard sits on the identity, so this continues the declaration above:
```ts title="src/identities.ts"
import { createRemoteJWKSet, jwtVerify } from 'jose';
import { permissions } from './permissions';
const jwks = createRemoteJWKSet(new URL('https://auth.example.com/oauth2/jwks'));
// ...continues `export const user = k.identity.oauth2({ ... })`
.guard(async ({ oauth2, deny }) => {
if (!oauth2) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
let claims;
try {
({ payload: claims } = await jwtVerify(oauth2.token, jwks, {
issuer: 'https://auth.example.com',
audience: 'https://api.example.com',
}));
} catch {
return deny({
status: 401,
body: {
detail: 'Invalid or expired token',
},
});
}
const tokenScopes = typeof claims.scope === 'string' ? claims.scope.split(' ') : [];
return {
userId: String(claims.sub),
role: claims.role === 'admin' ? 'admin' : 'member',
permissions: permissions.names.filter((name) => tokenScopes.includes(name)),
};
});
```
Name it under `auth.identities` on your config and a route's `auth: 'user'` runs it.
The caller holds what both the role and the token allow. When a route requires a permission the role holds but the token lacks, Kizuna answers `403` with the `insufficient_scope` challenge ([RFC 6750](https://www.rfc-editor.org/rfc/rfc6750)), so the client knows a new token would pass. When the role lacks it, the `403` has no challenge, since no token could help.
Both challenges point at the discovery document, and so does every `401` from `deny`:
```http
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://api.example.com/.well-known/oauth-protected-resource"
HTTP/1.1 403 Forbidden
WWW-Authenticate: Bearer error="insufficient_scope", scope="users:write", resource_metadata="https://api.example.com/.well-known/oauth-protected-resource"
```
## Serve the discovery document
Clients that do not know your authorization server find it through [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) Protected Resource Metadata at `/.well-known/oauth-protected-resource`. Serve it on the framework, next to `api.mount`:
```ts title="src/metadata.ts"
import { buildProtectedResourceMetadata } from 'kizunajs';
import { user } from './identities';
export const metadata = buildProtectedResourceMetadata({
resource: 'https://api.example.com',
scheme: user,
});
```
```ts title="src/index.ts"
app.get('/.well-known/oauth-protected-resource', (_req, res) => {
res.json(metadata);
});
api.mount(app);
```
```ts title="src/index.ts"
app.get('/.well-known/oauth-protected-resource', async () => metadata);
await api.mount(app);
```
```ts title="src/index.ts"
app.get('/.well-known/oauth-protected-resource', (c) => c.json(metadata));
api.mount(app);
```
```ts title="app/.well-known/oauth-protected-resource/route.ts"
import { metadata } from '@/server/metadata';
export function GET() {
return Response.json(metadata);
}
```
The document builds from the identity, so it says what you declared. `resource` is the canonical URI of your API, the same value your guard checks as the token audience.
Serve it when OAuth clients discover your API rather than being configured for it. A first-party app with a hardcoded authorization server never looks at it.
See [`ProtectedResourceMetadataSchema`](/docs/reference/protected-resource-metadata-schema) for the document's fields and builders.
## Reference
- [Authentication](/docs/authentication) for identities and guards
- [Access Control](/docs/access-control) for what a route's `auth` can say
- [`k.identity`](/docs/reference/k-identity)
- [`ProtectedResourceMetadataSchema`](/docs/reference/protected-resource-metadata-schema)
---
# OpenAPI
Source: /docs/openapi
---
title: OpenAPI
description: Generate an OpenAPI 3.1.0 document from your routes, and serve it with a reference UI.
---
`@kizunajs/openapi` generates an [OpenAPI 3.1.0](https://spec.openapis.org/oas/v3.1.0) document from your routes.
## Install it
`openApiPlugin` writes the document on `kizuna generate`, and serves it with an API reference UI on any adapter.
## Declare the plugin
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { openApiPlugin } from '@kizunajs/openapi';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
docsPath: '/docs',
}),
],
});
```
Each prop serves one route, and serves nothing until you give it a path:
| Prop | Serves | Path |
| ---------- | --------------------------------------- | --------------- |
| `docsPath` | the API reference UI, Scalar by default | anything |
| `jsonPath` | the document | ends in `.json` |
| `yamlPath` | the document as YAML | ends in `.yaml` |
```ts
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
docsPath: '/docs',
jsonPath: '/openapi.json',
});
```
The UI embeds the document, so `docsPath` alone is enough to browse the API. All three are [plugin routes](/docs/extend/create-plugin#routes), which are hidden, so they stay out of your clients and out of the document itself.
The routes are public. Gate them with your framework's own middleware if that is not what you want.
### Writing it to disk
Give the plugin an `output`, and `kizuna generate` writes the document there:
```ts title="kizuna.config.ts"
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
output: './openapi.yaml',
}),
```
It's the same document the plugin serves. The format comes from the extension, JSON for `.json` and YAML for anything else, and `kizuna generate --check` fails CI when the file falls behind your routes.
To write it from a script of your own instead, like a build step in CI, render it with [`generateOpenApi`](#generateopenapi):
```ts title="scripts/generate-openapi.ts"
import { writeFileSync } from 'node:fs';
import { generateOpenApi } from '@kizunajs/openapi';
import kizuna from '../kizuna.config';
const spec = generateOpenApi(kizuna.api);
writeFileSync('openapi.yaml', spec('yaml'));
```
```sh title="Terminal"
tsx scripts/generate-openapi.ts
```
## Which routes it documents
The document describes every route that isn't [hidden](/docs/routes#hidden-routes). A health check or a webhook route marked `hidden` isn't in it, so a document you serve publicly never maps out your internal routes.
To document every route the server serves, opt in:
```ts title="kizuna.config.ts"
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
output: './openapi.internal.yaml',
includeHidden: true,
}),
```
That's the one for your own team, written to disk or served behind auth.
## Serving it yourself
[`generateOpenApi`](#generateopenapi) renders the document directly:
```ts title="src/index.ts"
const spec = generateOpenApi(kizuna.api);
app.get('/openapi.yaml', (_req, res) => {
res.type('text/yaml; charset=utf-8').send(spec('yaml'));
});
```
Leave `yamlPath` unset when you do, or two handlers claim the path and whichever registered first wins. Kizuna sees collisions between your routes and a plugin's, but a route you register on the app yourself is invisible to it.
Mixing is the useful case: set `jsonPath` and leave `docsPath` unset, and the plugin serves the document while you render your own UI.
### Swagger instead of Scalar
```ts
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
provider: 'swagger',
});
```
Point `cdnUrl` at a self-hosted copy for air-gapped deployments or a strict CSP.
## `generateOpenApi`
`generateOpenApi` returns a renderer. Call it with `'json'` for the document object or `'yaml'` for a YAML string. Everything it needs, `info` included, comes off the api, declared once on [`openApiPlugin`](#declare-the-plugin).
```ts title="scripts/generate-openapi.ts"
import { generateOpenApi } from '@kizunajs/openapi';
import kizuna from '../kizuna.config';
const spec = generateOpenApi(kizuna.api);
spec('json'); // OpenApiDocument object
spec('yaml'); // YAML string
```
## Deprecation
Routes with `deprecated` and fields with `.meta({ deprecated: ... })` get `deprecated: true` in the generated spec, with no extra options here. Routes with a deprecation `date` or a `sunset` get the `Deprecation`, `Sunset`, and `Link` headers they send documented on every response. See [Deprecations](/docs/deprecations).
## Examples
Give a field an example with `.meta({ example: ... })`:
```ts
const UserSchema = Kizuna.model({
title: 'User',
schema: z.object({
id: z.string().meta({
example: 'usr_k7f3q9',
}),
email: z.email().meta({
example: 'ada@example.com',
}),
}),
});
```
Pass an array for several. It lands as JSON Schema `examples` on the field's schema, and documentation UIs like Scalar and Swagger pick it up from there.
## Options
They go on `openApiPlugin` in your config, and `generateOpenApi` reads them from there.
```ts title="kizuna.config.ts"
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
description: 'Optional description',
},
servers: [
{
url: 'https://api.example.com',
description: 'Production',
},
{
url: 'http://localhost:3000',
description: 'Development',
},
],
setOperationId: true,
});
```
| Option | Default | Description |
| ----------------- | -------- | --------------------------------------------------------------------------------------- |
| `info` | required | OpenAPI `info` object |
| `output` | none | Where `kizuna generate` writes the document. `.json` for JSON, anything else for YAML |
| `includeHidden` | `false` | Document [hidden](/docs/routes#hidden-routes) routes too |
| `servers` | none | Server URLs |
| `setOperationId` | `false` | Set `operationId` from the route key. Use `'concatenated-path'` to include parent keys. |
| `operationMapper` | none | Callback to transform each operation before it is added to the spec |
| `derivedHead` | `false` | Document the derived `head` operation on every `GET` path without a declared one |
## Security
Security comes from what you declared. The [identities](/docs/authentication) you name under `auth.identities` on `defineConfig` are emitted as `components.securitySchemes`, and each route's `auth` becomes that operation's `security`, with the permissions an OAuth route requires as its scopes, the roles a route accepts under `x-kizuna-roles`, and the permissions it requires under `x-kizuna-requires`. There are no generator options for it, so the spec cannot disagree with what the server enforces.
```ts title="src/identities.ts"
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(/* ... */);
```
```yaml title="openapi.yaml"
# generated
components:
securitySchemes:
user:
type: http
scheme: bearer
paths:
/workspace:
get:
security:
- user: []
```
Routes with `auth: false` get no `security` entry. A [`custom`](/docs/reference/k-identity#custom-identities) identity also emits no `security`, since OpenAPI can't describe its credential, but its routes carry an `x-kizuna-guarded` extension so they stay distinguishable from public ones.
## Validation errors
Routes with a `body` or `query` schema automatically include a `400` validation error response, matching what Kizuna returns when request data fails validation. A route that declares its own `400` keeps it; nothing is added.
## Refusals
A route whose [`auth`](/docs/access-control) names an identity includes `401` and `403` as [Problem Details](/docs/reference/problem-details-schema). The `401` documents the `WWW-Authenticate` header too, required when every identity on the route has a challenge and optional when only some do. A route behind an API key declares no header.
## Streams
A response declared with [`stream`](/docs/streaming) is documented under `text/event-stream`, with a schema describing one message as `event`, `data`, `id`, and `retry`, one `oneOf` branch per named event. OpenAPI 3.1 has no field for a sequence of messages, so it sits under `schema`. OpenAPI 3.2 adds `itemSchema` with this shape, and the generator moves to it when it targets 3.2.
## Reference
- [`generateOpenApi`](/docs/reference/generate-openapi)
- [`openApiPlugin`](/docs/reference/openapi-plugin)
## Breaking changes
[`diffAgainst`](/docs/breaking-changes) compares your API against a git ref and reports what each change costs a caller.
## Scheduled jobs
[Scheduled jobs](/docs/jobs) live under `jobs` on your config, not `routes`, so they are not in the document.
---
# Project Structure
Source: /docs/project-structure
---
title: Project Structure
description: Where your declarations, your config, and your clients live.
---
Kizuna has no opinion about your file layout. A single file works. The two fixed points are `kizuna.config.ts` at the root of your app, which is where the CLI looks, and the `k` you declare everything against.
The layout below is the one we use ourselves. It goes from a handful of routes to a few hundred without anything moving.
```
my-api/
├── kizuna.config.ts # defineConfig, default-exported
├── kizuna.types.ts # written by kizuna generate
└── src/
├── k.ts # new Kizuna(), exports k
├── groups.ts # k.groups
├── identities.ts # k.identity.bearer(...).guard(...)
├── request-context.ts # k.requestContext(...).handler(...)
├── permissions.ts # Kizuna.permissions
├── roles.ts # Kizuna.roles
├── jobs.ts # k.jobs
├── plugins/
│ ├── email/
│ │ ├── index.ts # definePlugin
│ │ └── types.ts # its schemas and types
│ └── tenancy/
│ └── index.ts
├── routes/
│ ├── users.ts # k.routes.users({ ... })
│ ├── events.ts
│ ├── health.ts
│ └── index.ts # lists the route files
└── index.ts # kizuna.api.mount(app)
```
Each route carries the handler that answers it. The same holds for the rest: a guard sits on its identity, a resolver sits on its request context value, and a job's handler sits on the job.
- **`k.ts`** constructs the surface once, typed by the `Config` in `kizuna.types.ts`. Everything else imports `k` from here.
- **`routes/`** holds one file per group, each calling `k.routes.`, with an `index.ts` listing them so the config has one import to make. See [splitting routes across files](/docs/routes#splitting-routes-across-files).
- **`identities.ts`** names who can call the API, and each identity's `guard` is what authenticates them. See [Authentication](/docs/authentication).
- **`roles.ts`** names who a caller can be, and each route's `auth` says who may call it. See [Access Control](/docs/access-control).
- **`plugins/`** holds your app's own building blocks, one folder each, with what your handlers call. Every handler and job reaches them under `plugins`, typed. See [Create a Plugin](/docs/extend/create-plugin).
- **`kizuna.config.ts`** is where the adapter, the routes, the identities, the jobs and the plugins come together. A browser imports the [generated client](/docs/clients/fetch) written from it.
## The `@/` alias
Examples throughout these docs import from `@/k` and `@/routes`. That is `@/` pointing at `src/`, which `create-next-app` sets up for you. Anywhere else, declare it yourself:
```json title="tsconfig.json"
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}
```
## Next steps
- [Routes](/docs/routes) covers declaring a route and everything its handler receives
- [Adapters](/docs/adapters/express) covers the setup for each framework
---
# Quickstart
Source: /docs/quickstart
---
title: Quickstart
description: Declare your routes, serve them on your framework, and call them from a typed client in 8 minutes.
---
## Installation
Install `kizunajs`, your framework's adapter, Zod 4 for the schemas, and the CLI.
Kizuna installs from the `beta` tag until 2.0.0 ships. The 1.x line published under a different name and is no longer maintained, so it
gets no fixes and no security backports.
Enable `strict` in your `tsconfig.json`. Kizuna's inference depends on it.
```json title="tsconfig.json"
{
"compilerOptions": {
"strict": true
}
}
```
## Start with the config
`kizuna.config.ts` sits at the root of your app. Start with your framework's adapter:
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { nextAdapter } from '@kizunajs/next'; // or express, fastify, hono
export default defineConfig({
adapter: nextAdapter(),
typescript: {
outputFile: './kizuna.types.ts',
},
});
```
The adapter puts that framework's own request in every handler's args, typed.
## Add the generate script
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate",
"kizuna:check": "kizuna generate --check"
}
}
```
```bash
pnpm kizuna:generate
```
That writes the `Config` that types everything you declare next. Run it after every change, and `kizuna:check` in CI.
Say so where it gets read:
```md title="AGENTS.md"
After changing a route, run `pnpm kizuna:generate`.
```
## Declare the routes
Keep one `k` for the API and export it:
```ts title="src/k.ts"
import { Kizuna } from 'kizunajs';
import type { Config } from '../kizuna.types';
export const k = new Kizuna();
```
`k` is typed by the `Config` that `kizuna:generate` writes, so every name you use is checked against what your config declares. See [`new Kizuna()`](/docs/reference/Kizuna).
Each route pairs a method and path with Zod schemas, and carries the handler that answers it:
```ts title="src/routes/users.ts"
import { Kizuna } from 'kizunajs';
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../k';
export const UserSchema = Kizuna.model({
title: 'User',
schema: z.object({
id: z.string(),
name: z.string(),
email: z.email(),
}),
});
export const users = k.routes({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: z.object({
page: z.int().min(1).default(1),
limit: z.int().min(1).max(100).default(10),
}),
responses: {
200: z.object({
users: z.array(UserSchema),
total: z.number(),
}),
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
})),
createUser: k
.route({
method: 'POST',
path: '/users',
body: z.object({
name: z.string().min(1),
email: z.email(),
}),
responses: {
201: UserSchema,
400: ProblemDetailsSchema,
},
})
.handler(async ({ body }) => {
const existing = await db.users.findByEmail(body.email);
if (existing) {
return {
status: 400,
body: {
detail: 'Email already in use',
},
};
}
return {
status: 201,
body: await db.users.create(body),
};
}),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params }) => {
const user = await db.users.findById(params.id);
if (!user) {
return {
status: 404,
body: {
detail: 'User not found',
},
};
}
return {
status: 200,
body: user,
};
}),
});
```
The handler's `query`, `body` and `params` are typed from the declaration right above it, and its return is checked against that route's `responses`.
[`Kizuna.model`](/docs/reference/kizuna-model) names `UserSchema`, so it lands as `User` in the generated client and `components.schemas.User` in the OpenAPI document rather than being written out at each use.
Add them to the config:
```ts title="kizuna.config.ts"
import { users } from './src/routes/users';
export default defineConfig({
adapter: nextAdapter(),
routes: [users],
});
```
## Mount it
```ts title="src/app/api/[...kizuna]/route.ts"
import kizuna from '../../../../kizuna.config';
export const { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } = kizuna.api.mount({
basePath: '/api',
});
```
This is the one step that differs per framework. [Express, Fastify and Hono](/docs/adapters/express) each mount their own way.
## Call it from a typed client
Add `fetchClient` to the config, pointed at the file you want written:
```ts title="kizuna.config.ts"
import { fetchClient } from '@kizunajs/fetch';
export default defineConfig({
adapter: nextAdapter(),
routes: [users],
clients: [
fetchClient({
output: './src/lib/api-client.generated.ts',
}),
],
});
```
```bash
pnpm kizuna:generate
```
Wrap it once with the base URL you serve on:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'http://localhost:3000/api',
});
```
```tsx title="page.tsx"
import { apiClient } from '@/lib/api-client';
export default async function UsersPage() {
const { body } = await apiClient.listUsers({
query: {
page: 1,
limit: 10,
},
});
// body.users is User[]
return (
{body.users.map((user) => (
{user.name}
))}
);
}
```
A route with more than one status narrows on `status`:
```tsx title="actions.ts"
'use server';
import { apiClient } from '@/lib/api-client';
export async function createUser(name: string, email: string) {
const result = await apiClient.users.createUser({
body: {
name,
email,
},
});
// result.status is 201 | 400, and TypeScript narrows the body from there
if (result.status === 201) {
return result.body.id;
}
throw new Error(result.body.detail);
}
```
## Next steps
- [Routes](/docs/routes) covers declaring a route and everything its handler receives
- [Authentication](/docs/authentication) declares identities and the guards on them, [Access Control](/docs/access-control) says who may call each route, and handler types and OpenAPI security follow
- [Adapters](/docs/adapters/express) covers Express, Fastify, Hono, and Next.js setup and options
- [Fetch client](/docs/clients/fetch) covers headers, custom fetch, and error handling
- [OpenAPI generation](/docs/openapi) serves a spec alongside your API
---
# Request Context
Source: /docs/request-context
---
title: Request Context
description: Declare request-scoped values every handler receives, typed, resolved once per request.
---
A **request context** is a value every handler receives, resolved once per request: an analytics session, a logger, the caller's locale.
## Declare the value and how it resolves
`k.requestContext` takes the schema of what handlers receive, and `.handler()` takes the resolver that fills it. Add `headers` when the value comes off the request:
```ts title="src/request-context.ts"
import { z } from 'zod';
import { getHeaderValue } from 'kizunajs';
import { k } from './k';
export const analytics = k
.requestContext({
headers: z.object({
'x-posthog-session-id': z.string().optional(),
}),
context: z.object({
sessionId: z.string().nullable(),
}),
})
.handler(({ headers }) => ({
sessionId: getHeaderValue(headers['x-posthog-session-id']) ?? null,
}));
```
The resolver's `headers` are typed by the schema right above it, and its return is checked against `context`.
## Name it on your config
Name it under what handlers will read it by:
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { analytics } from './src/request-context';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
requestContext: {
analytics,
},
});
```
## Read it in the handler
Every handler receives the resolved value under `requestContext`, keyed by the name:
```ts title="src/routes/notifications.ts"
listEvents: k
.route({
method: 'GET',
path: '/events',
responses: {
200: EventListSchema,
},
})
.handler(({ query, requestContext }) => {
track(requestContext.analytics.sessionId, 'listEvents');
return {
status: 200,
body: {
events: findEvents(query),
},
};
}),
```
## Two kinds of declaration
A value the server derives on its own takes the context schema alone:
```ts title="src/request-context.ts"
export const logger = k
.requestContext(
z.object({
requestId: z.string(),
})
)
.handler(() => ({
requestId: randomUUID(),
}));
```
A value that comes from the caller declares the `headers` it reads. Every client types them, so a caller sets them once and the resolver reads them by name:
```ts title="src/request-context.ts"
export const locale = k
.requestContext({
headers: z.object({
'accept-language': z.string().optional(),
}),
context: z.object({
language: z.enum(['en', 'nb']),
}),
})
.handler(({ headers }) => ({
language: negotiateLanguage(headers['accept-language']) ?? 'en',
}));
```
`headers` is what arrives on the wire, `context` is what handlers get, and the resolver is the step between them.
## Resolvers
A resolver receives one object:
| Argument | What it is |
| -------------- | --------------------------------------------------------------------------------------------------------- |
| `headers` | The declared headers, typed by the schema. A declaration without one gets the adapter's raw header record |
| `params` | The matched route's path params, as strings, so a resolver can read `params.workspaceId` |
| native request | The adapter's own request objects |
The native objects differ per adapter:
| Adapter | Arguments |
| ------- | ------------------ |
| Express | `req`, `res` |
| Fastify | `request`, `reply` |
| Hono | `c` |
| Next.js | `request` |
```ts title="src/request-context.ts"
.handler(({ headers, req }) => ({
sessionId: getHeaderValue(headers['x-posthog-session-id']) ?? req.cookies.posthogSessionId ?? null,
}));
```
A resolver may be async, and its return is typed against the declaration's `context` schema. Each one gets the request and nothing else, so two resolvers that need the same lookup each do it.
A throw inside a resolver fails the request the way a throw inside a handler does, answering `500` unless the adapter's `onError` says otherwise. Resolvers run on every route, so keep them cheap and let them fall back rather than throw.
## Sending the headers from a client
The fetch client takes the declared headers under `requestContext` and sends them with every request:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'https://api.example.com',
requestContext: {
'x-posthog-session-id': sessionId,
},
});
```
The Swift and Kotlin clients take a `RequestContext` in their initializer:
```swift title="APISetup.swift"
let client = APIClient(
baseURL: url,
requestContext: .init(
xPosthogSessionId: sessionId
)
)
```
```kotlin title="APISetup.kt"
val client = APIClient(
baseUrl = baseUrl,
requestContext = APIClient.RequestContext(
xPosthogSessionId = sessionId
)
)
```
The values are typed from the header schemas, so a required header is required here too.
## Where it runs
Resolvers run on every route, public ones included, before the guards, so a [guard](/docs/reference/k-identity) reads the resolved values under `requestContext` the way a handler does. The [job](/docs/jobs) handlers take only their `input`, so they see none of it. [MCP](/docs/mcp) tool calls run the resolvers the same way the HTTP pipeline does, reading the headers of the transport request.
## Request context or a guard
Both run before the handler and both put a typed value in its args. They answer different questions:
| | Request context | Guard |
| ----------- | ----------------------- | ---------------------------------- |
| Runs on | Every route | The routes whose `auth` names it |
| Runs | Before the guards | After every resolver has run |
| Can reject | No | Yes, with `deny({ status, body })` |
| Handler arg | `requestContext.` | `auth.` |
If the answer decides whether the request may proceed, it belongs in a [guard](/docs/authentication). If it is something the handler wants to have on hand, it belongs here.
## Reference
- [`k.requestContext`](/docs/reference/k-request-context)
- [`defineConfig`](/docs/reference/define-config)
- [Fetch client](/docs/clients/fetch)
---
# Resend
Source: /docs/resend
---
title: Resend
description: Send email and newsletters from your handlers, and act on what Resend reports back.
---
The Resend plugin is new and still settling. Its options and exports may change while v2 is in beta, so pin your version if you depend on them.
`@kizunajs/resend` connects your API to [Resend](https://resend.com). Handlers send email and manage newsletters through `plugins.resend`, and Resend's webhook events reach functions you write.
## Install the plugin
```ts title="kizuna.config.ts"
import { resendPlugin } from '@kizunajs/resend';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
resendPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Kizuna ',
}),
],
});
```
A missing API key, or a `from` Resend wouldn't accept, stops the app at startup, naming the field. `from` is an address, or a name and an address like `Kizuna `.
## Send an email
Every route and job handler reaches the plugin at `plugins.resend`:
```ts title="src/routes/users.ts"
.handler(async ({ body, plugins }) => {
const user = await db.users.create(body);
await plugins.resend.sendEmail({
to: user.email,
subject: 'Welcome',
html: `
Welcome, ${user.name}.
`,
});
return {
status: 201,
body: user,
};
}),
```
`from` comes from the plugin's options unless the email names its own.
## React Email
Pass a component as `react` instead of `html`, and Resend renders it. Install `@react-email/render` too, which Resend's SDK loads when an email has `react`:
```tsx
await plugins.resend.sendEmail({
to: user.email,
subject: 'Welcome',
react: ,
});
```
`sendBroadcast` takes `react` the same way.
## Newsletters
A list is a Resend segment, plus the topic its contacts opt in and out of. Name each one once, and handlers use the name:
```ts title="kizuna.config.ts"
resendPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Kizuna ',
lists: {
weekly: {
segmentId: 'seg_123',
topicId: 'top_456',
},
},
}),
```
`subscribe` adds a contact to a list, creating the contact when it's new, and returns Resend's id for it:
```ts title="src/routes/newsletter.ts"
subscribe: k
.route({
method: 'POST',
path: '/newsletter/subscribers',
auth: 'user',
responses: {
204: z.void(),
},
})
.handler(async ({ auth, plugins }) => {
const user = await db.users.findById(auth.user.userId);
const { contactId } = await plugins.resend.subscribe({
email: user.email,
list: 'weekly',
});
await db.users.update(user.id, {
resendContactId: contactId,
});
return {
status: 204,
};
}),
```
Contact events carry it back as `event.data.id`, which the [webhook example](#webhooks) uses to find the user.
`unsubscribe` takes a contact off one list, or off everything when you leave `list` out:
```ts
await plugins.resend.unsubscribe({
email: 'ada@example.com',
list: 'weekly',
});
```
When a user changes their email, `changeEmail` moves their contact to the new address, keeping its name, lists and topics:
```ts title="src/routes/account.ts"
changeEmail: k
.route({
method: 'PATCH',
path: '/account/email',
auth: 'user',
body: z.object({
email: z.email(),
}),
responses: {
204: z.void(),
},
})
.handler(async ({ auth, body, plugins }) => {
const user = await db.users.findById(auth.user.userId);
const { contactId } = await plugins.resend.changeEmail({
from: user.email,
to: body.email,
});
await db.users.update(user.id, {
email: body.email,
resendContactId: contactId,
});
return {
status: 204,
};
}),
```
Resend can't change a contact's email, so this creates a new contact and removes the old one, which is why the id changes too.
`sendBroadcast` sends to everyone on a list, now or at `scheduledAt`:
```ts
await plugins.resend.sendBroadcast({
list: 'weekly',
subject: 'This week',
html: newsletterHtml,
scheduledAt: 'in 2 days',
});
```
Resend fills placeholders in a broadcast for each contact. Every newsletter needs the unsubscribe link:
```ts
await plugins.resend.sendBroadcast({
list: 'weekly',
subject: 'This week',
html: `
Hi {{{FIRST_NAME|there}}},
${news}
Unsubscribe
`,
});
```
The text after `|` is used when a contact has no first name. See [Resend's broadcast docs](https://resend.com/docs/api-reference/broadcasts/create) for every placeholder.
To check a newsletter before it goes out, send it to yourself first with `sendEmail`. Resend only fills placeholders in broadcasts, so a test through `sendEmail` shows `{{{FIRST_NAME}}}` as it's written. Render the test with your own name instead:
```ts
const newsletter = (firstName: string) => `
Hi ${firstName},
${news}
`;
await plugins.resend.sendEmail({
to: editor.email,
subject: 'This week',
html: newsletter(editor.firstName),
});
await plugins.resend.sendBroadcast({
list: 'weekly',
subject: 'This week',
html: newsletter('{{{FIRST_NAME|there}}}'),
});
```
A list without a `topicId` works too. Unsubscribing from it removes the contact from its segment.
## Webhooks
Create a webhook in Resend pointing at `/resend/webhooks`, and pass its signing secret. The plugin checks each delivery's signature against the body as it was sent, then runs your function for the event's type:
```ts title="kizuna.config.ts"
import { resendEvents } from './src/resend-events';
resendPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Kizuna ',
webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
on: resendEvents,
}),
```
Write the functions in a file of their own with `defineResendEvents`. Here, someone who unsubscribes through Resend's link loses their consent in your own database too. Give it your `Config`, the way you give it to `new Kizuna()`, and `jobs` and `plugins` are typed from your app:
```ts title="src/resend-events.ts"
import { defineResendEvents } from '@kizunajs/resend';
import type { Config } from '../kizuna.types';
import { db } from './db';
export const resendEvents = defineResendEvents({
'contact.updated': async ({ event }) => {
const user = await db.users.findByResendContactId(event.data.id);
if (user === null) return;
await db.users.update(user.id, {
newsletterConsent: !event.data.unsubscribed,
});
},
});
```
Each function receives:
| Argument | What it is |
| ------------ | ------------------------------------------------- |
| `event` | The event, typed from Resend's own types |
| `deliveryId` | The delivery's id, the same on every retry of it |
| `jobs` | Your app's jobs, to queue work |
| `plugins` | Your installed plugins, `plugins.resend` included |
Anything else it needs, like your database, it imports. An event with no function is acknowledged and dropped. A delivery whose signature doesn't match is answered with `400`, and nothing runs.
The route is [hidden](/docs/routes#hidden-routes), so it stays out of your clients and the OpenAPI document.
### Keep the functions quick
Resend waits a few seconds for an answer, then sends the event again. For anything slow, queue a [job](/docs/jobs) from the function and return. On a serverless host like Vercel, work started after the response is sent can be cut off, so there it's the only reliable way.
### Handle an event twice safely
Resend can deliver the same event more than once. Skip a `deliveryId` you've already handled.
### Tag emails with your own ids
Tags you set when sending come back on every event for that email, in `event.data.tags`:
```ts
await plugins.resend.sendEmail({
to: user.email,
subject: 'Welcome',
html,
tags: [
{
name: 'orderId',
value: order.id,
},
],
});
```
Contact events carry no tags.
## Moving the webhook route
The plugin serves its routes under `/resend`. When that clashes with your own routes, pass another base path:
```ts title="kizuna.config.ts"
resendPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Kizuna ',
webhookSecret: process.env.RESEND_WEBHOOK_SECRET,
basePath: '/integrations/resend',
}),
```
## In development
`intercept` catches every email and forwards it to your own inbox instead of its real recipients:
```ts title="kizuna.config.ts"
resendPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Kizuna ',
intercept: {
enabled: process.env.NODE_ENV !== 'production',
forwardTo: process.env.EMAIL_FORWARD_TO,
deliverTo: ['@example.com'],
subjectPrefix: '[dev]',
},
}),
```
`enabled` says whether it's on. When it is, `forwardTo` has to be set, so a missing `EMAIL_FORWARD_TO` stops the app at startup instead of emailing real people.
| Option | Default | Description |
| --------------- | ------------------------------- | -------------------------------------------------------------------------------------------------------------- |
| `enabled` | required | Whether emails are intercepted |
| `forwardTo` | required when `enabled` is true | Where every email is forwarded, one address or several |
| `deliverTo` | none | Addresses, or whole domains like `@example.com`, whose emails are delivered as normal, with `forwardTo` in bcc |
| `subjectPrefix` | none | Put in front of every intercepted email's subject |
Each intercepted email carries who it was for in `X-Intercepted-To`, `X-Intercepted-Cc` and `X-Intercepted-Bcc` headers. Use `delivered@resend.dev` as `forwardTo` when nobody should get anything.
Broadcasts go to a segment, so `intercept` doesn't reach them. Point your `lists` at a test segment in development instead.
## Errors
Resend's SDK answers with `{ data, error }` instead of throwing. The plugin throws a `ResendRequestError` instead, so a failed call fails the handler that made it, and kizuna answers `500` and logs it.
A call Resend rate-limits is tried again after the wait its `retry-after` header asks for, up to three times, before it fails.
## Anything else
`plugins.resend.client` is the Resend client itself, for anything the plugin doesn't cover:
```ts
await plugins.resend.client.domains.list();
```
## Options
| Option | Default | Description |
| --------------- | --------- | ----------------------------------------------------------------------- |
| `apiKey` | required | The Resend API key |
| `from` | required | The sender every email and broadcast uses unless it names its own |
| `lists` | none | Lists by name, each a `segmentId` and an optional `topicId` |
| `webhookSecret` | none | The webhook's signing secret. Set it to serve the webhook route |
| `on` | none | A function per webhook event type. Needs `webhookSecret` |
| `intercept` | none | Catch every email in development, see [In development](#in-development) |
| `resend` | none | Resend's own `ResendOptions`, passed to its client |
| `basePath` | `/resend` | Where the webhook route is served |
---
# Routes
Source: /docs/routes
---
title: Routes
description: Declare a route, the schemas it takes and answers with, and the handler that serves it.
---
A route is a method, a path, the schemas it takes and answers with, and the handler that serves it. Everything else is read from that: [`defineConfig`](/docs/reference/define-config) assembles your routes into the api you mount, and the generators write your OpenAPI document and your clients from the same declarations.
## Create the surface
Construct it once, usually in `src/k.ts`, and export `k`. Its type parameter is the `Config` that `kizuna generate` writes from your `kizuna.config.ts`, and that is what types everything a handler receives and checks every name you write.
```ts title="src/k.ts"
import { Kizuna } from 'kizunajs';
import type { Config } from '../kizuna.types';
export const k = new Kizuna();
```
Declare your groups beside it, so routes have somewhere to be filed. Each group becomes a name `k.routes` offers, and a tag in the OpenAPI document.
```ts title="src/groups.ts"
import { k } from './k';
export const groups = k.groups({
users: 'Users',
});
```
## Declare your routes
`k.route` takes what the route is, and `.handler()` takes what answers it. `k.routes.users` files them under the Users group, at the bottom of the file:
```ts title="src/routes/users.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../k';
export const UserSchema = z.object({
id: z.string(),
name: z.string(),
email: z.email(),
});
const listUsers = k
.route({
method: 'GET',
path: '/users',
query: z.object({
page: z.int().min(1).default(1),
limit: z.int().min(1).max(100).default(10),
}),
responses: {
200: z.object({
users: z.array(UserSchema),
total: z.number(),
}),
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
}));
const createUser = k
.route({
method: 'POST',
path: '/users',
body: z.object({
name: z.string().min(1),
email: z.email(),
}),
responses: {
201: UserSchema,
400: ProblemDetailsSchema,
},
})
.handler(async ({ body }) => ({
status: 201,
body: await db.users.create(body),
}));
export const users = k.routes.users({
listUsers,
createUser,
});
```
The handler's `query` and `body` are typed from the declaration right above it, and its return is checked against that route's `responses`. See [Routes](/docs/routes) for everything a handler receives.
A route only a generator or a client reads can skip `.handler()`. One your config serves cannot.
### Route fields
| Field | Required | Description |
| ------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `method` | Yes | `GET` `POST` `PUT` `PATCH` `DELETE` `HEAD` `OPTIONS` |
| `path` | Yes | URL path. Use `:name` for path parameters |
| `responses` | Yes | Response schemas keyed by status code |
| `pathParams` | No | Path parameter schema, keyed by placeholder name |
| `body` | No | Request body schema |
| `query` | No | Query string schema |
| `headers` | No | Request headers schema |
| `contentType` | No | `'application/json'` (default), `'multipart/form-data'`, `'application/x-www-form-urlencoded'` |
| `summary` | No | Short description shown in OpenAPI, and what a model reads when the route publishes as a tool |
| `description` | No | The longer account, for OpenAPI and for a model |
| `groups` | No | More [groups](/docs/reference/k-groups) to list the route under, beside the one `k.routes` files it in |
| `auth` | No | The identity this route requires, and the roles or permissions it accepts. Required once your config declares an identity, so public takes an explicit `false`. See [Access Control](/docs/access-control) |
| `tool` | No | Publish this route as a [tool](/docs/tools) a model can call |
| `rawBody` | No | `true` to receive the body as sent, as `rawBody`, for checking a signature. See [below](#verifying-signed-requests) |
| `hidden` | No | `true` to leave it out of the generated clients and the OpenAPI document. See [below](#hidden-routes) |
| `deprecated` | No | `true`, or the migration message. See [Deprecations](/docs/deprecations) |
| `cache` | No | The `Cache-Control` policy its responses send. See [Caching](/docs/caching) |
### Typing path parameters
`params` is typed from the path itself, so `/users/:id` gives the handler `params.id` as a string with nothing else to declare. Add `pathParams` when you want it parsed or narrowed:
```ts
getUser: k
.route({
method: 'GET',
path: '/users/:id',
pathParams: z.object({
id: z.uuid(),
}),
responses: {
200: UserSchema,
},
})
.handler(/* ... */),
```
Its keys are checked against the path, so a name the path does not carry is a compile error naming the path it looked in:
```text
pathParams declares "userId", which is not a parameter in path "/users/:id"
```
Each value must be a scalar, since a path segment arrives as one string. Lists belong in `query`. To parse one into something richer, use `z.string().transform(...)`:
```ts
pathParams: z.object({
tags: z.string().transform((value) => value.split(',')),
}),
```
### What each part can carry
A route can only declare what its part of the request can send, and `k.routes` throws on anything else when the config loads:
| Part | Carries |
| ------------------------------------------- | ------------------------------------------------------------- |
| `pathParams` | a value: a string, number, boolean, enum, date or bigint |
| `query` | a value, or a list of values |
| `headers` | a value |
| a `multipart/form-data` body | values, lists of values, and files declared with `FileSchema` |
| an `application/x-www-form-urlencoded` body | values and lists of values |
| a JSON body | anything JSON can hold |
An object in a query or a form can't be sent. Split it into fields of their own, or move it to a JSON body.
## Handler arguments
Each handler receives an object with the validated inputs for that route:
| Property | Available when |
| ------------------ | ------------------------------------------------------------------ |
| `params` | Route path has `:param` placeholders |
| `query` | Route has a `query` schema |
| `body` | Route has a `body` schema |
| `headers` | Route has a `headers` schema |
| `throwError` | Always |
| `auth` | Route's [`auth`](/docs/access-control) names an identity |
| `requestContext` | Config declares [request context](/docs/request-context) |
| `plugins` | Config declares [plugins](/docs/config#using-what-a-plugin-offers) |
| `jobs` | Config declares [jobs](/docs/jobs) |
| `req`, `res` | Express adapter |
| `c` | Hono adapter |
| `request`, `reply` | Fastify adapter |
| `request` | Next.js adapter |
Which framework object arrives is decided by the `adapter` your config names, so a handler reads `req` or `c` without importing either framework's types.
## Identity context
When a route's [`auth`](/docs/access-control) names an identity, the handler receives that identity's context under `auth`, keyed by the identity's name. The context is whatever its guard returned, typed by the identity's `context` schema, with `role` beside it when the identity declares roles, and `permissions` when those roles come from a catalog. A row check goes here too, with `auth` in hand. See [Access Control](/docs/access-control#one-row).
```ts title="src/routes/members.ts"
listMembers: k
.route({
method: 'GET',
path: '/members',
auth: 'user',
responses: {
200: MemberListSchema,
},
})
.handler(({ auth }) => ({
status: 200,
body: {
members: findMembersExcept(auth.user.userId),
},
})),
```
A route requiring several identities receives all of them under `auth`:
```ts title="src/routes/workspace.ts"
.handler(({ body, auth }) => {
// auth.user.userId and auth.member.workspaceUserId are both there, typed
});
```
A route whose `auth` names `roles` or `requires` is checked before the handler runs, so the handler never asks whether the caller may be there. It reads the role when it needs it for something else, such as an audit line:
```ts title="src/routes/workspace.ts"
deleteWorkspace: k
.route({
method: 'DELETE',
path: '/workspace',
auth: {
identity: 'member',
requires: {
workspace: ['delete'],
},
},
responses: {
200: OkSchema,
},
})
.handler(async ({ auth }) => {
await audit('workspace.deleted', {
by: auth.member.workspaceUserId,
as: auth.member.role,
});
return {
status: 200,
body: {
ok: true,
},
};
}),
```
Values declared as [request context](/docs/request-context) arrive the same way, under `requestContext` on every route.
## Return type
Return `{ status, body }` matching one of the route's declared responses. TypeScript enforces that the status and body match.
```ts
// Route: responses: { 200: UserSchema, 404: ProblemDetailsSchema }
return {
status: 200,
body: user,
};
return {
status: 404,
body: {
detail: 'User not found',
},
};
```
For routes with typed response headers, include `headers` too:
```ts
return {
status: 200,
body: user,
headers: {
'x-request-id': req.headers['x-request-id'] ?? '',
},
};
```
A status declared with [`stream`](/docs/streaming) takes an async generator function as `body`. Kizuna sends the status and headers, then writes each `yield` as it happens:
```ts
return {
status: 200,
body: async function* ({ signal }) {
yield {
event: 'delta',
data: {
text: 'Hello',
},
};
},
};
```
`signal` fires when the client goes away. `throwError` takes no streamed status.
A response with a [cache policy](/docs/caching) sends its `Cache-Control` whenever your handler returns that status. The declaration wins, so returning a `cache-control` of your own does not change it.
## Error responses
Use [`ProblemDetailsSchema`](/docs/reference/problem-details-schema) from `kizunajs/schemas` for error status codes. This is the same shape [`deny()`](/docs/reference/k-identity) produces in guards, and the one every built-in Kizuna error uses.
In the handler, `throwError` returns a typed error response. It takes the same `{ status, body }` as a normal return but throws internally, which is useful in branching logic where you want to bail out early:
```ts title="src/routes/users.ts"
.handler(async ({ params, throwError }) => {
const user = await db.users.findById(params.id);
if (!user) {
return throwError({
status: 404,
body: {
detail: 'Not found',
},
});
}
return {
status: 200,
body: user,
};
});
```
TypeScript enforces the status and body the same way it does for a return value.
## Validation errors
When a request body or query fails schema validation, Kizuna returns a `400` before the handler runs:
```json
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request validation failed",
"errors": [
{
"code": "invalid_type",
"path": ["email"],
"message": "Expected string, received number"
},
{
"code": "invalid_phone_number",
"path": ["phone"],
"message": "Must include country code"
}
]
}
```
Each issue includes a `code` that tells you _why_ the field failed, not just _that_ it failed. Codes come from Zod's built-in validation:
| Code | When it fires |
| ----------------------- | ----------------------------------------- |
| `invalid_type` | Wrong type or missing required field |
| `too_small` | Below `min()` / `minLength()` |
| `too_big` | Above `max()` / `maxLength()` |
| `invalid_string_format` | Failed `email()`, `url()`, `uuid()`, etc. |
| `unrecognized_keys` | Extra keys when using `strict()` |
| `not_multiple_of` | Failed `multipleOf()` |
| `custom` | `.refine()` or `.superRefine()` check |
User-defined checks (`.refine()`) report as `custom` by default. To emit a **typed** code instead, like `invalid_phone_number` above, declare it under `validation.issueCodes` on [`defineConfig`](/docs/reference/define-config) and raise it with [`k.issue`](/docs/reference/k-issue). It then shows up in `errors[].code` as a typed literal on both the server and the generated client, not a bare `string`.
The `message` and `path` fields come from your Zod schemas, custom messages (`z.string().min(1, 'Name is required')`) included.
This `400` is reflected in the [fetch client](/docs/clients/fetch#validation-errors) return type and the [OpenAPI spec](/docs/openapi) for any route that declares a `body` or `query` schema.
If you declare your own `400` response, the client sees a union of both your type and Kizuna's `ValidationError`. Use [`isValidationError`](/docs/clients/fetch#isvalidationerror) on the client to distinguish them.
## Query, path, and header coercion
Values in the URL and in headers always arrive as strings. Kizuna coerces them to the types you declare, so both the client and the server see the parsed value:
| Declare | Accepts on the wire | You get |
| ------------------------ | -------------------- | ------------------- |
| `z.number()` / `z.int()` | `"42"` | `42` |
| `z.boolean()` | `"true"` / `"false"` | `true` / `false` |
| `z.bigint()` | `"9007199254740993"` | `9007199254740993n` |
| `z.date()` | an ISO 8601 string | `Date` |
Arrays of these coerce too (`z.array(z.number())`). A list repeats its key, `?ids=1&ids=2`, and a single `?ids=1` arrives as a one-item list. The fetch client serializes `Date` and `bigint` values for you, so a `z.date()` query param round-trips without manual formatting. Request bodies are sent as JSON and keep their types.
Because coercion is built in, **`z.coerce` is not supported**, and `k.routes` throws if any schema uses it. Declare the plain schema (`z.number()`, `z.date()`, `z.bigint()`). To receive a different type than you send, use `z.string().transform(...)`.
### Response schemas
One Zod schema per status code:
```ts
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
```
Use `z.void()` for a status that carries no body:
```ts
responses: {
204: z.void(),
404: ProblemDetailsSchema,
},
```
The handler answers it with the status alone:
```ts
return {
status: 204,
};
```
To type response headers, give the status a `{ body, headers }` object:
```ts
responses: {
200: {
body: UserSchema,
headers: z.object({
'x-request-id': z.string().optional(),
}),
},
},
```
To send a response piece by piece, declare `stream` in place of `body`, with the schema of one message, or a record of event name to schema:
```ts
responses: {
200: {
stream: {
delta: z.object({
text: z.string(),
}),
},
},
},
```
The handler then yields messages instead of returning one body, and the fetch client reads them with `for await`. See [Streaming](/docs/streaming).
## One route per file
A route and its handler travel together, so a route that outgrows its group moves to its own file and `k.routes` still groups it:
```ts title="src/routes/users/create-user.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../../k';
import { UserSchema } from '../schemas';
export const createUser = k
.route({
method: 'POST',
path: '/users',
body: z.object({
name: z.string().min(1),
email: z.email(),
}),
responses: {
201: UserSchema,
400: ProblemDetailsSchema,
},
})
.handler(async ({ body }) => ({
status: 201,
body: await db.users.create(body),
}));
```
```ts title="src/routes/users/index.ts"
import { k } from '../../k';
import { createUser } from './create-user';
import { getUser } from './get-user';
export const users = k.routes.users({
createUser,
getUser,
});
```
### Nothing runs at import
`kizuna generate` imports your route files to read them, so whatever a module does at the top level, it does on every generate. Importing a database client is fine. Opening a connection, reading a file, or throwing on a missing environment variable is not, so keep that inside the handler.
## Verifying signed requests
Services that call your API, like Resend or Stripe webhooks, sign each request so you can prove it came from them. The signature covers the body exactly as it was sent, so a route that checks one sets `rawBody: true` and receives that text beside the validated `body`:
```ts title="src/routes/webhooks.ts"
import { Webhook } from 'svix';
resendEvents: k
.route({
method: 'POST',
path: '/webhooks/resend',
auth: false,
hidden: true,
rawBody: true,
headers: z.object({
'svix-id': z.string(),
'svix-timestamp': z.string(),
'svix-signature': z.string(),
}),
body: z.object({
type: z.string(),
data: z.object({
to: z.array(z.email()),
}),
}),
responses: {
204: z.void(),
400: ProblemDetailsSchema,
},
})
.handler(async ({ rawBody, headers, body, throwError }) => {
try {
new Webhook(process.env.RESEND_WEBHOOK_SECRET).verify(rawBody, headers);
} catch {
return throwError({
status: 400,
body: {
detail: 'The signature does not match the body',
},
});
}
if (body.type === 'email.bounced') {
await db.users.markEmailUndeliverable(body.data.to);
}
return {
status: 204,
};
}),
```
`rawBody` is the body as a string, before any parsing. Checking the signature against it, rather than against `body`, is what makes the check hold, since re-serialising the JSON can change a single byte and break it. Every adapter keeps it for you. On Express it takes one extra step only if your app also runs `express.json()` ahead of Kizuna; see [alongside your own Express routes](/docs/adapters/express#alongside-your-own-express-routes).
## Non-JSON responses
For non-JSON responses, set `contentType` to send the body as-is instead of JSON. Responses default to `application/json`, errors to `application/problem+json`, and a [stream](/docs/streaming) to `text/event-stream`. Declare a non-JSON body as `z.string()`:
```ts
responses: {
200: {
body: z.string(),
contentType: 'text/csv',
},
},
```
Every client reads that body as the text the server sent, never as JSON.
For binary responses, use [`BinarySchema`](/docs/reference/binary-and-file-schemas) for a body of raw bytes (`Uint8Array`/`Buffer`), such as a PDF download:
```ts title="src/routes/reports.ts"
import { BinarySchema } from 'kizunajs/schemas';
responses: {
200: {
body: BinarySchema,
contentType: 'application/pdf',
},
},
```
## Hidden routes
Every route lands in every client your config generates, and in the OpenAPI document. Some routes aren't for your apps at all: Stripe calls your webhook route, and your load balancer calls the health check. Mark those `hidden`:
```ts title="src/routes/health.ts"
check: k
.route({
method: 'GET',
path: '/health',
hidden: true,
responses: {
200: HealthSchema,
},
})
.handler(() => ({ ... })),
```
The server answers it as always. It's left out of every generated client and, by default, the OpenAPI document, so no app gets a `check()` method nobody would call.
### It can't be a tool
A hidden route stays out of [MCP](/docs/tools) too. `hidden` and `tool` on the same route is a type error, and a stream can't name a hidden route under `tools`, so a webhook or a health check never becomes something a model can call.
### It isn't access control
A hidden route is still served, and anyone who knows its URL can call it. Its `auth` is what decides who may.
`kizuna routes` marks hidden routes, and [`kizuna diff`](/docs/breaking-changes) reports a route becoming hidden as breaking for your clients' callers, even though the server still serves it.
## Going further
### Naming schemas with models
By default the generators inline each schema wherever it appears. Use [`Kizuna.model`](/docs/reference/kizuna-model) to give a schema a name they can reuse:
```ts title="src/routes/schemas.ts"
import { Kizuna } from 'kizunajs';
export const UserSchema = Kizuna.model({
title: 'User',
description: 'A user in the system',
schema: z.object({
id: z.string(),
name: z.string(),
email: z.email(),
}),
});
```
- **OpenAPI**: extracted into `components.schemas.User`, and every usage becomes a `$ref`
- **Swift**: emitted as a shared `public struct User`
- **TypeScript**: emitted as `API.User` in the generated client (see [Named types](/docs/clients/fetch#named-types))
### Splitting routes across files
Large APIs split into groups, nested as deep as the API needs. Declare them once with [`k.groups`](/docs/reference/k-groups) and name them on `defineConfig`:
```ts title="src/groups.ts"
import { k } from './k';
export const groups = k.groups({
users: {
title: 'Users',
description: 'User management endpoints',
},
workspaces: {
title: 'Workspaces',
groups: {
members: 'Members',
invites: 'Invites',
},
},
health: 'Health',
});
```
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { groups } from './src/groups';
import { routes } from './src/routes';
export default defineConfig({
groups,
routes,
});
```
Each file declares its routes, then files them into a group at the bottom. A nested group is reached through its parent:
```ts title="src/routes/members.ts"
import { k } from '../k';
const listMembers = k.route({ ... }).handler(...);
const removeMember = k.route({ ... }).handler(...);
export const memberRoutes = k.routes.workspaces.members({
listMembers,
removeMember,
});
```
An `index.ts` beside them lists the files, in any order, so the config has one import to make:
```ts title="src/routes/index.ts"
import { users } from './users';
import { memberRoutes } from './members';
import { inviteRoutes } from './invites';
import { health } from './health';
export const routes = [users, memberRoutes, inviteRoutes, health];
```
Each route's key is its group's path, then its name: `listMembers` is `workspaces.members.listMembers`, and clients call `client.workspaces.members.listMembers()`. An object inside the group call adds a level without adding a group:
```ts
export const projectRoutes = k.routes.projects({
listProjects,
settings: {
get: getProjectSettings,
update: updateProjectSettings,
},
});
```
That is `client.projects.settings.update()`, filed under Projects in the docs. Two routes that claim the same key make `defineConfig` throw.
See [Project Structure](/docs/project-structure) for where the rest of the pieces go.
Each top-level group becomes an OpenAPI tag, with its `title` as the tag's name and its `description` in the tag definition. OpenAPI 3.1 has no nested tags, so a route in a nested group is listed under the group at the top of its path: `listMembers` shows under Workspaces. A route can also list more groups by dotted path:
```ts
const listMyInvites = k
.route({
method: 'GET',
path: '/me/invites',
groups: ['workspaces.invites'],
// ...
})
.handler(/* ... */);
```
### Deprecating routes and fields
Set `deprecated` on a route, either `true` or a migration message:
```ts
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
deprecated: 'use `archiveUser` instead',
responses: {
200: z.object({
success: z.boolean(),
}),
},
})
.handler(/* ... */),
```
Fields declare it in their [Zod metadata](https://zod.dev/metadata), with the same `true | string` shape:
```ts
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: z.object({
id: z.string(),
name: z.string(),
legacyUsername: z.string().optional().meta({
deprecated: 'use name instead',
}),
}),
},
})
.handler(/* ... */),
```
Your editor, the OpenAPI spec, and the Swift and Kotlin clients pick both up. A route also takes a deprecation `date` and a `sunset` timestamp, both ISO 8601, and every response from it then announces them in the `Deprecation` and `Sunset` headers. See [Deprecations](/docs/deprecations).
## Reference
- [`new Kizuna()`](/docs/reference/Kizuna)
- [`k.route`](/docs/reference/k-route)
- [`Kizuna.model`](/docs/reference/kizuna-model)
- [`k.groups`](/docs/reference/k-groups)
- [`isValidationError`](/docs/reference/is-validation-error)
## Next steps
- [Config](/docs/config) to assemble your routes and serve them
- [Authentication](/docs/authentication) for the identities a route's `auth` names
---
# Standards
Source: /docs/standards
---
title: Standards
description: The specifications Kizuna follows, what each one covers, and what it deliberately leaves out.
---
Kizuna is spec-driven. It tries to follow these specifications as closely as it can.
## HTTP
| Standard | What it covers |
| --- | --- |
| [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110) HTTP Semantics | Methods, status codes, headers, content negotiation, and which methods are safe and idempotent |
| [RFC 5789](https://www.rfc-editor.org/rfc/rfc5789) PATCH Method | The `PATCH` method, which RFC 9110 does not define, and its unsafe and non-idempotent semantics |
| [RFC 9457](https://www.rfc-editor.org/rfc/rfc9457) Problem Details | The body of every error response, as `type`, `title`, `status`, `detail`, and `instance` |
| [RFC 6585](https://www.rfc-editor.org/rfc/rfc6585) Additional HTTP Status Codes | The `429 Too Many Requests` a client with retries turned on waits out |
| [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) URI Syntax | Percent-encoding of path parameters, and exact path matching, so `/users/1` and `/users/1/` are distinct resources |
| [RFC 8594](https://www.rfc-editor.org/rfc/rfc8594) Sunset Header | The `Sunset` response header and the `sunset` link relation, announcing when a route will be removed and where its retirement policy lives |
| [RFC 9745](https://www.rfc-editor.org/rfc/rfc9745) Deprecation Header | The `Deprecation` response header and the `deprecation` link relation, carrying the date a route became deprecated and a link to its documentation |
| [RFC 9111](https://www.rfc-editor.org/rfc/rfc9111) HTTP Caching | The `Cache-Control` and `Vary` response headers a response's `cache` policy sends |
| [RFC 5861](https://www.rfc-editor.org/rfc/rfc5861) Stale Content | The `stale-while-revalidate` and `stale-if-error` cache directives |
| [RFC 8246](https://www.rfc-editor.org/rfc/rfc8246) Immutable Responses | The `immutable` cache directive |
| [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110) Conditional Requests | The `ETag` a response's `etag` sends, the `If-None-Match` it is compared against, and the `304 Not Modified` a match answers with |
| [Server-sent events](https://html.spec.whatwg.org/multipage/server-sent-events.html) WHATWG HTML | The `text/event-stream` framing of a route's `stream` response: `event`, `data`, `id`, `retry`, and comment lines |
Every `GET` route answers `HEAD` too. [RFC 9110 §9.3.2](https://www.rfc-editor.org/rfc/rfc9110#section-9.3.2) defines `HEAD` as `GET` without the content, so Kizuna serves it from the path's `GET` route: same status and headers, a `Content-Length`, no body. A declared `HEAD` route takes the path instead, and `HEAD` joins `GET` in every `Allow` header. The derived route stays out of the OpenAPI document and the clients; the generator's `derivedHead` option opts it in.
## OpenAPI
| Standard | What it covers |
| --- | --- |
| [OpenAPI 3.1.0](https://spec.openapis.org/oas/v3.1.0) | The document `@kizunajs/openapi` generates from your routes |
See [OpenAPI](/docs/openapi) for the generator and the reference UI it serves.
## Authentication
An API that verifies tokens rather than issuing them is a resource server, and Kizuna serves the documents and challenges one owes its clients.
| Standard | What it covers |
| --- | --- |
| [OAuth 2.1](https://datatracker.ietf.org/doc/html/draft-ietf-oauth-v2-1) | The resource server model Kizuna implements |
| [RFC 9728](https://www.rfc-editor.org/rfc/rfc9728) Protected Resource Metadata | The discovery document served at `/.well-known/oauth-protected-resource` |
| [RFC 8414](https://www.rfc-editor.org/rfc/rfc8414) Authorization Server Metadata | An identity's `issuer` |
| [RFC 8707](https://www.rfc-editor.org/rfc/rfc8707) Resource Indicators | The canonical `resource` URI, and the audience a guard checks a token against |
| [RFC 6750](https://www.rfc-editor.org/rfc/rfc6750) Bearer Token Usage | The `WWW-Authenticate` challenge, including `insufficient_scope` |
See [authentication](/docs/authentication) for identities and guards, and [access control](/docs/access-control) for permissions and roles.
## Model Context Protocol
| Standard | What it covers |
| --- | --- |
| [Model Context Protocol](https://modelcontextprotocol.io/specification/latest) | The MCP endpoint, its tools, and their input and output schemas |
| [MCP authorization](https://modelcontextprotocol.io/specification/latest/basic/authorization) | Serving the endpoint as an OAuth 2.1 resource server |
See [MCP](/docs/mcp) for the endpoint, and [tools](/docs/tools) for declaring your own.
No standard covers streamed tool calls. MCP deliberately has none, having replaced interactive tool flows with multi round-trip requests in its `2026-07-28` revision, so the `tool_call`, `tool_result` and `tool_error` events a streamed response carries are Kizuna's own vocabulary. Their framing follows the WHATWG server-sent events specification like any other stream. A route's `needsApproval` follows MCP's multi round-trip model on a stream too: the call waits, and the person's answer arrives as the next request.
## Deliberate omissions
| Omission | Why |
| --------------------------------------------------------- | ------------------------------------------------------------------------------------- |
| `TRACE` is absent from `Method` | Disabled in production everywhere, and unsupported by the frameworks Kizuna mounts on |
| Support for [Standard Schema](https://standardschema.dev) | Routes take Zod alone, see [Zod](/docs/zod) |
---
# Streaming
Source: /docs/streaming
---
title: Streaming
description: Declare a route that answers with a stream of typed events, write the handler as an async generator, and read it back with for await in the fetch client.
---
Streaming is new. How a route declares a stream, how a handler writes one, and how a client reads one will likely change while v2 is in beta, so pin your version if you depend on it.
An assistant's reply arrives one token at a time, and a caller who has to wait for the last token before seeing the first stops reading. A long export, a progress report, and a feed of events that has no end share the shape. The route declares what each piece looks like, the handler yields the pieces, and the client reads them as they come.
## Declare the stream
A `stream` takes the place of a `body` on the response:
```ts title="src/routes/assistant.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../k';
export const replyRoute = k.route({
method: 'POST',
path: '/assistant/reply',
body: z.object({
prompt: z.string().min(1),
}),
responses: {
200: {
stream: {
delta: z.object({
text: z.string(),
}),
done: z.object({
inputTokens: z.int(),
outputTokens: z.int(),
}),
},
},
400: ProblemDetailsSchema,
},
});
```
Two `body`s meet on a route like this. The route's own `body` is the request body, the prompt the caller posts, and a streaming route takes one like any other route. The `body` a status would declare under `responses` is the response body, and `stream` takes its place there: a status is sent at once or piece by piece. The `400` is an ordinary Problem Details body, returned or thrown as always. The `200` alone streams.
`stream` is a record of event name to schema, so every message the route sends has a name and a shape. Give it one schema instead when the messages are all alike.
## Write the handler
The handler returns the status, and for `body` an async generator function. Kizuna sends the status and headers, calls the function, and writes each `yield` the moment it happens:
```ts title="src/routes/assistant.ts"
import Anthropic from '@anthropic-ai/sdk';
const anthropic = new Anthropic();
export const assistant = k.routes.assistant({
reply: replyRoute.handler(async ({ body }) => ({
status: 200,
body: async function* ({ signal }) {
const stream = anthropic.messages.stream(
{
model: 'claude-opus-5',
max_tokens: 64000,
messages: [
{
role: 'user',
content: body.prompt,
},
],
},
{
signal,
}
);
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
yield {
event: 'delta',
data: {
text: event.delta.text,
},
};
}
}
const message = await stream.finalMessage();
yield {
event: 'done',
data: {
inputTokens: message.usage.input_tokens,
outputTokens: message.usage.output_tokens,
},
};
},
})),
});
```
Each `yield` names its `event` and carries `data` matching that event's schema, and TypeScript checks the pair, so a `delta` carrying a `done` payload is a compile error. The provider's own events stay inside the handler. What you declared describes your API, and the client on the other side reads `delta` and `done` without knowing which model answered.
The wire is `text/event-stream`, one block per yield, with `data` as JSON:
```
event: delta
data: {"text":"Hel"}
event: delta
data: {"text":"lo"}
event: done
data: {"inputTokens":12,"outputTokens":2}
```
## Read it
On the streamed status the fetch client hands back `body` as an async iterable. Read it with `for await`, and each message narrows on `event` to its own `data`:
```ts title="chat.ts"
const result = await apiClient.assistant.reply({
body: {
prompt: 'Explain server-sent events in one paragraph',
},
});
if (result.status === 200) {
let reply = '';
for await (const message of result.body) {
if (message.event === 'delta') reply += message.data.text;
if (message.event === 'done') console.log(`${message.data.outputTokens} tokens`);
}
}
```
Every other status arrives as it does today, so `result.status === 400` gives a parsed Problem Details body.
In React, append each delta to state and the reply types itself out:
```tsx title="Reply.tsx"
const [reply, setReply] = useState('');
const ask = async (prompt: string) => {
setReply('');
const result = await apiClient.assistant.reply({
body: {
prompt,
},
});
if (result.status !== 200) return;
for await (const message of result.body) {
if (message.event === 'delta') setReply((current) => current + message.data.text);
}
};
```
### Cancelling
Pass a signal as you would to `fetch`. Aborting it closes the connection:
```ts title="chat.ts"
const controller = new AbortController();
const result = await apiClient.assistant.reply({
body: {
prompt,
},
fetchOptions: {
signal: controller.signal,
},
});
stopButton.onclick = () => controller.abort();
```
On the server the generator's `signal` fires, so an upstream call that took it stops too, and Kizuna returns the generator so a `finally` block runs. The handler above hands `signal` to the Anthropic SDK for this reason.
## Messages without names
Give `stream` one schema when every message has the same shape. The handler yields `{ data }`, the wire carries `data:` lines alone, and the client reads `message.data`:
```ts title="src/routes/notifications.ts"
watchEvents: k
.route({
method: 'GET',
path: '/events/watch',
responses: {
200: {
stream: EventRecord,
},
},
})
.handler(async () => ({
status: 200,
body: async function* ({ signal }) {
for await (const record of db.events.watch(signal)) {
yield {
data: record,
};
}
},
})),
```
## Ids, retry, and comments
A yield may carry the other two fields a server-sent event has. `id` names the message so a client that reconnects can say where it left off, and `retry` tells it how many milliseconds to wait before it does:
```ts
yield {
event: 'delta',
data: {
text,
},
id: `${messageId}:${index}`,
retry: 5000,
};
```
A `comment` yields a comment line. It carries no data, and it keeps an idle connection open through proxies that close quiet ones:
```ts
yield {
comment: 'keep-alive',
};
```
The client hands `id` and `retry` back on each message and drops comments.
### Resuming
A client that reconnects sends the last `id` it saw as `Last-Event-ID`. A handler of an event stream receives it as `lastEventId`, and sends what follows:
```ts title="src/routes/notifications.ts"
watchNotifications: k
.route({
method: 'GET',
path: '/notifications/stream',
responses: {
200: {
stream: NotificationSchema,
},
},
})
.handler(({ lastEventId }) => ({
status: 200,
body: async function* () {
for (const notification of await notificationsAfter(lastEventId)) {
yield {
id: notification.id,
data: notification,
};
}
},
})),
```
The clients reconnect when you turn it on, with `reconnect` in the fetch client and a `ReconnectPolicy` in the Swift and Kotlin clients. As the [event stream specification](https://html.spec.whatwg.org/multipage/server-sent-events.html) has it, they reconnect whenever the connection closes, whether the network dropped it or the server ended the stream, so a proxy closing an idle stream doesn't end it for good. They wait the last `retry` the server sent, longer after reconnections in a row that fail, then send `Last-Event-ID` and carry on yielding to the same loop. `onRequest`, `requestMiddleware` and `requestInterceptor` run again before each reconnection, so a refreshed token goes with it.
To end a stream for good, answer the reconnection with `204 No Content`. Any other status than the stream's own, or a body that isn't `text/event-stream`, fails the stream. Only a `GET`, `HEAD`, `OPTIONS`, `PUT` or `DELETE` stream reconnects, since a `POST` like the assistant route above would run its handler again.
## Raw chunks
A `z.string()` schema with a `text/*` content type, or `BinarySchema` with any other, writes each yield as it is, with no framing around it:
```ts title="src/routes/reports.ts"
exportEvents: k
.route({
method: 'GET',
path: '/events/export.csv',
responses: {
200: {
stream: z.string(),
contentType: 'text/csv',
},
},
})
.handler(async () => ({
status: 200,
body: async function* () {
yield 'id,kind,occurredAt\n';
for await (const record of db.events.all()) {
yield `${record.id},${record.kind},${record.occurredAt}\n`;
}
},
})),
```
For bytes, hand over a `ReadableStream` in place of the generator. That is how a route passes a file from storage through without holding it in memory:
```ts title="src/routes/reports.ts"
downloadArchive: k
.route({
method: 'GET',
path: '/reports/:id/archive',
responses: {
200: {
stream: BinarySchema,
contentType: 'application/zip',
},
},
})
.handler(async ({ params }) => {
const upstream = await fetch(storage.archiveUrl(params.id));
return {
status: 200,
body: upstream.body,
};
}),
```
The client iterates strings for a text stream and `Uint8Array` chunks for a binary one.
## Building the generator elsewhere
An inline generator function sits inside the route's return type, so its event names infer as literals. One declared on its own has nothing to infer from, and TypeScript widens `event` to `string`. Annotate it with `StreamBody`, naming the route and the status:
```ts title="src/routes/canned-reply.ts"
import type { StreamBody } from 'kizunajs';
import { replyRoute } from './assistant';
const cannedReply: StreamBody = async function* () {
yield {
event: 'delta',
data: {
text: 'Hello',
},
};
yield {
event: 'done',
data: {
inputTokens: 0,
outputTokens: 1,
},
};
};
export const assistant = k.routes.assistant({
reply: replyRoute.handler(async () => ({
status: 200,
body: cannedReply,
})),
});
```
## Errors
Before the first message, everything works as on any route: validation answers `400`, a guard `401` or `403`, and `throwError` any status the route declares, all as Problem Details. `throwError` takes no streamed status. A stream is a body to produce, and bailing out is what `throwError` is for.
Once the handler has returned, the status and headers are on the wire. A throw inside the generator after that cannot become a `500`, so Kizuna ends the connection. The client's loop rejects instead of finishing quietly, and the adapter's error callback is told. Declare a terminal event like `done` when the reader must know the reply is whole, and an `error` event of your own when it must know why it stopped short.
With `responseValidation` on, Kizuna validates each message against its schema before writing it, and a message that fails ends the stream the same way.
## Headers
A streamed response goes out with `Content-Type: text/event-stream` and `Cache-Control: no-store`, since a cache stores a complete representation and a stream has none. Return your own `headers` to add to what Kizuna sends, the way you would on any response. `X-Accel-Buffering: no` tells nginx to pass each message through rather than collect them.
Every `GET` route answers `HEAD`, a stream route included: the status and headers, no body, and no `Content-Length`, since the length is unknown. The handler runs, and the generator is never called.
## Tools
A streamed response can name the tools the model may call, adding `tool_call`, `tool_result` and `tool_error` to the events it declares:
```ts
200: {
stream: {
delta: z.object({
text: z.string(),
}),
},
tools,
},
```
Each is discriminated on the tool's dotted key. The handler receives `tools`, whose `run` calls one of those routes as the person streaming and yields its events. See [tools](/docs/tools#running-the-calls).
## Reference
- [`k.routes`](/docs/reference/k-routes)
- [a route's `handler`](/docs/reference/k-route)
- [Fetch client](/docs/clients/fetch)
---
# Tools
Source: /docs/tools
---
title: Tools
description: Publish a route as a tool a model can call, and read each call typed in your client.
---
Tools are new. How a route publishes, how a call runs, and how a client reads one will likely change while v2 is in beta, so pin your version if you depend on it.
A tool is usually written three times: a JSON Schema for the model, a typed event for the client, and a function that runs it. A route already carries all three, so say `tool: true` and it publishes.
## Say which routes publish
```ts title="src/routes/weather.ts"
import { z } from 'zod';
import { k } from '../k';
export const weatherRoutes = k.routes.weather({
getForecast: k
.route({
method: 'GET',
path: '/forecast/:city',
auth: false,
pathParams: z.object({
city: z.string().min(1),
}),
query: z.object({
unit: z.enum(['celsius', 'fahrenheit']).default('celsius'),
}),
responses: {
200: z.object({
temperature: z.number(),
unit: z.enum(['celsius', 'fahrenheit']),
summary: z.string(),
}),
},
summary: 'Look up tomorrow forecast for one city',
tool: true,
})
.handler(({ params, query }) => ({
status: 200,
body: forecastFor(params.city, query.unit),
})),
});
```
`tool: true` takes the route's `summary` as what a model reads before calling, so a route that publishes has to carry one. Its input is the `{ params, query, body }` the route already declares, and its output is the body of its `2xx` response.
## Say how it behaves
`tool` also takes an object. `description`, `title` and the four hints are MCP's own, field for field:
```ts title="src/routes/workspace.ts"
deleteWorkspace: k
.route({
method: 'DELETE',
path: '/workspace',
auth: { identity: 'member', requires: { workspace: ['delete'] } },
summary: 'Delete the workspace, owner only',
tool: {
needsApproval: true,
},
responses: {
200: z.object({ ok: z.boolean() }),
},
})
.handler(/* ... */),
```
| Field | Meaning |
| ----------------- | --------------------------------------------------------------------------------- |
| `description` | What the model reads when it decides whether to call. Defaults to `summary` |
| `title` | A human-readable name for display. MCP's `ToolAnnotations.title` |
| `readOnlyHint` | The route only reads. Defaults to true for `GET` and `HEAD` |
| `idempotentHint` | Calling twice does what calling once did. Defaults to true for `PUT` and `DELETE` |
| `destructiveHint` | The route may remove or overwrite. Defaults to true for `DELETE` |
| `openWorldHint` | The route reaches something outside this API |
| `needsApproval` | The person approves each call before it runs. Kizuna's own |
The hints come from the method's RFC 9110 semantics, so a `GET` is already marked read only and a `DELETE` already destructive. Set one to say what the method cannot.
`needsApproval` is the one field MCP has no way to declare. A client reads the hints and decides for itself whether to ask; `needsApproval` asks, and declining leaves the handler uncalled. It sits on the declaration rather than in the handler because the handler also answers HTTP, where there is nobody to ask.
`needsApproval` asks about what the model chose to do in someone's name, not about what they may do. A rule that depends on the input, such as a refund limit, belongs in the handler. HTTP callers meet it too, and a model reads the refusal as the tool's result, with the Problem Details that explain it:
```ts title="src/routes/orders.ts"
.handler(({ body, throwError }) => {
if (body.amount > 100) {
throwError({
status: 403,
body: {
detail: 'Refunds over 100 need a manager.',
},
});
}
// ...
}),
```
Over MCP the person is asked through an elicitation, named after the route's `summary`. On a stream the call waits for them, as [waiting for approval](#wait-for-approval) shows.
## Publish them
[`mcpPlugin`](/docs/reference/mcp-plugin) serves the endpoint. Which routes it offers is each route's own business, so it takes nothing but its name:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
mcpPlugin({
name: 'My API',
}),
],
});
```
A route that publishes is still an ordinary route. An HTTP caller reaches `GET /forecast/Oslo`, a model calls `weather_get_forecast`, and both run the same handler through the same validation, guards and Problem Details.
## Put them on a stream
Naming `tools` on a streamed response adds three events, typed against the routes you name:
```ts title="src/routes/assistant.ts"
responses: {
200: {
stream: {
delta: z.object({
text: z.string(),
}),
},
tools: weatherRoutes,
},
},
```
| Event | Payload |
| ------------- | ----------------------- |
| `tool_call` | `{ id, name, input }` |
| `tool_result` | `{ id, name, output }` |
| `tool_error` | `{ id, name, message }` |
`id` ties a result back to its call, and `input` carries the `{ params, query, body }` the route takes. Every route named under `tools` declares `tool`, and `k.routes` throws on one that does not, or on one that streams or takes a form body.
## Running the calls
A handler whose stream names `tools` receives `tools`, bound to the request that is streaming. It holds the routes that response names and nothing else, so an assistant that names `weatherRoutes` cannot reach a route outside them.
### Describe them to the model
`tools.definitions` has one entry per route: the `name` a model calls it by, the `description` it reads, and `inputSchema` as JSON Schema.
```ts title="src/routes/assistant.ts"
const stream = anthropic.messages.stream({
model: 'claude-opus-5',
max_tokens: 64000,
messages,
tools: tools.definitions.map((tool) => ({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
})),
});
```
### Run what the model asks for
`tools.run` takes a call as the model sent it and runs the route as the person who made the request. The route's own validation, guards and handler run, with the credentials the stream request carried, so a handler never passes a token along. Delegate to it with `yield*`: it sends `tool_call`, then `tool_result` or `tool_error`, and returns what the model reads.
```ts title="src/routes/assistant.ts"
import Anthropic from '@anthropic-ai/sdk';
import { weatherRoutes } from './weather';
const anthropic = new Anthropic();
reply: k
.route({
method: 'POST',
path: '/assistant/reply',
auth: 'user',
body: z.object({
prompt: z.string(),
}),
responses: {
200: {
stream: {
delta: z.object({
text: z.string(),
}),
},
tools: weatherRoutes,
},
},
})
.handler(({ body, tools }) => ({
status: 200,
body: async function* () {
const messages: Anthropic.MessageParam[] = [
{
role: 'user',
content: body.prompt,
},
];
for (;;) {
const stream = anthropic.messages.stream({
model: 'claude-opus-5',
max_tokens: 64000,
messages,
tools: tools.definitions.map((tool) => ({
name: tool.name,
description: tool.description,
input_schema: tool.inputSchema,
})),
});
for await (const event of stream) {
if (event.type === 'content_block_delta' && event.delta.type === 'text_delta') {
yield {
event: 'delta',
data: {
text: event.delta.text,
},
};
}
}
const message = await stream.finalMessage();
const calls = message.content.filter((block) => block.type === 'tool_use');
if (calls.length === 0) return;
const results: Anthropic.ToolResultBlockParam[] = [];
for (const call of calls) {
const result = yield* tools.run(call);
if (result.state === 'needs-approval') return;
results.push({
type: 'tool_result',
tool_use_id: call.id,
content: result.content,
is_error: result.isError,
});
}
messages.push(
{
role: 'assistant',
content: message.content,
},
{
role: 'user',
content: results,
}
);
}
},
})),
```
`result.content` is the `{ status, body }` the route answered with, as JSON. When the route refuses, because the input fails its schema, a guard says no, or the handler answers `4xx`, `result.isError` is `true` and `content` carries the same Problem Details an HTTP caller would get, so the model reads why and can try again.
### Wait for approval
Some calls should wait for the person. A notes assistant can read notes freely, but saving one should need a yes. `needsApproval` on the route says so:
```ts title="src/routes/notes.ts"
add: k
.route({
method: 'POST',
path: '/notes',
auth: 'user',
body: z.object({
text: z.string(),
}),
responses: {
201: NoteSchema,
},
summary: 'Save a note for the signed-in user',
tool: {
needsApproval: true,
},
})
.handler(/* ... */),
```
This is what happens when the person types "remember the demo is on Friday":
1. **The model asks to call `notes_add`.** Kizuna does not run it. The stream sends the call marked `needsApproval`, and `tools.run` returns `needs-approval`, so the loop above ends the stream:
```
event: tool_call
data: {"id":"toolu_1","name":"notes.add","needsApproval":true,"input":{"body":{"text":"the demo is on Friday"}}}
```
2. **The app asks the person.** `readToolCalls` gives the call as a row with `state: 'needs-approval'` and the note in `input`, so the app can put it in its own words.
3. **They tap Yes.** The app sends a second request carrying the call it showed and the answer.
4. **The server runs that call.** The note is saved as the signed-in person, `tool_result` streams back, and the model carries on.
Had they tapped No, nothing is saved, and the model reads `Declined, so nothing ran.`
The call comes back from the app in step 3 rather than from the model a second time. The server keeps nothing between the two requests, and a model asked again would make a new call, with a new id and maybe different wording. Sending back what the person saw means exactly that runs.
#### On the client
Ask on a `needs-approval` row, and send the row back with the answer:
```tsx title="components/ToolCallView.tsx"
if (call.state === 'needs-approval' && call.name === 'notes.add') {
return (
Save “{call.input.body.text}” to your notes?
);
}
```
`send` starts the next request to the same route.
#### On the server
Take the answer in the body with `ToolAnswerSchema`:
```ts
import { ToolAnswerSchema } from 'kizunajs/schemas';
body: z.object({
prompt: z.string(),
answer: ToolAnswerSchema.optional(),
}),
```
When one arrives, run its call before asking the model anything, and put the result in the conversation. `result.call` is the call as the model knows it:
```ts
body: async function* () {
const messages: Anthropic.MessageParam[] = [
{
role: 'user',
content: body.prompt,
},
];
if (body.answer) {
const result = yield* tools.run(body.answer.call, body.answer);
if (result.state === 'needs-approval') return;
messages.push(
{
role: 'assistant',
content: [
{
type: 'tool_use',
...result.call,
},
],
},
{
role: 'user',
content: [
{
type: 'tool_result',
tool_use_id: result.call.id,
content: result.content,
is_error: result.isError,
},
],
}
);
}
// the loop from above
},
```
The call runs as the person who sent the answer, through the route's guards, so an edited answer can do nothing their own request could not.
## Reading the calls
A call arrives as one event and its answer as another. `readToolCalls` folds them back into one row per call, carrying the tool's `name`, a `state` of `running`, `needs-approval`, `done` or `failed`, and the payloads narrowed to that tool.
TypeScript imports it from `kizunajs`; the Swift and Kotlin generators emit it beside the route's `Event` type.
`streamOptions` from [`@kizunajs/tanstack-query`](/docs/clients/tanstack-query) already holds the messages received so far, so there is no state to keep at all.
```tsx title="components/Chat.tsx"
import { useQuery } from '@tanstack/react-query';
import { readToolCalls } from 'kizunajs';
import { api } from '../api';
export function Chat({ prompt }: { prompt: string }) {
const { data } = useQuery(
api.assistant.reply.streamOptions({
input: {
body: {
prompt,
},
},
})
);
const messages = data ?? [];
return (
{readToolCalls(messages).map((call) => (
))}
);
}
```
```tsx title="components/ToolCallView.tsx"
import type { ToolCallRecord } from 'kizunajs';
type Call = ToolCallRecord;
export function ToolCallView({ call }: { call: Call }) {
switch (call.name) {
case 'charts.plotSignups':
return call.state === 'done' ? : ;
default:
return ;
}
}
```
```swift title="ChatModel.swift"
@Observable
@MainActor
final class ChatModel {
var messages: [AssistantReply.Event] = []
func send(_ prompt: String) async throws {
messages = []
let result = try await client.assistantReply(body: .init(prompt: prompt))
for try await event in result.body {
messages.append(event)
}
}
}
```
```swift title="ChatView.swift"
import APIClient
struct ChatView: View {
@State private var model = ChatModel()
var body: some View {
VStack(alignment: .leading, spacing: 12) {
ForEach(APIClient.AssistantReply.readToolCalls(model.messages)) { call in
ToolCallView(call: call)
}
Text(model.messages.text)
}
}
}
```
```swift title="ToolCallView.swift"
struct ToolCallView: View {
let call: ToolCallRecord
var body: some View {
switch call.name {
case "charts.plotSignups":
SignupChart(points: call.points)
default:
ToolPill(name: call.name, state: call.state)
}
}
}
```
```kotlin title="ChatViewModel.kt"
class ChatViewModel(private val client: APIClient) : ViewModel() {
private val _messages = MutableStateFlow(emptyList())
val messages: StateFlow> = _messages.asStateFlow()
fun send(prompt: String) = viewModelScope.launch {
_messages.value = emptyList()
client.assistantReply(AssistantReplyBody(prompt)).body.collect { event ->
_messages.update { it + event }
}
}
}
```
```kotlin title="ChatScreen.kt"
import com.kizuna.demo.APIClient
@Composable
fun ChatScreen(model: ChatViewModel = viewModel()) {
val messages by model.messages.collectAsStateWithLifecycle()
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
APIClient.AssistantReply.readToolCalls(messages).forEach { call -> ToolCallView(call) }
Text(messages.text())
}
}
```
```kotlin title="ToolCallView.kt"
@Composable
fun ToolCallView(call: ToolCallRecord) {
when (call.name) {
"charts.plotSignups" -> SignupChart(call.points)
else -> ToolPill(call.name, call.state)
}
}
```
### Reaching one tool payload
Narrow on the tool name where you want its own data. The generated types carry the payload, so there is no cast.
```ts
if (message.event === 'tool_result') {
switch (message.data.name) {
case 'charts.plotSignups':
// { points: Array<{ date: string; signups: number }> }
points = message.data.output.points;
break;
case 'weather.getForecast':
// { temperature: number; unit: 'celsius' | 'fahrenheit'; summary: string }
temperature = message.data.output.temperature;
break;
case 'countWords':
// { words: number }
words = message.data.output.words;
break;
}
}
```
```swift
case .tool_result(let result):
switch result {
case .charts_plotSignups(let plotted):
points = plotted.output.points
case .weather_getForecast(let forecast):
temperature = forecast.output.temperature
case .countWords(let counted):
words = counted.output.words
}
```
```kotlin
is Event.ToolResult -> when (val result = event.data) {
is ToolResult.Charts_plotSignups -> points = result.value.output.points
is ToolResult.Weather_getForecast -> temperature = result.value.output.temperature
is ToolResult.CountWords -> words = result.value.output.words
}
```
Rename a field on the route and every one of these stops compiling.
## Publishing over MCP
A route that declares `tool` already has a name, a description, an input schema, an output schema and a handler, which is what an MCP tool is. [`mcpPlugin`](/docs/reference/mcp-plugin) serves them:
```ts title="kizuna.config.ts"
import { mcpPlugin } from '@kizunajs/mcp';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
mcpPlugin({
name: 'My API',
}),
],
});
```
A route names itself `users_get_user` over MCP, from its dotted key. If it needs an identity, the same guard runs on a tool call as on an HTTP request, and a refusal reaches the model as an execution error.
See [MCP](/docs/mcp) for the rest of the endpoint, including OAuth.
## How it works underneath
Nothing here is a new transport. Every piece reduces to something Kizuna already had.
**The events are folded into the stream at `k.routes` time.** Before a route is validated, `expandStreamTools` turns each route you named into three Zod schemas and merges them into the response's `stream` record, then moves the `tools` field under a symbol, where the handler's `tools` reads it. From that point on the response is an ordinary named-event stream, which is why the four adapters, the OpenAPI generator, the fetch client, and the Swift and Kotlin generators needed no changes to carry tools.
**Each event is a discriminated union on the route's dotted key.** `tool_call` is `z.discriminatedUnion('name', [...])` with one arm per route, each carrying that route's own input. The type-level side walks the same tree to the same dotted keys, so `message.data.input` narrows in TypeScript, the Swift generator emits an `enum` with one case per tool, and the Kotlin generator emits a `sealed interface`.
**The dotted key is the discriminator, not the published name.** `weather.getForecast` on the wire, `weather_get_forecast` over MCP. Deriving the snake-case name at the type level would need a string algorithm that has to agree exactly with the runtime one, and disagreeing silently would be worse than reading the name off a definition.
**Execution is the route's own pipeline.** A tool call runs the route handler through the same validation, guards and Problem Details an HTTP request does, so there is one place a route runs whoever asked. On a stream, `tools.run` enters that pipeline after routing, with the stream request's headers and the adapter's handler context, and the tool's input in place of the URL and body.
## What Kizuna.js leaves out
- **Models.** Kizuna never calls one, holds a conversation, or runs an agent loop. It validates input, runs a handler, validates output. The loop lives in your route handler, the way a job's transport lives outside kizuna.
- **Provider wire shapes.** There is no `toAnthropicTools` or `toOpenAITools`, because those track a vendor changelog. `tools.definitions` hands you a name, a description and JSON Schema, and the `.map` to a provider is a few lines you can read.
- **Progressive tool input.** A model streams a tool's arguments as partial JSON, which has no schema until it is whole. A half-parsed `{ city: "Os" }` would type-check as a finished value while being wrong, so Kizuna emits `tool_call` once the arguments are complete.
## A note on standards
The declaration follows the Model Context Protocol `Tool` object, and its schemas follow JSON Schema 2020-12. The three event names are Kizuna's own, since no standard covers streamed tool calls. See [standards](/docs/standards).
---
# Zod
Source: /docs/zod
---
title: Zod
description: Routes are written in Zod, and the schema carries more than validation.
---
A Kizuna route is written in [Zod](https://zod.dev). Validation is the smaller job: the same schemas generate the OpenAPI document, the Swift and Kotlin clients, and the MCP tools, so what you can say in Zod is what your API can say. Every package that works with schemas declares `zod@^4.0.0` as a peer dependency.
## Standard Schema
Kizuna does not support [Standard Schema](https://standardschema.dev). We looked into it, and the clients are why we ultimately chose not to.
```ts
listEvents: k
.route({
method: 'GET',
path: '/events',
query: z.object({
from: z.date(),
}),
responses: {
200: z.array(EventSchema),
},
})
.handler(/* ... */),
```
One `z.date()`, and every surface gets the real type:
- **The handler** receives `from` as a `Date`, coerced from the query string.
- **The Swift client** compiles it to `Date`, the Kotlin client to `Instant`.
- **The fetch client** serializes it back on the way out.
A validator-neutral description cannot say any of that. JSON Schema has no `Date`, `bigint`, or transform to describe, a file upload flattens to a string, and a discriminated union loses its discriminator.
Reading one library also pays inside Kizuna: the OpenAPI, Swift, Kotlin, and MCP generators share one toolkit for walking schemas, so a fix or a feature in that reading lands in all of them at once. Routes take Zod, and Kizuna reads all of it.
We wanted every client to behave the same, whatever the language, and one deeply read library is what keeps that true.
## Metadata
`.meta()` is where a schema says things validation cannot. Kizuna reads Zod's own `title` and `description`, and `kizunajs` adds its own:
| Property | Type | Where it lands |
| ------------ | ------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `deprecated` | `boolean \| string` | `deprecated: true` in the OpenAPI document, `@available(*, deprecated)` in Swift, `@Deprecated` in Kotlin. A string carries the message into outputs with a place for it. |
| `example` | The schema's type, or an array of it | JSON Schema `examples` in the OpenAPI document |
| `brand` | `string` | A named type in every client and `x-kizuna-brand` in the OpenAPI document. Set it with [`Kizuna.brand`](#branded-ids). |
```ts
const UserSchema = z.object({
id: z.string().meta({
example: 'usr_k7f3q9',
}),
});
```
Routes deprecate too, with dates and sunset headers. See [Deprecations](/docs/deprecations) for every surface.
## Named schemas
[`Kizuna.model`](/docs/reference/kizuna-model) registers a schema under a stable name, so the OpenAPI document emits `#/components/schemas/User` and the Swift and Kotlin clients emit a `User` type, instead of repeating the shape inline everywhere it appears. Only names registered through `Kizuna.model` reach the generators.
## Branded IDs
A user ID and a workspace ID are both strings, so passing one where the other belongs compiles. [`Kizuna.brand`](/docs/reference/kizuna-brand) gives the ID its own type in the handler and in every client, so the swap stops compiling. The wire stays a plain string.
```ts title="user-id.ts"
export const UserId = Kizuna.brand('UserId', z.string());
```
Use it everywhere the ID appears. In a model:
```ts
export const UserSchema = Kizuna.model({
title: 'User',
schema: z.object({
id: UserId,
name: z.string(),
}),
});
```
And in every route that takes one:
```ts
getUser: k.route({
method: 'GET',
path: '/users/:id',
pathParams: z.object({
id: UserId,
}),
responses: {
200: UserSchema,
},
}),
```
An ID from a response is already branded, so it passes straight into the next call. You only wrap one yourself when it comes from outside the API, like a URL or a form:
```ts
import { toUserId } from './api-client.generated';
const userId = new URLSearchParams(location.search).get('user') ?? '';
const id = toUserId(userId);
```
```swift
let userID = url.lastPathComponent
let id = API.UserId(userID)
```
```kotlin
val userId = uri.lastPathSegment ?: return
val id = API.UserId(userId)
```
In the handler, `params.id` is a `UserId` and still a string, so it goes into a database call as it is, and a row's plain ID goes into a response body as it is.
Brand the IDs that sit beside other IDs of the same shape, and leave other values plain. A swapped ID is a common mistake for people and coding agents alike, and a brand turns it into a compile error that names both types.
## Optional and null fields
A field can be left out, can be `null`, or both, and Zod says which. On the wire these differ: a request without the key of a `.nullable()` field gets a `400`, and so does a `null` sent for an `.optional()` one. Every client follows the schema, so whatever you declare, the generated types only build requests the server accepts.
| Declare | Key may be left out | Value may be `null` | TypeScript | Swift | Kotlin |
| ------------- | ------------------- | ------------------- | --------------------------- | --------------------- | --------------------- |
| `.optional()` | yes | no | `timezone?: string` | `String? = nil` | `String? = null` |
| `.nullable()` | no | yes | `timezone: string \| null` | `String?`, no default | `String?`, no default |
| `.nullish()` | yes | yes | `timezone?: string \| null` | `String? = nil` | `String? = null` |
### Which to declare
**A response field that may be empty is `.nullable()`.** The key is always sent, so a reader checks for `null` and nothing else, and a handler returns a database row as it is:
```ts
avatarUrl: z.string().nullable(),
```
**A request field the caller may skip is `.optional()`.** Leaving it out means "no filter" or "use the default", like `page` on a list or `locale` on a new user:
```ts
locale: z.string().optional(),
```
**A request field the caller must state, even when it is empty, is `.nullable()`.** On a PUT that replaces a user's preferences, the caller passes `timezone: nil` on purpose. A screen that forgets the field fails to compile, where a default would have sent `null` and cleared the user's timezone:
```ts
timezone: z.string().nullable(),
```
**A field where leaving it out and sending `null` mean the same thing is `.nullish()`.** It accepts both, so a caller does whichever is easier:
```ts
signature: z.string().nullish(),
```
Swift and Kotlin have one `nil`, so the default says which one you get. An `.optional()` or `.nullish()` field defaults to `nil` and is left out of the request. A `.nullable()` field has no default, so the caller passes `nil` and the client sends `null`.
### Query, path, header and form fields
A URL, a header and a form field have no `null`, so every client leaves a `nil` out, and a `.nullable()` field there fails as missing. Declare `.optional()` instead. The [ESLint plugin](/docs/eslint#a-nullable-query-path-header-or-form-field) flags it. A `.nullish()` field there means the same as `.optional()`, and the clients type it as one.
## Coercion
Path parameters, query parameters, and headers arrive as strings, and Kizuna coerces them to the declared schema, so `z.number()` in a query means the handler receives a number. Declare plain schemas; `k.routes` throws on `z.coerce`, since coercion is already built in. See [coercion](/docs/routes#query-path-and-header-coercion).
## Custom issue codes
A `.refine()` failure reports its code as `custom`. Declare `validation.issueCodes` in [`defineConfig`](/docs/reference/define-config) and raise them with [`k.issue`](/docs/reference/k-issue) to put a typed, machine-readable code in `errors[].code` instead.
## Binary bodies and uploads
JSON is the default body encoding. For bytes, [`BinarySchema` and `FileSchema`](/docs/reference/binary-and-file-schemas) describe binary response bodies and `multipart/form-data` upload fields, and the generators map them to native types like Swift's `Data`.
---
# Express
Source: /docs/adapters/express
---
title: Express
description: Mount a Kizuna API on an Express 5 application.
---
`@kizunajs/express` serves a Kizuna API from an Express 5 application. It handles routing, request validation, body parsing, and error formatting, all driven by what you declared.
**Requires Express ≥ 5.**
## The adapter
`expressAdapter()` is what you name in `kizuna.config.ts`. Naming it is what gives every handler on this API Express's own `req` and `res`, typed.
## Declare a route
```ts title="src/routes/users.ts"
import { k } from '../k';
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: ListUsersQuerySchema,
responses: {
200: UserListSchema,
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
})),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params }) => {
const user = await db.users.findById(params.id);
if (!user) {
return {
status: 404,
body: {
detail: 'Not found',
},
};
}
return {
status: 200,
body: user,
};
}),
});
```
## Name Express in your config
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { users } from './src/routes/users';
export default defineConfig({
adapter: expressAdapter(),
routes: [users],
});
```
## Mount it
```ts title="src/index.ts"
import express from 'express';
import kizuna from '../kizuna.config';
const app = express();
kizuna.api.mount(app);
app.listen(3000);
```
## Handler context
Each handler receives `{ params, query, body, headers, req, res }`. The `req` and `res` are the native Express objects, useful when you need to read cookies, set custom headers, or stream a response.
```ts title="src/routes/users.ts"
.handler(async ({ params, req, res }) => {
console.log(req.ip);
res.setHeader('x-custom', 'value');
return {
status: 200,
body: await db.users.findById(params.id),
};
});
```
## Guards
A guard sits on the identity it authenticates, and receives the credential extracted and typed, alongside the native `req`/`res`. See the [Authentication guide](/docs/authentication).
```ts title="src/identities.ts"
import { k } from './k';
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny, req }) => {
const session = bearer ? await verifySession(bearer.token) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
## Middleware
For request-scoped values handlers need, use [request context](/docs/request-context). Rate limiting, multipart parsing and the rest go in Express's own `app.use`. Authentication belongs in [guards](#guards).
## Options
```ts title="src/index.ts"
kizuna.api.mount(app, {
responseValidation: false,
json: {
limit: '5mb',
},
});
```
| Option | Default | Description |
| -------------------- | ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `responseValidation` | `false` | Validate handler return values against response schemas, surfacing as 500 on mismatch. Enable in development. |
| `json` | Express's defaults | The options for `express.json()`, like `limit` and `strict`, used for Kizuna's own routes. Leave it out if the app runs its own `express.json()`. |
| `formatError` | none | Reshape error (`>= 400`) response bytes for migrating clients. Most don't need it (use Problem Details extension members). See [Migrating an existing API](/docs/migration/existing-api). |
## Type-safe request properties
Middleware that sets custom properties on `req`, such as a request id, needs declaration merging to extend the Express `Request` interface. Authentication data does not: guards hand handlers typed context directly.
```ts title="express.d.ts"
declare global {
namespace Express {
interface Request {
requestId: string;
}
}
}
```
Both middleware and handlers are then typed:
```ts title="src/routes/users.ts"
.handler(async ({ params, req }) => {
console.log(req.requestId);
// ...
});
```
## Method mismatches
If a path is matched but the method is not declared, the adapter returns 405 with an `Allow` header listing the supported methods. This follows [RFC 9110 §15.5.6](https://www.rfc-editor.org/rfc/rfc9110#section-15.5.6).
## Alongside your own Express routes
An app with Express routes of its own usually runs `express.json()` for them. Kizuna works with that: its routes use the body `express.json()` already parsed. Set it up one of two ways.
### Mount Kizuna first
Kizuna's routes answer before `express.json()` runs, so it only parses for yours:
```ts title="src/index.ts"
const app = express();
kizuna.api.mount(app);
app.use(express.json());
app.post('/legacy/import', importHandler);
```
### Or keep the raw body
With `express.json()` registered first, pass `keepRawBody` as its `verify` option, so routes with [`rawBody: true`](/docs/routes#verifying-signed-requests) still get the body as it was sent:
```ts title="src/index.ts"
import express from 'express';
import { keepRawBody } from '@kizunajs/express';
import kizuna from '../kizuna.config';
const app = express();
app.use(
express.json({
verify: keepRawBody,
})
);
app.post('/legacy/import', importHandler);
kizuna.api.mount(app);
```
Without either, a `rawBody` route answers `500`, and the log names the route and both fixes.
## Multipart / file uploads
For routes with `contentType: 'multipart/form-data'`, add a multipart middleware such as `multer` or `busboy` before the Kizuna handler. The adapter reads `req.body` as-is.
```ts title="src/index.ts"
import multer from 'multer';
const upload = multer({
storage: multer.memoryStorage(),
});
app.post('/avatar', upload.single('file'), (req, res, next) => {
next();
});
kizuna.api.mount(app);
```
## Streams
A [stream](/docs/streaming) response is piped to `res` after `flushHeaders()`, so the client sees the headers before the first message. The generator's `signal` fires when `res` closes before the stream has finished.
## Reference
- [`defineConfig`](/docs/reference/define-config)
- [a route's `handler`](/docs/reference/k-route)
- [an identity's `guard`](/docs/reference/k-identity)
---
# Fastify
Source: /docs/adapters/fastify
---
title: Fastify
description: Mount a Kizuna API on a Fastify application.
---
`@kizunajs/fastify` serves a Kizuna API from a [Fastify](https://fastify.dev) application.
**Requires Fastify >= 5.**
## The adapter
`fastifyAdapter()` is what you name in `kizuna.config.ts`. Naming it is what gives every handler on this API Fastify's own `request` and `reply`, typed.
## Declare a route
```ts title="src/routes/users.ts"
import { k } from '../k';
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: ListUsersQuerySchema,
responses: {
200: UserListSchema,
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
})),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params }) => {
const user = await db.users.findById(params.id);
if (!user) {
return {
status: 404,
body: {
detail: 'Not found',
},
};
}
return {
status: 200,
body: user,
};
}),
});
```
## Name Fastify in your config
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { fastifyAdapter } from '@kizunajs/fastify';
import { users } from './src/routes/users';
export default defineConfig({
adapter: fastifyAdapter(),
routes: [users],
});
```
## Mount it
Fastify registers plugins asynchronously, so `mount` returns a promise:
```ts title="src/index.ts"
import Fastify from 'fastify';
import kizuna from '../kizuna.config';
const app = Fastify();
await kizuna.api.mount(app);
app.listen({
port: 3000,
});
```
## Handler context
Each handler receives `{ params, query, body, headers, request, reply }`. The `request` is Fastify's `FastifyRequest` and `reply` is `FastifyReply`, useful when you need raw headers, cookies, or anything else Fastify exposes.
```ts title="src/routes/users.ts"
.handler(async ({ params, request }) => {
request.log.info({ id: params.id }, 'loading user');
return {
status: 200,
body: await db.users.findById(params.id),
};
});
```
## Guards
A guard sits on the identity it authenticates, and receives the credential extracted and typed, alongside the native `request`/`reply`. See the [Authentication guide](/docs/authentication).
```ts title="src/identities.ts"
import { k } from './k';
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny }) => {
const session = bearer ? await verifySession(bearer.token) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
## Middleware
For request-scoped values handlers need, use [request context](/docs/request-context). For other middleware, such as logging and rate limiting, use Fastify's own [hooks](https://fastify.dev/docs/latest/Reference/Hooks/) (`app.addHook('preHandler', ...)`). Authentication belongs in [guards](#guards).
## Options
```ts title="src/index.ts"
await kizuna.api.mount(app, {
responseValidation: false,
});
```
| Option | Default | Description |
| -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `responseValidation` | `false` | Validate handler return values against response schemas. Enable in development. |
| `formatError` | none | Reshape error (`>= 400`) response bytes for migrating clients. Most don't need it (use Problem Details extension members). See [Migrating an existing API](/docs/migration/existing-api). |
The same options go on `fastifyKizuna` when you register the plugin yourself:
```ts title="src/index.ts"
import { fastifyKizuna } from '@kizunajs/fastify';
import kizuna from '../kizuna.config';
await app.register(fastifyKizuna, {
api: kizuna.api,
responseValidation: false,
});
```
## Type-safe request properties
Middleware that sets custom properties on `request`, such as a request id, needs Fastify's [declaration merging](https://fastify.dev/docs/latest/Reference/TypeScript/#creating-a-typescript-fastify-plugin) to extend the `FastifyRequest` interface. Authentication data does not: guards hand handlers typed context directly.
```ts title="fastify.d.ts"
declare module 'fastify' {
interface FastifyRequest {
requestId: string;
}
}
```
Both middleware and handlers are then typed:
```ts title="src/routes/users.ts"
.handler(async ({ params, request }) => {
console.log(request.requestId);
// ...
});
```
The adapter also sets `request.kizunaRoute` on every matched request, holding the route that matched.
## Streams
A [stream](/docs/streaming) response hijacks the reply and is piped to `reply.raw` after its headers are flushed. The generator's `signal` fires when the raw response closes before the stream has finished.
## Reference
- [`defineConfig`](/docs/reference/define-config)
- [a route's `handler`](/docs/reference/k-route)
- [an identity's `guard`](/docs/reference/k-identity)
---
# Hono
Source: /docs/adapters/hono
---
title: Hono
description: Mount a Kizuna API on a Hono application.
---
`@kizunajs/hono` serves a Kizuna API from a [Hono](https://hono.dev) application. Hono runs on Cloudflare Workers, Deno, Bun, Node.js, and other runtimes.
**Requires Hono >= 4.**
## The adapter
`honoAdapter()` is what you name in `kizuna.config.ts`. Naming it is what gives every handler on this API Hono's own `Context`, typed.
## Declare a route
```ts title="src/routes/users.ts"
import { k } from '../k';
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: ListUsersQuerySchema,
responses: {
200: UserListSchema,
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
})),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params }) => {
const user = await db.users.findById(params.id);
if (!user) {
return {
status: 404,
body: {
detail: 'Not found',
},
};
}
return {
status: 200,
body: user,
};
}),
});
```
## Name Hono in your config
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { honoAdapter } from '@kizunajs/hono';
import { users } from './src/routes/users';
export default defineConfig({
adapter: honoAdapter(),
routes: [users],
});
```
## Mount it
```ts title="src/index.ts"
import { Hono } from 'hono';
import kizuna from '../kizuna.config';
const app = new Hono();
kizuna.api.mount(app);
export default app;
```
## Handler context
Each handler receives `{ params, query, body, headers, c }`. The `c` is Hono's `Context`, useful when you need to read cookies, reach environment bindings, or use anything else Hono exposes.
```ts title="src/routes/users.ts"
.handler(async ({ params, c }) => {
const locale = c.req.header('accept-language');
return {
status: 200,
body: await db.users.findById(params.id),
};
});
```
## Environment bindings
On runtimes like Cloudflare Workers, bindings live on the Hono context as `c.env`.
```ts title="src/routes/users.ts"
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
},
})
.handler(async ({ params, c }) => ({
status: 200,
body: await c.env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(params.id).first(),
})),
```
## Guards
A guard sits on the identity it authenticates, and receives the credential extracted and typed, alongside the native `c`. See the [Authentication guide](/docs/authentication).
```ts title="src/identities.ts"
import { k } from './k';
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny, c }) => {
const session = bearer ? await verifySession(bearer.token, c.env) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
## Middleware
For request-scoped values handlers need, use [request context](/docs/request-context). For other middleware, such as logging, rate limiting, and caching headers, use Hono's own `app.use`. Authentication belongs in [guards](#guards).
## Options
```ts title="src/index.ts"
kizuna.api.mount(app, {
responseValidation: false,
});
```
| Option | Default | Description |
| -------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `responseValidation` | `false` | Validate handler return values against response schemas. Enable in development. |
| `formatError` | none | Reshape error (`>= 400`) response bytes for migrating clients. Most don't need it (use Problem Details extension members). See [Migrating an existing API](/docs/migration/existing-api). |
## Streams
A [stream](/docs/streaming) response is returned as a `ReadableStream` body. The generator's `signal` is `c.req.raw.signal`, which the Node server aborts when the client goes away.
## Reference
- [`defineConfig`](/docs/reference/define-config)
- [a route's `handler`](/docs/reference/k-route)
- [an identity's `guard`](/docs/reference/k-identity)
---
# Next.js
Source: /docs/adapters/next
---
title: Next.js
description: Mount a Kizuna API on a Next.js App Router catch-all route.
---
`@kizunajs/next` serves a Kizuna API from a Next.js App Router application, through a single catch-all route file.
**Requires Next.js ≥ 16** (App Router).
## The adapter
`nextAdapter()` is what you name in `kizuna.config.ts`. Naming it is what gives every handler on this API Next's own `NextRequest`, typed.
## Declare a route
```ts title="src/routes/users.ts"
import { k } from '../k';
export const users = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: ListUsersQuerySchema,
responses: {
200: UserListSchema,
},
})
.handler(async ({ query }) => ({
status: 200,
body: {
users: await db.users.findMany({
skip: (query.page - 1) * query.limit,
take: query.limit,
}),
total: await db.users.count(),
},
})),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(async ({ params }) => {
const user = await db.users.findById(params.id);
if (!user) {
return {
status: 404,
body: {
detail: 'Not found',
},
};
}
return {
status: 200,
body: user,
};
}),
});
```
## Name Next in your config
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { nextAdapter } from '@kizunajs/next';
import { users } from './src/routes/users';
export default defineConfig({
adapter: nextAdapter(),
routes: [users],
});
```
## Mount it at a catch-all route
`mount` hands back a handler per HTTP method, which Next dispatches for you:
```ts title="src/app/api/[...kizuna]/route.ts"
import kizuna from '../../../../kizuna.config';
export const { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } = kizuna.api.mount({
basePath: '/api',
});
```
## Handler context
Each handler receives `{ params, query, body, headers, request }`. The `request` is the native `NextRequest`, useful when you need to read cookies or anything else Next exposes.
```ts title="src/routes/users.ts"
.handler(async ({ params, request }) => {
const theme = request.cookies.get('theme')?.value;
return {
status: 200,
body: await db.users.findById(params.id),
};
});
```
## Guards
A guard sits on the identity it authenticates, and receives the credential extracted and typed, alongside the native `request`. See the [Authentication guide](/docs/authentication).
```ts title="src/identities.ts"
import { k } from './k';
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny }) => {
const session = bearer ? await verifySession(bearer.token) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
## Middleware
For request-scoped values handlers need, use [request context](/docs/request-context). For cache headers, declare a [cache policy](/docs/caching) on the route. For other middleware, such as logging and rate limiting, use Next.js's own [middleware](https://nextjs.org/docs/app/building-your-application/routing/middleware), or the [`requestMiddleware`](#requestmiddleware) option to run middleware after route matching. Authentication belongs in [guards](#guards).
## Options
```ts title="src/app/api/[...kizuna]/route.ts"
export const { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } = kizuna.api.mount({
basePath: '/api',
responseValidation: false,
});
```
| Option | Default | Description |
| -------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------ |
| `basePath` | `''` | Path prefix to strip when matching incoming paths |
| `requestMiddleware` | `[]` | Middleware run after route matching, before the handler. See [`requestMiddleware`](#requestmiddleware) |
| `responseValidation` | `false` | Validate handler return values against response schemas. Enable in development. |
| `onError` | none | Map a thrown error into a response (inbound migration seam); return an `AdapterResult`/`Response` to override the default 500. |
## `onError`
Pass `onError` to `nextAdapter()`, or to `mount`, to send your own response:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: nextAdapter({
onError: (error) => {
if (error instanceof AuthError) {
return {
kind: 'raw-response',
response: new Response(
JSON.stringify({
message: 'Unauthorized',
}),
{
status: 401,
headers: {
'Content-Type': 'application/json',
},
}
),
};
}
},
}),
routes,
});
```
## `requestMiddleware`
`requestMiddleware` applies a flat array of middleware to every matched route, after route matching and before the handler. Each middleware receives `(request, route)`, where `route` is the matched route's `path` and `method`, and may return a `Response` to short-circuit.
## Type-safe request properties
Middleware that sets custom properties on the request, such as a request id, needs module augmentation to extend `NextRequest` so handlers reach them without casts. Authentication data does not: guards hand handlers typed context directly.
```ts title="next.d.ts"
import 'next/server';
declare module 'next/server' {
interface NextRequest {
requestId: string;
}
}
```
Both middleware and handlers are then typed:
```ts title="src/routes/users.ts"
.handler(async ({ params, request }) => {
console.log(request.requestId);
// ...
});
```
## Multipart / file uploads
Routes with `contentType: 'multipart/form-data'` work natively. The adapter calls `request.formData()` internally.
```ts title="src/routes/users.ts"
.handler(async ({ body }) => {
await storage.upload(body.userId, body.file);
return {
status: 200,
body: {
size: body.file.size,
userId: body.userId,
},
};
});
```
## Streams
A [stream](/docs/streaming) response is returned as a `NextResponse` with a `ReadableStream` body. The generator's `signal` is `request.signal`.
## Reference
- [`defineConfig`](/docs/reference/define-config)
- [a route's `handler`](/docs/reference/k-route)
- [an identity's `guard`](/docs/reference/k-identity)
---
# Fetch
Source: /docs/clients/fetch
---
title: Fetch
description: A fully typed HTTP client for consuming Kizuna routes in the browser, on the server, or in React Native.
---
`@kizunajs/fetch` writes a typed client for your routes, a wrapper around the native `fetch` API. The client runs anywhere `fetch` does, [React Native](#react-native) included.
The generated file carries named types, a table of methods and paths, and the code that sends the requests. It imports nothing, so the app that calls your API installs nothing. Its types come from the global `fetch`, so the DOM lib, `@types/node` or React Native's types are all it needs. `@kizunajs/fetch` goes beside `kizuna.config.ts`:
## Add it to your config
Point `fetchClient` at the file you want written:
```ts title="kizuna.config.ts"
import { fetchClient } from '@kizunajs/fetch';
export default defineConfig({
adapter: expressAdapter(),
routes: [users],
clients: [
fetchClient({
output: './src/lib/api-client.generated.ts',
}),
],
});
```
```bash
kizuna generate
```
## What it writes
```ts title="src/lib/api-client.generated.ts"
/* eslint-disable */
/**
* Generated by @kizunajs/fetch. Do not edit.
*
* Regenerate: kizuna generate
*/
export namespace API {
/**
* A user in the system
*/
export type User = {
id: string;
name: string;
nickname?: string;
};
export namespace UsersGetUser {
export type Params = {
id: string;
};
export type Result =
| { status: 200; body: User; headers: Record }
| { status: 404; body: ProblemDetails; headers: Record };
}
}
```
Every model keeps the title you gave `Kizuna.model`, and is declared once however many routes use it. Below the types come the route table, `createClient`, and the code that sends requests.
## Create the client
The generated file exports `createClient`. Wrap it once, where the rest of your app imports it from:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'http://localhost:3000',
});
```
The client mirrors your route groups, one function per route.
## Call a route
```ts title="users.ts"
// GET /users?page=1&limit=10
const { status, body } = await apiClient.users.listUsers({
query: {
page: 1,
limit: 10,
},
});
// body is { users: User[]; total: number }
```
```ts title="users.ts"
// POST /users
const result = await apiClient.users.createUser({
body: {
name: 'Alice',
email: 'alice@example.com',
},
});
if (result.status === 201) {
console.log(result.body.id);
} else {
// result.status === 400
console.error(result.body.detail);
}
```
```ts title="users.ts"
// GET /users/:id
const { status, body } = await apiClient.users.getUser({
params: {
id: 'usr_abc123',
},
});
```
`params` is required when the path contains `:param` placeholders, and rejected when it does not.
When the route declares a `pathParams` schema, `params` is typed by that schema instead of the path template. A [branded ID](#branded-ids) reaches the caller:
```ts title="users.ts"
// the route declares: pathParams: z.object({ id: UserId }), where UserId = Kizuna.brand('UserId', z.string())
const { body } = await apiClient.users.getUser({
params: {
id: userId, // must be an API.UserId, a plain string is a type error
},
});
```
## `ClientConfig`
```ts
export interface ClientConfig {
baseUrl: string;
baseHeaders?: Record;
credentials?: RequestInit['credentials'];
fetch?: typeof fetch;
onRequest?: (request: OutgoingRequest) => void | Promise;
retry?: RetryOptions;
reconnect?: ReconnectOptions;
}
```
| Option | Description |
| ------------- | --------------------------------------------------------------------------------- |
| `baseUrl` | Base URL prepended to every route path |
| `baseHeaders` | Headers merged into every request |
| `credentials` | Passed as `credentials` to every `fetch` call |
| `fetch` | Custom fetch implementation (e.g. for testing or a polyfill) |
| `onRequest` | Callback before each request, receiving the `OutgoingRequest` it is about to send |
| `retry` | Retry a request the server could not take yet, see [Retries](#retries) |
| `reconnect` | Reconnect a dropped event stream, see [Resuming](/docs/streaming#resuming) |
Setting a header on the `headers` of an `OutgoingRequest` sets it on the request that goes out, which is how a credential that lives in storage is read per request rather than fixed at construction. See [React Native](#reading-a-token-from-storage).
## Request context
When your config declares [request context](/docs/request-context) headers, `createClient` takes them too, typed by what the API asked for, and sends them on every request. This is a different thing from the `OutgoingRequest` above: these are the headers your API declared with [`k.requestContext`](/docs/reference/k-request-context), and the generated file exports their type as `RequestContext`:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'http://localhost:3000',
requestContext: {
'x-posthog-session-id': sessionId,
},
});
```
An API that declares none takes `ClientConfig` alone.
## Per-request headers
If a route declares a `headers` schema, the client requires those headers:
```ts title="users.ts"
// the route declares: headers: z.object({ 'x-request-id': z.string() })
const { body } = await apiClient.users.getUser({
params: { id: 'usr_abc123' },
headers: { 'x-request-id': crypto.randomUUID() },
});
```
Routes without a `headers` schema accept an optional `headers?: Record` for arbitrary request headers.
## Authentication
When your routes name an identity with [identities](/docs/authentication), send the credential in `baseHeaders`. The server's guards read it, and answer `401`/`403` when it's missing or insufficient:
```ts title="src/lib/api-client.ts"
const apiClient = createClient({
baseUrl: 'https://api.example.com',
baseHeaders: {
Authorization: `Bearer ${token}`,
},
});
```
## Per-request fetch options
Pass any `RequestInit` option via `fetchOptions`:
```ts title="users.ts"
const { body } = await apiClient.users.listUsers({
query: { page: 1 },
fetchOptions: {
signal: AbortSignal.timeout(5000),
},
});
```
## Retries
A busy server answers `503 Service Unavailable` or `429 Too Many Requests` and says in `Retry-After` when to come back. Turn retries on and the client waits that long and sends the request again:
```ts title="src/lib/api-client.ts"
export const apiClient = createClient({
baseUrl: import.meta.env.VITE_API_URL,
retry: {
maximumAttempts: 3,
},
});
```
Only `GET`, `HEAD`, `OPTIONS`, `PUT` and `DELETE` are retried, the methods [RFC 9110](https://www.rfc-editor.org/rfc/rfc9110#section-9.2.2) lets a client send twice without asking. A `POST` that fails is handed back, so a payment never goes through twice. A network error is retried too, and a cancelled request never is.
Without a `Retry-After`, the client backs off, waiting at most `initialDelay` (500 ms) the first time and doubling from there. A `Retry-After` longer than `maximumDelay` (30 s) hands the response back instead of waiting.
TanStack Query retries failed queries on its own. Use one or the other.
## Response type
Each call returns a discriminated union over the route's defined status codes:
```ts
type ListUsersResponse = {
status: 200;
body: {
users: User[];
total: number;
};
headers: Record;
};
```
Every route's types are in the namespace, so `API.UsersListUsers.Query` is what `listUsers` takes as `query`, and `API.UsersListUsers.Result` is what it resolves to. [Wrapping the client](/docs/extend/wrap-fetch-client) builds on them.
## Streams
On a status the route declares with [`stream`](/docs/streaming), `body` is an async iterable in place of a value. Read it with `for await`, and each message narrows on `event` to its own `data`:
```ts title="chat.ts"
const result = await apiClient.assistant.reply({
body: {
prompt,
},
});
if (result.status === 200) {
for await (const message of result.body) {
if (message.event === 'delta') console.log(message.data.text);
}
}
```
The other statuses arrive parsed as they do today. Aborting the `signal` in `fetchOptions` closes the connection.
## Validation errors
A route with a `body` or `query` schema can answer `400` when the request fails validation. It is in the response type already, without you declaring it.
```ts title="users.ts"
const result = await apiClient.users.createUser({
body: {
name: '',
email: 'not-an-email',
},
});
if (result.status === 400) {
for (const issue of result.body.errors) {
console.log(issue.code, issue.path, issue.message);
// 'invalid_string_format', ['email'], 'Invalid email'
}
}
```
A route with neither takes no `400` in its response type.
### `isValidationError`
If your routes also declares a `400` response on the same route, the body becomes a union of your type and `ValidationError`. Use the `isValidationError` type guard to distinguish them:
The generated file exports it:
```ts title="users.ts"
import { isValidationError } from './lib/api-client.generated';
if (result.status === 400) {
if (isValidationError(result.body)) {
// kizuna validation error
} else {
// your routes' 400 response
}
}
```
## Refusals
A route whose `auth` names an identity carries `401` and `403` in its response type, as [Problem Details](/docs/reference/problem-details-schema). A public route carries neither. A route declaring its own `403` keeps that body alongside, the way a declared `400` sits beside the validation error.
```ts title="workspace.ts"
const result = await apiClient.workspace.deleteWorkspace();
if (result.status === 403) {
console.log(result.body.detail);
}
```
## React Native
The client works in Expo and in bare React Native, importing the [same generated client](/docs/project-structure) as your website.
### Reading a token from storage
`baseHeaders` is fixed when the client is constructed, so a credential that lives in storage goes in `onRequest`. It runs before every request, and the `Headers` it receives are the ones sent:
```ts title="src/lib/api-client.ts"
import * as SecureStore from 'expo-secure-store';
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: process.env.EXPO_PUBLIC_API_URL,
onRequest: async ({ headers }) => {
const token = await SecureStore.getItemAsync('accessToken');
if (token) headers.set('Authorization', `Bearer ${token}`);
},
});
```
### Uploading a file
Expo SDK 54 and later ships a `File` class, and `expo/fetch` is the implementation that puts one inside a multipart body. Hand the client Expo's:
```ts title="src/lib/api-client.ts"
import { fetch } from 'expo/fetch';
export const apiClient = createClient({
baseUrl: process.env.EXPO_PUBLIC_API_URL,
fetch,
});
```
Then build the `FormData` yourself, since the client forwards a `FormData` body untouched:
```ts title="upload-avatar.ts"
import { File } from 'expo-file-system';
const formData = new FormData();
formData.append('userId', userId);
formData.append('file', new File(photo.uri));
const { status } = await apiClient.users.uploadAvatar({
body: formData as never,
});
```
The cast is there because the route types the field as the `File` the server receives once the multipart request lands.
Bare React Native has no `File` it can build from a path. Append a `{ uri, name, type }` descriptor in its place and leave `fetch` out of the client config, since that form is the one the global `fetch` understands.
## Named types
The generated file gives every model a name, the thing the Swift and Kotlin clients have always had:
```tsx
import type { API } from './api-client.generated';
export function UserCard({ user }: { user: API.User }) {
return {user.name};
}
```
`users.getUser` becomes `UsersGetUser` in every generated client, so the three read as one API.
The namespace is called `API` until the config says otherwise, and `namespace` names it whatever the app calls its API. Every route type is reached through that name, so `MyAPI.UsersGetUser.Params`.
```ts title="kizuna.config.ts"
clients: [
fetchClient({
output: './src/lib/api-client.generated.ts',
namespace: 'MyAPI',
}),
],
```
## Branded IDs
A [branded ID](/docs/zod#branded-ids) becomes a named type, `API.UserId`, and a `toUserId` function that makes one. The parameter's type shows it, and passing a plain `string` does not compile.
An ID from a response is already an `API.UserId`, so it passes into the next call as it is:
```ts
const created = await client.users.createUser({
body: {
name: 'Ada Lovelace',
email: 'ada@example.com',
},
});
if (created.status === 201) {
await client.users.deleteUser({
params: {
id: created.body.id,
},
});
}
```
A `string` from outside the API, like a URL, is wrapped once:
```ts
import { toUserId } from './api-client.generated';
const user = await client.users.getUser({
params: {
id: toUserId(searchParams.userId),
},
});
```
It is still a `string`, so it renders and compares like one.
## Documentation in the client
Each method carries what the route declared, so an editor shows it at the call site: the route's `summary` and `description`, `@deprecated` with its migration message, and an `@example` of the call with the arguments it cannot be called without.
```ts
/**
* Delete a user
*
* @deprecated use `archiveUser` instead
*
* @example
* const result = await client.users.deleteUser({
* params: {
* id: '1',
* },
* });
*/
deleteUser(args: { params: API.UsersDeleteUser.Params }): Promise;
```
Fields carry theirs too. A schema's `description` becomes the field's doc comment, and anything it declares under `example` or `examples` in [Zod metadata](https://zod.dev/metadata) becomes an `@example`:
```ts
const UserSchema = z.object({
email: z.email().meta({
description: 'Email address',
example: 'alice@example.com',
}),
});
```
The same metadata is what the OpenAPI document publishes as its examples, so the two never drift.
## What ships
The generated file imports nothing. It carries no schema library, no handlers and no server code. The table it carries is method, path, content type, and each status the route answers with, marking the ones that stream:
```ts
const routes: GeneratedRoutes = {
users: {
getUser: {
method: 'GET',
path: '/users/:id',
responses: {
200: {},
404: {},
},
},
},
};
```
That is all the code below it reads. The types above it are erased at build time.
`kizuna generate` writes the table and the code that reads it into one file, so the two always come from the same release. Upgrading kizuna changes the client only when you regenerate it.
## Keeping it current
The file can fall behind your routes, and it fails loudly when it does: add a route and the client has no method for it, which your compiler catches. Regenerate it as part of your build and have CI fail on a dirty tree afterwards.
## Reference
- [`isValidationError`](/docs/reference/is-validation-error)
- [`k.requestContext()`](/docs/reference/k-request-context)
- [Configuration](/docs/config)
---
# Kotlin
Source: /docs/clients/kotlin
---
title: Kotlin
description: Generate a native Kotlin client from your routes, using OkHttp and kotlinx.serialization.
---
The Kotlin client is new and still settling. The generated API surface may change while v2 is in beta, so pin your version if you depend on it.
`@kizunajs/kotlin` generates a native Kotlin client from your Kizuna routes. The generated client uses OkHttp for HTTP, kotlinx.serialization for JSON, and Kotlin coroutines for async.
## Add the dependencies
The generated client uses OkHttp, kotlinx.serialization, and coroutines. Add them to your `build.gradle.kts`:
```kotlin title="build.gradle.kts"
dependencies {
implementation("com.squareup.okhttp3:okhttp:4.12.0")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.7.3")
implementation("org.jetbrains.kotlinx:kotlinx-datetime:0.6.1")
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.9.0")
}
```
## Add it to your config
Point `kotlinClient` at the file you want written:
```ts title="kizuna.config.ts"
import { kotlinClient } from '@kizunajs/kotlin';
export default defineConfig({
adapter: expressAdapter(),
routes,
clients: [
kotlinClient({
output: './android/app/src/main/kotlin/com/example/APIClient.kt',
namespace: 'API',
package: 'com.example',
}),
],
});
```
```bash
kizuna generate
```
| Option | Description |
| --------------------- | --------------------------------------------------------------------------------------------------- |
| `output` | Where the generated `.kt` file goes |
| `namespace` | Object wrapping all generated types, `API` by default |
| `package` | Package declaration for the generated file, such as `com.example.api` |
| `camelCaseProperties` | Convert wire field names to camelCase properties, mapped back via `@SerialName` |
| `unknownEnumCase` | Emit enums as a sealed interface with an `Unknown` member so new server values don't break decoding |
The path is relative to the config, so a client can land outside the TypeScript project. When the Android app lives in the same repository, `../android/app/src/main/kotlin/com/example/APIClient.kt` writes straight into it. An app in its own repository takes the generated file the way it takes any other vendored source, by copying it in from a build step or committing it.
## Add it to your project
Add the generated file to your Kotlin project as a regular source file. Set `package` so the file declares a package matching its directory, which Android and JVM projects expect.
## Call a route
Request inputs are built inside a lambda: `params` (path), `query`, `headers`, and `body`. You name no types, and missing a required field is a compile error:
```kotlin title="APISetup.kt"
val client = APIClient(baseUrl = "https://api.example.com")
```
```kotlin title="UserService.kt"
// path param + header, groups chain in order
val user = client.users.getUser {
params(
id = "1",
).headers(
xRequestId = "trace-1",
)
}
// query, all-optional, so it can be omitted entirely
val page = client.users.listUsers {
query(
page = 1,
limit = 20,
)
}
val all = client.users.listUsers()
// object body
val created = client.users.createUser {
body(
name = "Ada",
email = "ada@example.com",
)
}
```
## Use it in a screen
A schema wrapped in [`Kizuna.model`](/docs/reference/kizuna-model) generates a named type, so a composable can name it in its signature and every route that returns a user hands back the same `API.User`:
```kotlin title="UserRow.kt"
@Composable
fun UserRow(user: API.User) {
Column {
Text(user.name)
Text(user.id, style = MaterialTheme.typography.bodySmall)
}
}
```
```kotlin title="UserList.kt"
@Composable
fun UserList(client: APIClient) {
var users by remember { mutableStateOf(emptyList()) }
LaunchedEffect(Unit) {
users = client.users.listUsers().body.users
}
LazyColumn {
items(users, key = { it.id }) { user ->
UserRow(user)
}
}
}
```
## Branded IDs
A [branded ID](/docs/zod#branded-ids) becomes a value class, `API.UserId`, serialized as the bare string. The parameter's type shows it, and passing a `String` does not compile.
An ID from a response is already an `API.UserId`, so it passes into the next call as it is:
```kotlin
val created = client.users.createUser {
body(
name = "Ada Lovelace",
email = "ada@example.com",
)
}
client.users.deleteUser {
params(
id = created.body.id,
)
}
```
A `String` from outside the API, like a deep link, is wrapped once:
```kotlin
val userId = uri.lastPathSegment ?: return
val user = client.users.getUser {
params(
id = API.UserId(userId),
)
}
```
`value` reads the string back:
```kotlin
Text(user.body.id.value)
```
## Optional and null fields
An `.optional()` or `.nullish()` field is a `String?` that defaults to `null` and is left out of the request. A `.nullable()` field is a `String?` with no default, sent as `null` when you pass `null`:
```kotlin
client.users.updatePreferences {
params(
id = userId,
).body(
timezone = null,
mutedChannels = emptyList(),
)
}
```
See [Optional and null fields](/docs/zod#optional-and-null-fields) for which to declare.
## Property naming
By default, field names are emitted verbatim, so `total_count` on the wire stays `total_count` in the generated type. A `@file:Suppress(...)` header keeps the IDE green over the generated file.
Pass `--camel-case` to convert wire fields to camelCase properties (`total_count` becomes `totalCount`), preserving the wire name via `@SerialName`.
## Unknown enum case (open enums)
By default a `z.enum` is a closed `enum class` that throws on a wire value it doesn't know, failing the whole response. Pass `--unknown-enum-case` to make enums forward-compatible: each becomes a `sealed interface` with a `data object` per known value plus an `Unknown(wireValue)` member, so an unrecognised value deserializes to `Unknown("newValue")` instead of throwing:
```kotlin title="EventFeed.kt"
when (val kind = event.kind) {
EventKind.LOGIN, EventKind.LOGOUT, EventKind.SIGNUP -> render(event)
is EventKind.Unknown -> log("skipping unknown event kind: ${kind.wireValue}")
}
```
The raw value is preserved as `wireValue`, so re-encoding writes it back unchanged. Discriminated unions still throw on an unknown discriminator.
## Generated client
The generated file exports a typed class with `suspend` methods for each route and sub-clients for grouped routes. Each method takes a request-builder lambda whose receiver (`Scope`) exposes one factory per input group. The lambda must return the operation's `Args`, and only chains that provide every required group produce an `Args`, which is what makes missing required inputs a compile error. Each method returns the route's `Response` (or `Unit` for routes with no success body) and throws its `Failure`:
```kotlin title="APIClient.kt"
import kotlinx.serialization.*
import okhttp3.*
class APIClient(
private val baseUrl: String,
private val client: OkHttpClient = OkHttpClient(),
private val json: Json = Json { ignoreUnknownKeys = true },
private val requestInterceptor: (suspend (Request.Builder) -> Unit)? = null,
private val responseInterceptor: (suspend (Request, Response) -> Unit)? = null
) {
val users = APIUsersClient(...)
object UsersListUsers {
data class Query(
val page: Int? = null,
val limit: Int? = null
)
sealed interface Args {
val query: Query?
}
object Scope {
fun query(page: Int? = null, limit: Int? = null): AfterQuery = ...
}
// AfterQuery, Response, Result, Success, Failure ...
}
@Throws(UsersListUsers.Failure::class)
suspend fun listUsers(build: APIClient.UsersListUsers.Scope.() -> APIClient.UsersListUsers.Args = { query() }): APIClient.UsersListUsers.Result {
// ...
}
}
```
## Interceptors & auth
`requestInterceptor` runs before every request, so attach auth headers here. `responseInterceptor` observes every response. Both may suspend (e.g. to refresh a token):
```kotlin title="APISetup.kt"
val client = APIClient(
baseUrl = "https://api.example.com",
requestInterceptor = { builder ->
builder.header("Authorization", "Bearer $token")
},
responseInterceptor = { request, response ->
println("${request.method} ${request.url} -> ${response.code}")
}
)
```
## Handling responses
Success returns a `Result` with the decoded `body` (and `headers` when the route declares them). Routes with multiple success codes give you a sealed `Success` to `when` over; void routes return `Unit`.
Errors **throw** a sealed `Failure` with one named subtype per declared status (`NotFound`, `BadRequest`, …) carrying its typed `body`, plus `Unexpected(statusCode, data)` for undeclared statuses and `Decoding(cause, statusCode, data)` for bodies that don't parse. Catch one subtype, or `when` over the sealed class, and the compiler lists every case:
```kotlin title="UserService.kt"
try {
val response = client.users.getUser {
params(
id = "1",
)
}
println(response.body)
} catch (error: APIClient.UsersGetUser.Failure) {
when (error) {
is APIClient.UsersGetUser.Failure.NotFound -> println("missing: ${error.body.detail}")
is APIClient.UsersGetUser.Failure.Unexpected -> println("status ${error.statusCode}")
is APIClient.UsersGetUser.Failure.Decoding -> throw error
}
}
```
Methods throw, so `runCatching` works for a functional style:
```kotlin title="UserService.kt"
val result = runCatching {
client.users.getUser {
params(
id = "1",
)
}
}
result.onSuccess { println(it.body) }.onFailure { println("failed: ${it.message}") }
```
## Deprecation
Routes with `deprecated` and fields with `.meta({ deprecated: ... })` emit `@Deprecated` in the generated Kotlin code, with the message when one is set:
```kotlin title="APIClient.kt"
@Deprecated("use newRoute instead")
suspend fun deleteUser(build: APIClient.UsersDeleteUser.Scope.() -> APIClient.UsersDeleteUser.Args) {
// ...
}
```
## Retries
A busy server answers `503` or `429` and says in `Retry-After` when to come back. Pass a `RetryPolicy` and the client waits that long and sends the request again:
```kotlin title="Api.kt"
val api = APIClient(
baseUrl = "https://api.example.com",
retry = APIClient.RetryPolicy(maximumAttempts = 3),
)
```
Only `GET`, `HEAD`, `OPTIONS`, `PUT` and `DELETE` are retried, so a `POST` that fails is handed back rather than sent twice. A network error is retried too, and a cancelled coroutine never is. Without a `Retry-After` the client backs off from `initialDelay` (500 ms), and a `Retry-After` longer than `maximumDelay` (30 s) hands the response back.
## Streams
A route whose response [streams](/docs/streaming) returns its `body` as a `Flow`. Named events become a sealed `Event` interface with one class per event, each carrying its decoded payload as `data`:
```kotlin title="AssistantScreen.kt"
val result = client.assistant.reply {
body(
prompt = "hello",
)
}
result.body.collect { event ->
when (event) {
is APIClient.AssistantReply.Event.Delta -> text.append(event.data.text)
is APIClient.AssistantReply.Event.Done -> println(event.data.outputTokens)
}
}
```
A stream of one schema yields that type directly, a `text/*` stream yields one `String` per line, and a binary stream yields `ByteArray` chunks. The status and headers are checked before the method returns, so a `400` throws its `Failure` as on any route. The connection is open when the method returns, so collect the flow; cancelling the collector closes it. A route that mixes a streamed status with another `2xx` is left out of the client, with a warning.
Pass a `ReconnectPolicy` to reconnect an event stream whose connection drops. The client sends the id of the last event it received as `Last-Event-ID`, and the flow carries on. See [Resuming](/docs/streaming#resuming).
```kotlin title="Api.kt"
val api = APIClient(
baseUrl = "https://api.example.com",
reconnect = APIClient.ReconnectPolicy(),
)
```
## Keeping it current
`kizuna generate` writes every client the config declares, so the Kotlin one is never generated on its own:
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate",
"kizuna:check": "kizuna generate --check"
}
}
```
Run [`kizuna generate --check`](/docs/config#kizuna-generate---check) in CI, and a Kotlin client nobody regenerated fails the build instead of drifting from the routes it was generated from.
## Reference
- [`generateKotlinClient`](/docs/reference/generate-kotlin-client)
---
# Swift
Source: /docs/clients/swift
---
title: Swift
description: Generate a native Swift client from your routes, using URLSession and Codable.
---
`@kizunajs/swift` generates a native Swift client from your Kizuna routes. The generated client uses `URLSession` and `Codable`, with no third-party Swift dependencies required.
## Add it to your config
Point `swiftClient` at the file you want written:
```ts title="kizuna.config.ts"
import { swiftClient } from '@kizunajs/swift';
export default defineConfig({
adapter: expressAdapter(),
routes,
clients: [
swiftClient({
output: './ios/MyApp/Generated/APIClient.swift',
namespace: 'API',
}),
],
});
```
```bash
kizuna generate
```
| Option | Description |
| --------------------- | --------------------------------------------------------------------------------------- |
| `output` | Where the generated `.swift` file goes |
| `namespace` | Public enum wrapping all generated types, `API` by default |
| `camelCaseProperties` | Convert wire field names to camelCase properties with CodingKeys |
| `unknownEnumCase` | Emit enums with an `unknown(String)` fallback so new server values don't break decoding |
The path is relative to the config, so a client can land outside the TypeScript project. When the iOS app lives in the same repository, `../ios/MyApp/Generated/APIClient.swift` writes straight into it. An app in its own repository takes the generated file the way it takes any other vendored source, by copying it in from a build step or committing it.
## Add it to your project
Add the generated file to your Xcode project or Swift package as a regular source file. It needs no third-party Swift dependencies.
## Call a route
```swift title="APISetup.swift"
let client = APIClient(baseURL: URL(string: "https://api.example.com")!)
```
Request inputs are passed as components named after the route's input groups: `.params` (path), `.body`, `.query`, and `.headers`:
```swift title="UserService.swift"
// object body
let created = try await client.users.createUser(
.body(
name: "Ada",
email: "ada@example.com"
)
)
// path param + header
let user = try await client.users.getUser(
.params(id: "42"),
.headers(xRequestId: "trace-1")
)
// query
let page = try await client.users.listUsers(
.query(page: 1, limit: 20)
)
let all = try await client.users.listUsers()
// discriminated-union body
try await client.sendNotification(
.body(
.email(to: "ada@example.com", subject: "Hi")
)
)
```
## Use it in a screen
A schema wrapped in [`Kizuna.model`](/docs/reference/kizuna-model) generates a named type, so a view can name it in its signature and every route that returns a user hands back the same `API.User`:
```swift title="UserRow.swift"
import SwiftUI
struct UserRow: View {
let user: API.User
var body: some View {
VStack(alignment: .leading) {
Text(user.name)
Text(user.id)
.font(.caption)
}
}
}
```
```swift title="UserList.swift"
struct UserList: View {
@State private var users: [API.User] = []
var body: some View {
List(users, id: \.id) { user in
UserRow(user: user)
}
.task {
if let response = try? await client.users.listUsers() {
users = response.body.users
}
}
}
}
```
## Branded IDs
A [branded ID](/docs/zod#branded-ids) becomes a struct, `API.UserId`, encoded as the bare string. The parameter's type shows it, and passing a `String` does not compile.
An ID from a response is already an `API.UserId`, so it passes into the next call as it is:
```swift
let created = try await client.users.createUser(
.body(
name: "Ada Lovelace",
email: "ada@example.com"
)
)
try await client.users.deleteUser(
.params(id: created.body.id)
)
```
A `String` from outside the API, like a deep link, is wrapped once:
```swift
let userID = url.lastPathComponent
let user = try await client.users.getUser(
.params(id: API.UserId(userID))
)
```
`rawValue` reads the string back:
```swift
Text(user.body.id.rawValue)
```
## Optional and null fields
An `.optional()` or `.nullish()` field is a `String?` that defaults to `nil` and is left out of the request. A `.nullable()` field is a `String?` with no default, sent as `null` when you pass `nil`:
```swift
try await client.users.updatePreferences(
.params(id: userID),
.body(
timezone: nil,
mutedChannels: []
)
)
```
See [Optional and null fields](/docs/zod#optional-and-null-fields) for which to declare.
## Property naming
By default, field names are emitted verbatim, so `total_count` on the wire stays `total_count` in the generated type.
Pass `--camel-case` to convert wire fields to camelCase properties (`total_count` becomes `totalCount`), preserving the wire name via `CodingKeys`.
## Unknown enum case (open enums)
By default a `z.enum` is a closed Swift enum that throws on a wire value it doesn't know, failing the whole response. Pass `--unknown-enum-case` to make enums forward-compatible: each gains an `unknown(String)` case, so an unrecognised value decodes to `.unknown("newValue")` instead of throwing:
```swift title="EventFeed.swift"
switch event.kind {
case .login, .logout, .signup:
render(event)
case .unknown(let raw):
log("skipping unknown event kind: \(raw)")
}
```
The raw value is preserved, so re-encoding writes it back unchanged. Discriminated unions still throw on an unknown discriminator.
## Generated client
The generated file exports a `Sendable` client with methods for each route and sub-clients for grouped routes. It is `Sendable`, so sharing it across tasks needs no actor hop per request. Each request group is a nested struct with a group-named factory:
```swift title="APIClient.swift"
import Foundation
public final class APIClient: Sendable {
public let baseURL: URL
public let session: URLSession
public var users: APIUsersClient { ... }
public func listUsers(_ query: APIClient.ListUsers.Query = .query()) async throws(APIClient.ListUsers.Failure) -> APIClient.ListUsers.Result {
// ...
}
public enum ListUsers {
public struct Query: Sendable {
public let page: Int?
public let limit: Int?
public init(page: Int? = nil, limit: Int? = nil) { ... }
public static func query(page: Int? = nil, limit: Int? = nil) -> Self { .init(page: page, limit: limit) }
}
// Response, Result, Failure ...
}
}
```
## Cancellation
`Failure.cancelled` covers a cancelled request, which SwiftUI produces routinely: a view carrying a `.task` cancels it on disappear, so a screen that loads and then closes arrives in your error path. An error path shared across several routes can check `(error as? any KizunaFailure)?.isCancelled` instead of matching each route's own enum.
## Deprecation
Routes with `deprecated` and fields with `.meta({ deprecated: ... })` emit `@available(*, deprecated)` in the generated Swift code, with the message when one is set:
```swift title="APIClient.swift"
@available(*, deprecated)
public func deleteUser(_ params: APIClient.DeleteUser.Params) async throws(APIClient.DeleteUser.Failure) {
// ...
}
```
## Retries
A busy server answers `503` or `429` and says in `Retry-After` when to come back. Pass a `RetryPolicy` and the client waits that long and sends the request again:
```swift title="API.swift"
let api = APIClient(
baseURL: URL(string: "https://api.example.com")!,
retry: APIClient.RetryPolicy(maximumAttempts: 3)
)
```
Only `GET`, `HEAD`, `OPTIONS`, `PUT` and `DELETE` are retried, so a `POST` that fails is handed back rather than sent twice. A network error is retried too, and a cancelled task never is. Without a `Retry-After` the client backs off from `initialDelay` (0.5 s), and a `Retry-After` longer than `maximumDelay` (30 s) hands the response back.
## Streams
A route whose response [streams](/docs/streaming) returns its `body` as an `AsyncThrowingStream`. Named events become an `Event` enum with one case per event, each carrying its decoded payload:
```swift title="AssistantView.swift"
let result = try await client.assistant.reply(.body(prompt: "hello"))
for try await event in result.body {
switch event {
case .delta(let delta):
text += delta.text
case .done(let done):
print(done.outputTokens)
}
}
```
A stream of one schema yields that type directly, a `text/*` stream yields one `String` per line, and a binary stream yields `Data` chunks. The status and headers are checked before the method returns, so a `400` throws its `Failure` as on any route. Cancelling the task that reads the stream closes the connection. A route that mixes a streamed status with another `2xx` is left out of the client, with a warning.
Pass a `ReconnectPolicy` to reconnect an event stream whose connection drops. The client sends the id of the last event it received as `Last-Event-ID`, and the loop reading `result.body` carries on. See [Resuming](/docs/streaming#resuming).
```swift title="API.swift"
let api = APIClient(
baseURL: URL(string: "https://api.example.com")!,
reconnect: APIClient.ReconnectPolicy()
)
```
## Keeping it current
`kizuna generate` writes every client the config declares, so the Swift one is never generated on its own:
```json title="package.json"
{
"scripts": {
"kizuna:generate": "kizuna generate",
"kizuna:check": "kizuna generate --check"
}
}
```
Run [`kizuna generate --check`](/docs/config#kizuna-generate---check) in CI, and a Swift client nobody regenerated fails the build instead of drifting from the routes it was generated from.
## Reference
- [`generateSwiftClient`](/docs/reference/generate-swift-client)
---
# TanStack Query
Source: /docs/clients/tanstack-query
---
title: TanStack Query
description: Build TanStack Query options from your routes, with query keys derived from your routes.
---
The TanStack Query client is new and still settling. Its API surface may change while v2 is in beta, so pin your version if you depend on it.
`@kizunajs/tanstack-query` turns a generated [fetch client](/docs/clients/fetch) into TanStack Query options. Query keys come from each route's own path, so invalidation is a method call.
It builds on `@tanstack/query-core`, the package every TanStack Query adapter shares, and returns options objects. You pass them to your own framework's hooks.
Install it alongside your framework's package. It reads everything it needs off the generated client, so your app installs nothing else from kizuna:
The examples here use React.
## Create the client
It takes the client `createClient` returns from the file [`fetchClient`](/docs/clients/fetch) generates:
```ts title="src/lib/api.ts"
import { KizunaTanstackQuery } from '@kizunajs/tanstack-query';
import { createClient } from './api-client.generated';
export const api = new KizunaTanstackQuery(
createClient({
baseUrl: 'http://localhost:3000',
})
);
```
Every method on the generated client carries its HTTP method and the statuses it answers, so the client is the only argument.
## Run a query
```tsx title="user-list.tsx"
import { useQuery } from '@tanstack/react-query';
import { api } from '@/lib/api';
const { data } = useQuery(
api.users.listUsers.queryOptions({
input: {
query: {
page: 1,
limit: 10,
},
},
staleTime: 60_000,
})
);
```
`input` is what you would pass the fetch client. Everything beside it is TanStack's own and passes through untouched, so `staleTime`, `retry`, `select`, `enabled`, `initialData`, and `placeholderData` behave as documented.
`data` is the route's response union, discriminated on `status`.
```tsx title="user-list.tsx"
if (data?.status === 200) {
console.log(data.body.name);
}
```
A route with a `body` or `query` schema also carries the automatic `400`, so narrow before reading the body.
## Run a mutation
```tsx title="create-user.tsx"
import { useMutation, useQueryClient } from '@tanstack/react-query';
const queryClient = useQueryClient();
const createUser = useMutation(
api.users.createUser.mutationOptions({
onSuccess: () =>
queryClient.invalidateQueries({
queryKey: api.users.key(),
}),
})
);
createUser.mutate({
body: {
name: 'Alice',
email: 'alice@example.com',
},
});
```
`mutate` takes the route's call arguments, or nothing when every argument is optional.
## Infinite queries
`input` is a function of the page parameter. Annotate that parameter, since it types `initialPageParam` and `getNextPageParam`.
```tsx title="user-search.tsx"
import { useInfiniteQuery } from '@tanstack/react-query';
const search = useInfiniteQuery(
api.users.searchUsers.infiniteOptions({
input: (cursor: number) => ({
query: {
q: 'alice',
limit: 10,
cursor,
},
}),
initialPageParam: 0,
getNextPageParam: (lastPage) => (lastPage.status === 200 ? lastPage.body.nextCursor : null),
})
);
```
## Keys and invalidation
Keys are `[segments, { input, type }]`, where the segments are the route's path through your routes. A group's key is a prefix of every key beneath it.
| Factory | Returns | Use it for |
| ------------------------ | ----------------------------------------- | ----------------------------------- |
| `key()` | `[segments]` | Invalidating a whole group or route |
| `queryKey({ input })` | `[segments, { input, type: 'query' }]` | `getQueryData`, `setQueryData` |
| `infiniteKey({ input })` | `[segments, { input, type: 'infinite' }]` | The route's infinite query |
| `mutationKey()` | `[segments]` | `useMutationState`, `isMutating` |
```tsx title="user-list.tsx"
queryClient.invalidateQueries({
queryKey: api.users.key(),
});
queryClient.setQueryData(
api.users.getUser.queryKey({
input: {
params: {
id: '1',
},
},
}),
(old) => old
);
```
`fetchOptions` is stripped from the key, because the `AbortSignal` it carries changes per attempt. The signal is forwarded to the client for you, and one you set yourself is left alone.
## Error handling
A status the route declares arrives as `data`. Anything else throws `UndeclaredResponseError`, so `retry`, `throwOnError`, and error boundaries work.
```tsx title="user-profile.tsx"
import { isUndeclaredResponseError } from '@kizunajs/tanstack-query';
const { data, error } = useQuery(
api.users.getUser.queryOptions({
input: {
params: {
id: 'usr_abc123',
},
},
})
);
if (data?.status === 404) {
return ;
}
if (error !== null && isUndeclaredResponseError(error)) {
console.error(error.status, error.body);
}
```
Declaring a status changes this: a route declaring `500` has said a 500 is an outcome, so it arrives as data and is not retried. Network failures reject on their own.
## Disabling a query
```tsx title="user-search.tsx"
import { skipToken } from '@tanstack/react-query';
const { data } = useQuery(
api.users.searchUsers.queryOptions({
input:
term === ''
? skipToken
: {
query: {
q: term,
limit: 10,
cursor: 0,
},
},
})
);
```
## Server rendering
Prefetch with a client built for the request, then dehydrate. Keys are derived the same way on both sides, so the cache hydrates.
```tsx title="app/page.tsx"
import { HydrationBoundary, QueryClient, dehydrate } from '@tanstack/react-query';
import { serverApi } from '@/lib/server-api';
export default async function Page() {
const queryClient = new QueryClient();
await queryClient.prefetchQuery(
serverApi.users.listUsers.queryOptions({
input: {
query: {
page: 1,
limit: 10,
},
},
})
);
return (
);
}
```
Responses are plain JSON, so the default `dehydrate` and `hydrate` need no custom serializer.
`serverApi` is built from a client whose `onRequest` forwards the incoming cookies. Client components use the browser one.
## Calling a route directly
`call` runs a route through the client without touching the cache.
```ts title="users.ts"
const result = await api.users.getUser.call({
params: {
id: 'usr_abc123',
},
});
```
## Streams
A route whose response [streams](/docs/streaming) offers `streamOptions` in place of `queryOptions`. It builds on TanStack's `experimental_streamedQuery`, so `data` is the list of messages received so far and grows as they arrive:
```tsx title="assistant.tsx"
const { data } = useQuery(
api.assistant.reply.streamOptions({
input: {
body: {
prompt,
},
},
})
);
const text = data?.flatMap((message) => (message.event === 'delta' ? [message.data.text] : [])).join('') ?? '';
```
`refetchMode` decides what a refetch does with the messages already held: `'reset'` clears them first and is the default, `'append'` adds to them, and `'replace'` swaps them in once the stream ends. A status other than the streamed one, the route's `400` say, rejects the query with `NonStreamResponseError`. The key is `streamKey({ input })`, typed `'stream'`, and there is no `queryOptions` or `infiniteOptions`, since a cache entry holding an open connection is wrong.
## Reference
- [`new KizunaTanstackQuery()`](/docs/reference/kizuna-tanstack-query)
- [`isUndeclaredResponseError`](/docs/reference/is-undeclared-response-error)
---
# Create an Adapter
Source: /docs/extend/create-adapter
---
title: Create an Adapter
description: Build and ship your own Kizuna adapter for any HTTP runtime using defineAdapter from kizunajs/adapter.
---
The adapter API is new and still settling. `defineAdapter` and the `AdapterResult` shape may change while v2 is in beta, so pin your version if you depend on them.
`kizunajs/adapter` exposes `defineAdapter` so third parties can build and ship their own adapters independently. Kizuna ships Express, Fastify, Hono, and Next.js.
Whether an adapter goes first-party comes down to adoption, not age. If a framework picks up real usage, we will very likely add it. What we will not take on is a framework a handful of people use, since we maintain everything we merge. The adapter API is public, so you can build and publish your own today.
## Overview
An adapter translates between a native HTTP runtime (Bun, Cloudflare Workers, Deno, etc.) and Kizuna's handler pipeline. You provide three things:
- `buildHandlerContext` builds the context object your handlers receive alongside validated inputs
- `respond` translates an `AdapterResult` to a native response
- `onError` (optional) intercepts unhandled handler errors
## `defineAdapter`
```ts title="adapter.ts"
import { defineAdapter, renderJsonResult, parseFetchBody, entriesToObject, headersToObject, type AdapterRequest } from 'kizunajs/adapter';
```
## Minimal example (fetch-based runtime)
```ts title="adapter.ts"
import {
defineAdapter,
renderJsonResult,
parseFetchBody,
entriesToObject,
headersToObject,
type AdapterRequest,
type Routes,
type Router,
} from 'kizunajs/adapter';
export interface HandlerContext {
request: Request;
}
const adapter = defineAdapter({
buildHandlerContext: (adapterRequest) => ({
request: adapterRequest.request,
}),
respond: (result, { request }) => {
if (result.kind === 'raw-response') return result.response as Response;
const rendered = renderJsonResult(result);
if (rendered.stream) {
return new Response(rendered.stream({ signal: request.signal }), {
status: rendered.status,
headers: rendered.headers,
});
}
return new Response(rendered.body === null || rendered.body === undefined ? null : JSON.stringify(rendered.body), {
status: rendered.status,
headers: rendered.headers,
});
},
});
export const handleRequest = (
request: Request,
routes: T,
router: Router,
options?: { basePath?: string }
): Promise => {
const url = new URL(request.url);
const adapterRequest: AdapterRequest = {
request,
method: request.method,
resolution: {
kind: 'core-match',
path: url.pathname,
},
query: entriesToObject(url.searchParams),
headers: headersToObject(request.headers),
readBody: (route) => parseFetchBody(request, route),
};
return adapter.handle({
routes,
router,
request: adapterRequest,
responseContext: {},
basePath: options?.basePath,
});
};
```
## `AdapterDefinition`
```ts
interface AdapterDefinition> {
buildHandlerContext: (request: AdapterRequest, context: ResponseContext) => HandlerContext | Promise;
respond: (result: AdapterResult, context: ResponseContext) => NativeResponse | Promise;
onError?: (error: unknown, request: AdapterRequest) => AdapterResult | void | Promise;
matcher?: RouteMatcher;
}
```
| Field | Description |
| --------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `buildHandlerContext` | Returns the context object each handler receives alongside `params`, `query`, `body`, `headers`. |
| `respond` | Translates an `AdapterResult` to a native response. Always handle `kind: 'raw-response'` first, as it carries a pre-built native response from `onError`. |
| `onError` | Called on unhandled handler errors. Return an `AdapterResult` to override the default 500, or return `void` to let it pass through. |
| `matcher` | Custom route matcher. Defaults to Kizuna's built-in path matcher. |
## `AdapterRequest`
```ts
interface AdapterRequest {
request: NativeRequest;
method: string;
resolution:
| { kind: 'core-match'; path: string } // Next-style: core matches the path
| { kind: 'pre-resolved'; routeKey: string; route: RouteDefinition; params: Record }; // Express-style: adapter already routed
query: unknown;
headers: unknown;
readBody: (route: RouteDefinition) => Promise | unknown;
}
```
Use `kind: 'core-match'` for catch-all routing (one handler handles all paths). Use `kind: 'pre-resolved'` for per-route registration (Express-style, where the framework has already matched the route).
## `AdapterResult`
`respond` receives one of these from the pipeline:
| `kind` | When |
| -------------------- | ---------------------------------------------------------------------------------- |
| `success` | Handler returned a valid response |
| `not-found` | No route matched the path |
| `method-not-allowed` | Path matched but method is not in the routes |
| `validation-failed` | params, query, headers, or body failed schema validation |
| `handler-error` | Handler threw an unhandled error |
| `raw-response` | `onError` returned an override, so cast `result.response` back to `NativeResponse` |
## Helpers
### `renderJsonResult`
Translates any `AdapterResult` (except `raw-response`) to `{ status, headers, body }` using Kizuna's defaults, such as 405 with an `Allow` header and validation errors as Problem Details (`detail` plus an `errors` array).
```ts
const rendered = renderJsonResult(result);
// rendered.status, rendered.headers, rendered.body
```
Pass the request's method as the fourth argument when your adapter writes the wire bytes itself: a `HEAD` request then keeps `GET`'s status and headers, gains a `Content-Length`, and loses the content ([RFC 9110 §9.3.2](https://www.rfc-editor.org/rfc/rfc9110#section-9.3.2)). Leave it unset when the framework discards `HEAD` content itself, as Express, Fastify, and Hono do.
```ts
const rendered = renderJsonResult(result, formatError, request, request.method);
```
A `success` result on a status declared with [`stream`](/docs/streaming) renders with `body` undefined and a `stream` function in its place. Check `stream` before `body`, hand it the signal that fires when the client goes away, and write the `ReadableStream` it returns. `encodeStreamBody(result, { signal })` does the same for an adapter that renders results itself.
### `parseFetchBody`
Content-type-aware body parsing for fetch-based runtimes (`Request` / `Response` API). Handles `application/json`, `multipart/form-data`, and `application/x-www-form-urlencoded`.
```ts
readBody: (route) => parseFetchBody(request, route),
```
### `entriesToObject`
Converts a `URLSearchParams` or `FormData` to an object. A repeated key, `?ids=1&ids=2`, becomes a list of every value.
```ts
query: entriesToObject(url.searchParams),
```
### `headersToObject`
Converts a `Headers` instance to `Record`.
```ts
headers: headersToObject(request.headers),
```
---
# Create a Client
Source: /docs/extend/create-client
---
title: Create a Client
description: Generate a typed client for a language Kizuna doesn't ship, and publish it for every Kizuna API.
---
The client API is new and still settling. `defineClient` and the context it walks may change while v2 is in beta, so pin your version if you depend on them.
Kizuna ships clients for TypeScript, Swift and Kotlin. For anything else, you write the client once with `defineClient`, and it works for every Kizuna API.
The Swift and Kotlin clients are written with it too.
Whether a client goes first-party comes down to demand, not age. If enough teams need a language, we will add it. What we will not take on is one a handful of people need, since we maintain everything we merge. The client API is public, so you can build and publish your own today.
## `defineClient`
A client is a program that walks the API's models and routes and returns the file it generates. Here's the shape of a Dart client:
```ts title="@example/kizuna-dart/src/index.ts"
import { z } from 'zod';
import { defineClient } from 'kizunajs/generator';
export const dartClient = defineClient({
target: 'dart',
options: z.object({
library: z.string().default('api'),
}),
generate: ({ options }) => {
const writer = new DartWriter(options.library);
return {
processModel: (model) => writer.model(model),
processRoute: (context) => writer.method(context),
finalize: () => writer.render(),
};
},
});
```
| Field | What it is |
| ---------- | ---------------------------------------------------------------------------------- |
| `target` | The language this client generates |
| `options` | A Zod schema for what the app passes in, beside `output` |
| `generate` | Returns the walk: `processModel` and `processRoute` for each item, then `finalize` |
`DartWriter` stands for your own code that turns a model or a route into Dart. `finalize` returns the file as one string. Kizuna writes it to `output`, and `kizuna generate --check` compares it byte for byte.
## Installing it
Apps name it under `clients` like any client. `output` comes with every client, so your `options` only hold what's particular to yours:
```ts title="kizuna.config.ts"
import { dartClient } from '@example/kizuna-dart';
clients: [
dartClient({
output: '../app/lib/api.dart',
library: 'api',
}),
],
```
Kizuna skips [hidden](/docs/routes#hidden-routes) routes, plugin routes included, so one never reaches your `processRoute`.
## The walk
### `processModel`
Called once for every [`Kizuna.model`](/docs/reference/kizuna-model) the client's routes use:
| Property | Type | Description |
| ------------- | --------------------- | ------------------------------------------ |
| `name` | `string` | The model's title, e.g. `User` |
| `schema` | `ZodType` | The schema to generate a type from |
| `description` | `string \| undefined` | The model's description, for a doc comment |
### `processRoute`
Called once for every route in this client:
| Property | Type | Description |
| -------------------- | --------------------- | --------------------------------------------------------------------------------------- |
| `routeKey` | `string` | Dot-separated key path, e.g. `users.getUser` |
| `route` | `RouteDefinition` | The full route definition |
| `routeGroups` | `string[]` | Every group the route is filed under, as dotted paths: its own first, then its `groups` |
| `deprecated` | `boolean` | `true` when the route is deprecated |
| `deprecationMessage` | `string \| undefined` | The route's `deprecated` string, or the object form's `message` |
### `finalize`
Called once, after the walk, and returns the file.
## What a client does at runtime
The generated code is what app developers live with, so match what the first-party clients do:
- **Every declared status is a typed result**, so a `404` the route declares comes back as data the app can switch on. Undeclared statuses are errors.
- **Problem details decode** into a typed error body, including validation issues on a `400`.
- **Request context headers** are set once on the client and sent on every call.
- **Request and response middleware**, so an app can add auth headers and log responses, the way Swift's `requestMiddleware` and Kotlin's `requestInterceptor` do.
- **Route groups become groups**, like `api.users.getUser(...)`.
## Deprecation
Route deprecation arrives on the context. Fields declare theirs in Zod metadata, read with `readDeprecation`:
```ts
import { readDeprecation } from 'kizunajs/generator';
const deprecation = readDeprecation(fieldSchema);
if (deprecation) {
// deprecation.message is the string form's message, or undefined
}
```
See [Deprecations](/docs/deprecations) for the authoring side.
## Examples
A schema's declared example values read with `readMetaExamples`. It takes `example` first and then `examples`, each of which holds one value or a list:
```ts
import { readMetaExamples } from 'kizunajs/generator';
const [example] = readMetaExamples(fieldSchema);
```
## What `kizuna generate` expects
- **The output is deterministic.** `--check` re-renders and compares byte for byte, so a timestamp or an unsorted map in the output fails every CI run after the first.
- **One client, one file.** An app wanting two files installs your client twice, with two names.
- **The walk is synchronous.** Read whatever you need before you return from `generate`.
- **`output` resolves against the config's directory**, not the shell's, so `../app/lib/api.dart` writes into a sibling project wherever the command runs.
## Something other than a client
For a file that isn't a client, like a route manifest or a document, write a [generator](/docs/extend/create-generator). That's how the OpenAPI document is written.
---
# Create a Generator
Source: /docs/extend/create-generator
---
title: Create a Generator
description: Generate documents and other files from your routes, like the OpenAPI document, and keep them in step on every kizuna generate.
---
The generator API is new and still settling. `defineGenerator` and the context it walks may change while v2 is in beta, so pin your version if you depend on them.
A generator walks your routes and writes a file from them: a document, a manifest, a list for a gateway. The OpenAPI document is one. For code your apps call, write a [client](/docs/extend/create-client) instead.
## `defineGenerator`
A route manifest for an API gateway, listing every route it should forward:
```ts title="@example/kizuna-gateway/src/index.ts"
import { z } from 'zod';
import { defineGenerator } from 'kizunajs/generator';
export const gatewayManifest = defineGenerator({
options: z.object({
includeDeprecated: z.boolean().default(false),
}),
generate: ({ options }) => {
const entries: Array<{ method: string; path: string }> = [];
return {
processRoute: ({ route, deprecated }) => {
if (deprecated && !options.includeDeprecated) {
return;
}
entries.push({
method: route.method,
path: route.path,
});
},
finalize: () => JSON.stringify(entries, null, 4),
};
},
});
```
| Field | What it is |
| ---------- | ---------------------------------------------------------------------------------- |
| `options` | A Zod schema for what the plugin passes in, beside `output` |
| `generate` | Returns the walk: `processModel` and `processRoute` for each item, then `finalize` |
`finalize` returns the file as one string. Kizuna writes it to `output`, and `kizuna generate --check` compares it byte for byte.
## Installing it
A plugin brings generators from its `setup`, the same way it brings routes and jobs. A package that only generates a file is a plugin with nothing else in it:
```ts title="@example/kizuna-gateway/src/plugin.ts"
import { z } from 'zod';
import { definePlugin } from 'kizunajs/plugin';
import { gatewayManifest } from './generator';
export const gatewayPlugin = definePlugin({
slug: 'gateway',
options: z.object({
output: z.string(),
}),
setup: ({ options }) => ({
generators: [
gatewayManifest({
output: options.output,
}),
],
}),
});
```
```ts title="kizuna.config.ts"
plugins: [
gatewayPlugin({
output: './gateway/routes.json',
}),
],
```
`openApiPlugin` works the same way: its `output` option becomes a generator it returns, beside the routes that serve the document.
## The walk
`processRoute` is called once for every route the server serves, plugin routes included. `processModel` is called once for every named [model](/docs/reference/kizuna-model), and is optional.
| Property | Type | Description |
| -------------------- | ----------------------- | --------------------------------------------------------------------------------------- |
| `routeKey` | `string` | Dot-separated key path, e.g. `users.getUser` |
| `route` | `RouteDefinition` | The full route definition |
| `routeGroups` | `string[]` | Every group the route is filed under, as dotted paths: its own first, then its `groups` |
| `hidden` | `boolean` | `true` when the route is [hidden](/docs/routes#hidden-routes) |
| `deprecated` | `boolean` | `true` when the route is deprecated |
| `deprecationMessage` | `string \| undefined` | The route's `deprecated` string, or the object form's `message` |
| `plugin` | `{ slug } \| undefined` | The plugin whose route this is, under the slug the app installed it at |
A generator sees every served route and decides what to include. The OpenAPI document leaves hidden routes out unless it's told otherwise.
## Deprecation
Route deprecation arrives on the context. Fields declare theirs in Zod metadata, read with `readDeprecation`:
```ts
import { readDeprecation } from 'kizunajs/generator';
const deprecation = readDeprecation(fieldSchema);
if (deprecation) {
// deprecation.message is the string form's message, or undefined
}
```
See [Deprecations](/docs/deprecations) for the authoring side.
## Examples
A schema's declared example values read with `readMetaExamples`. It takes `example` first and then `examples`, each of which holds one value or a list:
```ts
import { readMetaExamples } from 'kizunajs/generator';
const [example] = readMetaExamples(fieldSchema);
```
## What `kizuna generate` expects
- **The output is deterministic.** `--check` re-renders and compares byte for byte, so a timestamp or an unsorted map in the output fails every CI run after the first.
- **One generator, one file.** For two files, install it twice with two outputs.
- **The walk is synchronous.** Read whatever you need before you return from `generate`.
- **`output` resolves against the config's directory**, not the shell's, so `./gateway/routes.json` lands in the same place wherever the command runs.
---
# Create a Job Transport
Source: /docs/extend/create-job-transport
---
title: Create a Job Transport
description: Connect any queue or scheduler to your Kizuna jobs by implementing one function.
---
The transport API is new and still settling. The message shape and what a transport must implement may change while v2 is in beta, so pin your version if you depend on them.
A transport carries a job from `jobs.indexUser.queue(...)` to the process that runs it.
Kizuna ships none, so you write one against the queue you run.
```ts title="job-transport.ts"
import { defineJobTransport } from 'kizunajs';
export const myQueue = defineJobTransport({
name: 'my-queue',
supports: {
retry: true,
dedupe: true,
},
dispatch: async (message) => {
await queue.add(message.job, message.input);
},
});
```
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
transport: myQueue,
},
});
```
`dispatch` is the only method you must implement.
## Two shapes
**Push** systems deliver by calling a URL: QStash, Cloud Tasks, SQS to Lambda. Point them at the run endpoint, `POST /jobs/run`, with `{ job, input }` as the body. Kizuna already guards and validates it, so these need only `dispatch`.
**Pull** systems store work and a worker drains it: BullMQ, pg-boss, a table in your own database. These also implement `start`.
## `dispatch`
```ts
dispatch: (message: JobMessage) => Promise | void;
```
| Field | What it is |
| ----------- | ------------------------------------------------------------------- |
| `job` | The job's dotted key, e.g. `billing.reconcileInvoices`. |
| `input` | The validated input, or `undefined`. JSON-safe. |
| `runAt` | Hold until then. Ignore unless you declare `supports.runAt`. |
| `dedupeKey` | Deliver at most one message with this key. Needs `supports.dedupe`. |
| `retry` | Attempts the job declared. Backoff is yours. |
Resolve once the queue has accepted the message, which is before the job runs. Reject when it could not be handed over at all. That surfaces at the `queue` call site, wrapped in a `JobDispatchError` naming your transport and the job.
## `start`
```ts
start?: (context: JobWorkerContext) => Promise;
```
You get every job your API declares, so you can subscribe by name, and a `run` that invokes one through the same handler a route would reach.
```ts title="job-transport.ts"
start: async ({ jobs, run }) => {
for (const job of jobs) {
await queue.process(job.job, async (stored) => {
await run({
...job,
input: stored.data,
});
});
}
return {
stop: () => queue.close(),
};
};
```
Call `run` once per message, and let its rejection propagate, which is how your queue learns to retry. A swallowed rejection reads as a successful queue.
## `register`
```ts
register?: (schedules: readonly ScheduledJob[]) => Promise | void;
```
For a system with a scheduler of its own. `startJobs` then hands the schedules across instead of ticking them, and you own missed occurrences. Throw on a `timezone` you cannot express rather than dropping it.
```ts title="job-transport.ts"
register: async (schedules) => {
for (const schedule of schedules) {
await queue.schedule(schedule.job, schedule.cron, {
tz: schedule.timezone,
});
}
};
```
## `supports`
A message's `runAt`, `dedupeKey` and `retry` are honoured only where the transport declares support, under `runAt`, `dedupe` and `retry`. Say which you honour and Kizuna warns when a job asks for one you drop.
`dedupe` is what makes `startJobs` safe on more than one instance: every replica ticking 05:00 produces the same `dedupeKey`.
## Example: QStash
[QStash](https://upstash.com/docs/qstash) is a push transport. You publish to it with a destination URL, and it delivers your body to that URL verbatim, retrying on failure and holding messages until a delay elapses. It has a scheduler of its own, so it honours everything and implements `register` too.
Every message goes to the same URL, the run endpoint, and names its job in the body.
```ts title="qstash.ts"
import { defineJobTransport, type JobMessage } from 'kizunajs';
interface QstashOptions {
token: string;
baseUrl: string;
/**
* The secret the jobs' identity checks, forwarded so a delivery from QStash
* authenticates the same way a platform cron does.
*/
schedulerSecret: string;
}
const runEndpoint = (options: QstashOptions): string => `${options.baseUrl}/jobs/run`;
const delivery = (options: QstashOptions, retry?: number): Record => ({
authorization: `Bearer ${options.token}`,
'content-type': 'application/json',
// Arrives at the run endpoint as `Authorization`.
'upstash-forward-authorization': `Bearer ${options.schedulerSecret}`,
// kizuna counts attempts, QStash counts retries after the first. Always
// sent: QStash defaults to 3, and a job asking for 1 should not get 3.
'upstash-retries': String((retry ?? 1) - 1),
});
export const qstash = (options: QstashOptions) =>
defineJobTransport({
name: 'qstash',
supports: {
retry: true,
dedupe: true,
runAt: true,
},
dispatch: async (message) => {
const response = await fetch(`https://qstash.upstash.io/v2/publish/${runEndpoint(options)}`, {
method: 'POST',
headers: {
...delivery(options, message.retry),
...(message.dedupeKey ? { 'upstash-deduplication-id': message.dedupeKey } : {}),
...(message.runAt ? { 'upstash-not-before': String(Math.floor(message.runAt.getTime() / 1000)) } : {}),
},
body: JSON.stringify({
job: message.job,
input: message.input,
}),
});
if (!response.ok) throw new Error(`QStash answered ${response.status}: ${await response.text()}`);
},
register: async (schedules) => {
for (const schedule of schedules) {
const response = await fetch(`https://qstash.upstash.io/v2/schedules/${runEndpoint(options)}`, {
method: 'POST',
headers: {
...delivery(options),
// A dotted job key is already a legal schedule id, and reusing
// it updates the schedule in place rather than adding a second.
'upstash-schedule-id': schedule.job,
'upstash-cron': schedule.timezone ? `CRON_TZ=${schedule.timezone} ${schedule.cron}` : schedule.cron,
},
body: JSON.stringify({
job: schedule.job,
}),
});
if (!response.ok) throw new Error(`QStash refused the schedule for "${schedule.job}": ${response.status}`);
}
},
});
```
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: nextAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
transport: qstash({
token: process.env.QSTASH_TOKEN,
baseUrl: 'https://api.example.com',
schedulerSecret: process.env.CRON_SECRET,
}),
},
});
```
Two things that are easy to get wrong here, and both look like a delivered job that never ran:
- **`upstash-retries` is off by one.** Kizuna's `retry` is a number of attempts; QStash's header is retries _after_ the first.
- **The body is the message, not the input.** QStash delivers what you publish verbatim, and the run endpoint reads `job` from it. Publishing the bare input leaves it with nothing to run.
`register` is worth implementing for QStash in particular: `CRON_TZ=` expresses a time zone, which platform cron cannot, since Vercel and GitHub read every expression as UTC. Note that a job you delete leaves its schedule behind, so prune what your config no longer declares.
Check the [QStash docs](https://upstash.com/docs/qstash) for the current header set before relying on the names above.
### Authenticating what QStash sends back
QStash calls the run endpoint, so the jobs' identity guards it. Forwarding the secret, as above, is the simplest thing that works: it arrives as `Authorization` and an ordinary bearer guard reads it, the same trust model as Vercel Cron's `CRON_SECRET`.
```ts title="src/identities.ts"
export const scheduler = k.identity.bearer({}).guard(({ bearer, deny }) =>
bearer?.token === process.env.CRON_SECRET
? undefined
: deny({
status: 401,
body: {
detail: 'Unauthorized',
},
})
);
```
A guard cannot verify QStash's `Upstash-Signature`. The signature covers the raw body, and the request pipeline reads the body before
guards run, so by then it is parsed on Express and the stream is consumed on Hono and Next. Verify it ahead of Kizuna instead: framework
middleware on the run endpoint, or `express.json({verify})` to keep the raw buffer for a guard to read.
## Example: BullMQ
[BullMQ](https://docs.bullmq.io/) is a pull transport, so it implements all three: `dispatch` adds to a Redis queue, `start` drains it, and `register` uses BullMQ's own repeatable jobs.
```ts title="bullmq.ts"
import { Queue, Worker, type ConnectionOptions } from 'bullmq';
import { defineJobTransport } from 'kizunajs';
export const bullmq = (connection: ConnectionOptions, queueName = 'jobs') => {
const queue = new Queue(queueName, { connection });
return defineJobTransport({
name: 'bullmq',
supports: {
retry: true,
dedupe: true,
runAt: true,
},
dispatch: async (message) => {
await queue.add(message.job, message.input, {
delay: message.runAt ? Math.max(message.runAt.getTime() - Date.now(), 0) : undefined,
jobId: message.dedupeKey,
attempts: message.retry,
});
},
start: async ({ jobs, run }) => {
const byName = new Map(jobs.map((job) => [job.job, job]));
const worker = new Worker(
queueName,
async (stored) => {
const job = byName.get(stored.name);
if (!job) throw new Error(`No job named "${stored.name}" on this API.`);
await run({ ...job, input: stored.data });
},
{ connection }
);
return {
stop: () => worker.close(),
};
},
register: async (schedules) => {
for (const schedule of schedules) {
await queue.add(
schedule.job,
{},
{
repeat: {
pattern: schedule.cron,
tz: schedule.timezone,
},
}
);
}
},
});
};
```
`start` is called by `startJobWorker`, not on its own. `startJobWorker` does, wherever you want the work done, whether that is the same process as the API or its own:
```ts title="worker.ts"
import { startJobWorker } from 'kizunajs/jobs';
const worker = await startJobWorker(api);
process.on('SIGTERM', () => void worker?.stop());
```
`jobId` is how BullMQ deduplicates, so `dedupeKey` maps onto it, but only while the job exists. Once it completes and is removed the id is free again, so `supports.dedupe` here is weaker than "never twice". `register` has the same edge in reverse, since changing a cron leaves the old repeatable job behind. Check the [BullMQ docs](https://docs.bullmq.io/) for the repeatable-job API in the version you run.
## What you can assume
- `input` is validated against the job's schema before you see it, and again when it runs, so a message that sat in your queue across a deploy is checked against the schema it lands on.
- `job` is unique and stable, so it is safe as a queue name or routing key.
## What you cannot
- `input` survives only as JSON. A `Date` does not come back a `Date`.
- Delivery is at least once. Kizuna does not try to make it exactly once.
---
# Create a Plugin
Source: /docs/extend/create-plugin
---
title: Create a Plugin
description: Package the code you reuse across projects, like email or push notifications, so any Kizuna app can install it.
---
The plugin API is new and still settling. `definePlugin` and the shape of what it returns may change while v2 is in beta, so pin your version if you depend on them.
Once you build more than one project with Kizuna, a lot of the code repeats: sending email, push notifications, checking which tenant a request belongs to. A plugin packages that code once, so every project can install it.
A plugin hands your route and job handlers functions to call, and can bring routes of its own.
## Your first plugin
### Describe what it sends
Each plugin gets its own folder. Start with the shape of an email:
```ts title="src/plugins/email/types.ts"
import { z } from 'zod';
export const EmailSchema = z.object({
to: z.email(),
subject: z.string().min(1),
html: z.string(),
});
export type Email = z.infer;
```
### Write it
```ts title="src/plugins/email/index.ts"
import { z } from 'zod';
import { Resend } from 'resend';
import { definePlugin } from 'kizunajs/plugin';
import type { Email } from './types';
export const emailPlugin = definePlugin({
slug: 'email',
options: z.object({
apiKey: z.string(),
from: z.string(),
}),
setup: ({ options }) => {
const resend = new Resend(options.apiKey);
return {
exports: {
send: (email: Email) =>
resend.emails.send({
from: options.from,
...email,
}),
},
};
},
});
```
### Install it
```ts title="kizuna.config.ts"
import { emailPlugin } from './src/plugins/email';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
emailPlugin({
apiKey: process.env.RESEND_API_KEY,
from: 'Acme ',
}),
],
});
```
### Use it
Every route handler and every job handler receives it under `plugins`, typed:
```ts title="src/routes/users.ts"
createUser: k
.route({
method: 'POST',
path: '/users',
body: CreateUserSchema,
responses: {
201: UserSchema,
},
})
.handler(async ({ body, plugins }) => {
const user = await db.users.create(body);
await plugins.email.send({
to: user.email,
subject: 'Welcome',
html: `
Welcome, ${user.name}.
`,
});
return {
status: 201,
body: user,
};
}),
```
## `definePlugin`
| Field | What it gives the plugin |
| --------- | ------------------------------------------------------------- |
| `slug` | What handlers reach it under: `plugins.email` |
| `options` | A Zod schema for what the app passes in |
| `setup` | Builds the plugin from its options and returns what it brings |
`setup` returns any of these:
| Key | What it is |
| ------------ | --------------------------------------------------------------------------------------------- |
| `exports` | Functions every route and job handler reaches at `plugins.` |
| `routes` | Routes an outside system calls, like a webhook |
| `generators` | Files `kizuna generate` writes, built with [`defineGenerator`](/docs/extend/create-generator) |
Everything `setup` returns shares what it creates, so the Resend client is made once and used by all of it.
`setup` runs when the config assembles, which includes `kizuna generate`. So it creates clients, and leaves connections and file reads to the handlers, the same as [route modules](/docs/routes#nothing-runs-at-import).
## Options
Every plugin's options are validated. `options` has to be a Zod schema, so what the plugin reads is always what it declared, and you never write checks of your own. The app's options are validated once, when the config assembles, and typed from the schema everywhere the plugin reads them.
```ts title="src/plugins/email/index.ts"
options: z.object({
apiKey: z.string(),
from: z.string(),
replyTo: z.email().optional(),
}),
```
A misconfigured plugin stops the app from starting, and the error names the plugin and the field. Secrets come in through options, so a missing environment variable is caught the same way:
```text
[kizuna] Plugin 'email' has invalid options: apiKey is required
```
### A type from an SDK
An SDK's options usually come as a plain TypeScript type. Take it with `z.custom`, and the field is typed as the SDK declares it:
```ts title="src/plugins/email/index.ts"
import { Resend, type ResendOptions } from 'resend';
export const emailPlugin = definePlugin({
slug: 'email',
options: z.object({
apiKey: z.string(),
from: z.string(),
resend: z.custom().optional(),
}),
setup: ({ options }) => {
const resend = new Resend(options.apiKey, options.resend);
// ...
},
});
```
`z.custom` checks nothing unless you pass it a check, so the SDK validates that field when it reads it.
## Exports
Every handler reaches a plugin's `exports` at `plugins.`. Take one object with named fields, like every other kizuna call:
```ts
await plugins.email.send({
to: user.email,
subject: 'Welcome',
html: `
Welcome, ${user.name}.
`,
});
```
### Your routes and jobs call the exports
A route your apps call is part of your API, so it lives with your routes and calls the plugin. A contact form:
```ts title="src/routes/contact.ts"
import { EmailSchema } from '@/plugins/email/types';
export const contact = k.routes.contact({
send: k
.route({
method: 'POST',
path: '/contact',
auth: false,
body: EmailSchema.pick({
subject: true,
html: true,
}),
responses: {
204: z.void(),
},
})
.handler(async ({ body, plugins }) => {
await plugins.email.send({
to: 'support@example.com',
...body,
});
return {
status: 204,
};
}),
});
```
The path, the body, `auth` and which clients get the route are yours to choose, and the plugin needs no option for any of it.
The same goes for background work. To send with retries, queue a job of your own that calls the plugin, so you decide what's queued, when and how often it retries:
```ts title="src/jobs.ts"
sendWelcomeEmail: k
.job({
input: z.object({
userId: z.string(),
}),
retry: 5,
})
.handler(async ({ input, plugins }) => {
const user = await db.users.find(input.userId);
await plugins.email.send({
to: user.email,
subject: 'Welcome',
html: `
Welcome, ${user.name}.
`,
});
}),
```
## Routes
A plugin brings routes of its own only when something outside your apps calls them, like a service's webhooks. Declare them with `route` from `kizunajs/plugin`, the plugin's `k.route`, and return them from `setup`. They run through the same pipeline as yours, with the same validation, guards and problem details.
- **Every plugin route is [hidden](/docs/routes#hidden-routes).** It's served, and stays out of your generated clients, the OpenAPI document and MCP, since no app calls it.
- **`auth: false`** for a caller with no credentials. A route that needs a caller takes `auth` as an option, because the plugin never knows your identities: `RouteAuthSchema` from `kizunajs/plugin` accepts exactly what a route's [`auth`](/docs/reference/k-route#auth) does.
- **`path`** as an option on a plugin with one route, so an app can move it when it clashes with one of its own. `RoutePathSchema` from `kizunajs/plugin` accepts a path that starts with `/`.
- **`rawBody: true`** on a webhook route to [check the sender's signature](/docs/routes#verifying-signed-requests).
If a plugin claims a path your routes already use, `defineConfig` throws and names both.
### Base path
A plugin with several routes declares a `basePath`, and writes each route's `path` relative to it. A route at `/` serves the base path itself:
```ts title="src/plugins/webhooks/index.ts"
export const webhooksPlugin = definePlugin({
slug: 'webhooks',
basePath: '/webhooks',
setup: () => ({
routes: {
receive: route({
method: 'POST',
path: '/',
auth: false,
responses: {
204: z.void(),
},
}).handler(receiveEvent),
status: route({
method: 'GET',
path: '/status',
auth: false,
responses: {
200: StatusSchema,
},
}).handler(reportStatus),
},
}),
});
```
That serves `/webhooks` and `/webhooks/status`. When those clash with your own routes, move them all at install:
```ts title="kizuna.config.ts"
plugins: [
webhooksPlugin({
basePath: '/integrations',
}),
],
```
Only a plugin that declares a `basePath` takes one at install.
### Running the app's own functions
A plugin whose route runs code the app writes, like a webhook's event functions, takes those functions as an option and hands them the app's jobs and plugins. `ApiContext` from `kizunajs/plugin` types them from the app's `Config`, so a helper that takes `Config` as a type parameter gives the app typed `jobs` and `plugins` in a file of its own:
```ts title="src/plugins/webhooks/events.ts"
import type { ApiContext } from 'kizunajs/plugin';
export type WebhookEventHandler = (context: ApiContext & { event: WebhookEvent }) => Promise | void;
export const defineWebhookEvents = (handlers: Record>) => handlers;
```
The route's handler passes `jobs` and `plugins` on from its own arguments. [`@kizunajs/resend`](/docs/resend) does this for Resend's events.
## Slugs
A plugin's `slug` is what handlers reach it under. The plugin picks one, and the app can change it. When two plugins want the same slug, `defineConfig` throws, names both, and tells you to rename one:
```ts title="kizuna.config.ts"
plugins: [
pushNotificationsPlugin(),
webPushPlugin({
slug: 'webPush',
}),
],
```
Handlers then use `plugins.push` and `plugins.webPush`. A plugin that needs several configurations takes them in its own options.
## Publishing
A published plugin is the same module in its own package, with its reach declared:
```json title="package.json"
{
"exports": {
".": "./dist/index.mjs"
},
"kizuna": {
"entries": {
".": "server"
}
}
}
```
A plugin is always `server`, since it runs where the config does.
## Reference
- [Config](/docs/config) for installing plugins
- [`mcpPlugin`](/docs/reference/mcp-plugin) and [`openApiPlugin`](/docs/reference/openapi-plugin) for worked examples
- [Create an Adapter](/docs/extend/create-adapter) if the runtime itself is missing
---
# Wrap the Fetch Client
Source: /docs/extend/wrap-fetch-client
---
title: Wrap the Fetch Client
description: Build and ship your own TypeScript client wrapper using the types and the route metadata a generated fetch client carries.
---
The wrapper surface is new and still settling. The shape of `'~route'` and the types the generated file exports may change while v2 is in beta, so pin your version if you depend on them.
A wrapper builds on the [fetch client](/docs/clients/fetch) your app already has, the one `kizuna generate` writes. Wrap it to build hooks, an SDK layer, or any other integration. `@kizunajs/tanstack-query` is one of these, and it takes the client and nothing else.
Whether a client goes first-party comes down to demand, not age. If it is something most teams on Kizuna would reach for, we will add it. What we will not take on is one a handful of people need, since we maintain everything we merge. The client API is public, so you can build and publish your own today.
## Pattern
```ts title="src/lib/my-client.ts"
import { apiClient } from './api-client';
export function createMyClient() {
return {
getUser: (id: string) =>
apiClient.users.getUser({
params: {
id,
},
}),
createUser: (data: Parameters[0]['body']) =>
apiClient.users.createUser({
body: data,
}),
};
}
```
## Reading the route off a method
A wrapper that treats routes generically, rather than naming each one, needs to know what each method answers: its method, its path, which statuses it declares. Every client method carries its route under `'~route'`:
```ts
const route = apiClient.users.getUser['~route'];
route.method; // 'GET'
route.path; // '/users/:id'
route.streams; // false
Object.keys(route.responses); // ['200', '404']
```
This is what lets a wrapper take the client alone. A `GET` gets query semantics, anything else gets mutation semantics, and the declared statuses say which responses are data. `responses` lists every status the method's `Result` type does, the automatic `400`, `401` and `403` included. A group has no `'~route'`, so it is easy to skip while walking the client.
The property is not enumerable, so it stays out of `Object.keys` and spreads.
## Types
The generated file exports what a wrapper types itself with:
| Type | Description |
| ----------------------------------------------------- | --------------------------------------------------------------------------------- |
| `Client` | The client `createClient` returns |
| `ClientConfig` | What `createClient` takes |
| `ClientMethod` | One method, with the HTTP method and whether it streams carried on its `'~route'` |
| `API.UsersGetUser.Params`, `Query`, `Body`, `Headers` | What one route's method accepts |
| `API.UsersGetUser.Result` | The discriminated union one route's method resolves to |
A wrapper published as a package cannot import a file each app generates, so it reads a method's types off the method itself. `ClientMethod` is matched by shape, so a package can declare its own copy and infer `Method`, `Streams`, `Args` and `Result` from any generated client:
```ts
type ClientMethod = ({} extends Args
? (args?: Args) => Promise
: (args: Args) => Promise) & {
readonly '~route': {
readonly method: Method;
readonly streams: Streams;
};
};
```
---
# Migrating an existing API
Source: /docs/migration/existing-api
---
title: Migrating an existing API
description: Move an existing API onto Kizuna without breaking deployed clients, using the additive pattern and the escape hatch for the rest.
---
You have an API in production with clients you cannot redeploy. Moving it onto Kizuna is mostly mechanical: routes, schemas, and success responses port across unchanged, and your URLs and status codes stay exactly where they are.
Errors are the one place Kizuna has an opinion. Every error response takes the [RFC 9457 Problem Details](/docs/reference/problem-details-schema) shape, `type`, `title`, `status`, `detail`, plus any extra fields you add. Whether your deployed clients notice depends on what your errors look like today, which is the first thing to work out.
## Do I need a new API version?
Usually not. Your endpoints and status codes never change, so the only question is whether a deployed client can still read the error body it gets back. Find your errors in the left column and do what the right one says.
| If your errors today are | You need to |
| ------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------- |
| A JSON object, like `{ message, code }` | Nothing. Keep every field as an [extension member](#the-additive-pattern-keep-your-old-fields) and clients read the same keys they read now |
| A bare string, or a wrapper like `{ ok, error }` | Add [`formatError`](#formaterror-the-escape-hatch), because the body shape changes and extension members cannot rewrite it |
| Read by a client that asserts `application/json` | Add [`formatError`](#formaterror-the-escape-hatch) to stamp the old content type, since errors now go out as `application/problem+json` |
All three keep your existing URLs and status codes, so none of them needs a `/v2`. Save a new version for an API that is incompatible for its own reasons.
## Success responses are unchanged
Only error statuses (`>= 400`) are constrained. A `2xx`/`3xx` response can be any shape, so port those exactly as they are. Everything below is about errors.
## Errors are Problem Details
A route that declares an error with a bespoke shape no longer typechecks, and the handler's error body resolves to `never`:
```ts
responses: {
200: UserSchema,
404: z.object({ message: z.string() }), // compile error at the handler
}
```
Use [`ProblemDetailsSchema`](/docs/reference/problem-details-schema). The handler supplies `detail`; `type`/`title`/`status` are filled in for you:
```ts title="src/routes/users.ts"
import { ProblemDetailsSchema } from 'kizunajs/schemas';
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
}
```
## The additive pattern: keep your old fields
This is the path for nearly every migration. If your errors carry fields beyond a message, such as an application code or a request ID, keep them as RFC 9457 **extension members** with `.extend()`:
```ts title="src/routes/users.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
responses: {
404: ProblemDetailsSchema.extend({
errorCode: z.string(),
requestId: z.string(),
}),
}
```
```ts title="src/routes/users.ts"
return throwError({
status: 404,
body: {
detail: 'No such user',
errorCode: 'USER_NOT_FOUND',
requestId: 'abc123',
},
});
```
The body is now valid Problem Details **and** still has `errorCode` / `requestId` as top-level keys:
```json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "No such user",
"errorCode": "USER_NOT_FOUND",
"requestId": "abc123"
}
```
A client reading `errorCode` keeps working untouched, and a new client reads the standard fields off the same body. When every client has moved to the standard fields, drop the extras.
## The content type
Errors go out as `application/problem+json`; success stays `application/json`. That is still JSON, so a client calling `response.json()` parses it identically. Only a client that strictly asserts `Content-Type: application/json` notices.
## When extension members aren't enough
Extension members only add top-level fields. They cannot nest, rename, or replace the body, so they can't reproduce a wrapper like `{ ok: false, error: {...} }` or an error body that is a bare string. For that, and for the content type above, use `formatError`.
## `formatError`, the escape hatch
`formatError` decides the bytes for an error response. Use it to stamp a different content type or reshape the body into a legacy structure. Because it receives the request, you can serve old and new clients at once. Your routes, types, and OpenAPI spec stay pure Problem Details; only the wire output changes.
Say old clients expect this body, as `application/json`:
```json
{
"ok": false,
"error": {
"code": 404,
"message": "No such user",
"errorCode": "USER_NOT_FOUND"
}
}
```
Branch on whatever signal tells your clients apart, such as a version header, a build header, or `Accept`, and reshape to the legacy body only for the old ones:
```ts title="src/index.ts"
api.mount(app, {
// `problem` is the full Problem Details object (envelope + extension members).
formatError: (problem, { request }) => {
// new clients opt in via a signal you control, here a version header
if (request.headers.get('x-api-version') === '2') {
return {
contentType: 'application/problem+json',
body: problem,
};
}
// old clients keep their existing shape
return {
contentType: 'application/json',
body: {
ok: false,
error: {
code: problem.status,
message: problem.detail,
errorCode: problem.errorCode, // extension member, carried through
},
},
};
},
});
```
This applies to every error: the built-in 404/405/415, validation 400s, guard denials, and anything your handlers pass to `throwError`. Every first-party adapter takes it. Remove the branch once the old clients are gone.
Doing a coordinated cutover instead? Skip the branch, always return the legacy shape, and delete `formatError` on flip day.
## Forwarding errors your handlers already throw
If your handlers throw domain errors (or you rely on framework error middleware), map them into Problem Details at the boundary instead of rewriting each handler. On Next.js that's the `onError` option; on Express, Fastify, and Hono, build the response with [`problemDetails()`](/docs/reference/problem-details-schema) in the framework's error handler.
```ts title="kizuna.config.ts"
import { problemDetails } from 'kizunajs';
export default defineConfig({
adapter: nextAdapter({
onError: (caught) => {
if (caught instanceof NotFoundError) {
return NextResponse.json(problemDetails(404, caught.message), {
status: 404,
headers: {
'content-type': 'application/problem+json',
},
});
}
// return nothing to fall through to the default 500
},
}),
routes,
});
```
## Errors that aren't JSON
For an error that genuinely isn't JSON, such as proxying an upstream body or an HTML error page, adapters expose a `raw-response` result you return directly. It bypasses validation and the spec, so use it only when neither extension members nor `formatError` fit.
## A typical migration, in order
1. Move error responses to `ProblemDetailsSchema`, using `.extend({...})` to keep any extra fields. Most APIs stop here.
2. Only if a client strictly checks the content type, or needs a structurally different body: add `formatError`.
3. Serving old and new clients simultaneously? Branch inside `formatError` on a signal your API has.
4. Map any errors your handlers throw into Problem Details at the boundary.
5. As clients adopt the standard shape, drop the extras and remove `formatError`.
---
# Migrating from ts-rest
Source: /docs/migration/from-ts-rest
---
title: Migrating from ts-rest
description: Side-by-side comparison of ts-rest and Kizuna, for anyone weighing a ts-rest alternative, with notes on deliberate differences.
---
Kizuna is inspired by [ts-rest](https://ts-rest.com) and the ideas it pioneered. ts-rest showed that routes-first TypeScript APIs work, and a lot of people built real things with it, ourselves included. Kizuna borrows several of its core concepts and keeps the public API deliberately familiar, but takes a different approach under the hood. This page maps every changed API to its Kizuna equivalent.
## Package mapping
| ts-rest | Kizuna | Notes |
| ------------------- | ------------------------------ | ------------------------------------------------- |
| `@ts-rest/core` | `kizunajs` + `@kizunajs/fetch` | `@kizunajs/fetch` writes the client into your app |
| `@ts-rest/express` | `@kizunajs/express` | |
| `@ts-rest/next` | `@kizunajs/next` | |
| `@ts-rest/open-api` | `@kizunajs/openapi` | |
## The biggest difference
In ts-rest a route is a shape, and its implementation lives in a parallel tree you keep in step by hand. In Kizuna a route carries the handler that answers it:
```ts title="Kizuna"
export const users = k.routes.users({
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
},
})
.handler(async ({ params }) => ({
status: 200,
body: await db.users.findById(params.id),
})),
});
```
Most of the mapping below follows from that: there is no router to build, and nothing to keep aligned.
## Routes
### `initContract` → `new Kizuna()` + `k.routes`
There is no `initContract`. Create your surface with `new Kizuna()` once, then declare groups with `k.routes`.
```ts title="ts-rest"
import { initContract } from '@ts-rest/core';
const c = initContract();
export const contract = c.router({ ... });
```
```ts title="Kizuna"
import { Kizuna } from 'kizunajs';
import type { Config } from '../kizuna.types';
export const k = new Kizuna();
export const users = k.routes.users({ ... });
```
`Config` is written by `kizuna generate` from your `kizuna.config.ts`. It is what types every handler and checks every name you write. See [`new Kizuna()`](/docs/reference/Kizuna).
### Nested routes
```ts title="ts-rest"
export const contract = c.router({
users: c.router({ ... }),
});
```
```ts title="Kizuna"
export const users = k.routes.users({ ... });
export const health = k.routes.health({ ... });
```
The group you reach on `k.routes`, one you declared with [`k.groups`](/docs/reference/k-groups), sets the OpenAPI tag for every route in it.
### `c.noBody()` → `z.void()`
ts-rest uses `c.noBody()` to mark a route as having no request body, or a response as having no body. In Kizuna, use `z.void()` for the response and omit `body` entirely.
```ts title="ts-rest"
export const contract = c.router({
deleteUser: {
method: 'DELETE',
path: '/users/:id',
body: c.noBody(),
responses: {
204: c.noBody(),
},
},
});
```
```ts title="Kizuna"
export const users = k.routes.users({
deleteUser: k
.route({
method: 'DELETE',
path: '/users/:id',
responses: {
204: z.void(),
},
})
.handler(async ({ params }) => {
await db.users.delete(params.id);
return {
status: 204,
};
}),
});
```
## Assembling it
ts-rest passes its router straight to the client and the server. Kizuna assembles everything in one `kizuna.config.ts` at the root of your app, which is also where the CLI looks:
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { users } from './src/routes/users';
export default defineConfig({
adapter: expressAdapter(),
routes: [users],
});
```
`adapter` is the one field with no ts-rest counterpart. Naming a framework there is what types every handler's `req`, `c` or `request`, so you never import your framework's types into a route file.
See [`defineConfig`](/docs/reference/define-config).
## Client
```ts title="ts-rest"
import { initClient } from '@ts-rest/core';
const client = initClient(contract, {
baseUrl: '...',
});
```
```ts title="Kizuna"
import { createClient } from './api-client.generated';
const client = createClient({
baseUrl: '...',
});
```
Where ts-rest hands the contract to the client at runtime, Kizuna writes the client out ahead of time. Your config holds the handlers, so it never reaches a browser; name the file you want under `clients` and run `kizuna generate`:
```ts title="kizuna.config.ts"
clients: [
fetchClient({
output: './src/lib/api-client.generated.ts',
}),
],
```
See [Clients](/docs/clients/fetch).
## Server
### `initServer` → the route's own `handler`
There is no `initServer` and no router. The implementation sits on the route.
```ts title="ts-rest"
import { initServer } from '@ts-rest/express';
const s = initServer();
const router = s.router(contract, {
getUser: async ({ params }) => ({
status: 200,
body: await db.users.findById(params.id),
}),
});
```
```ts title="Kizuna"
export const users = k.routes.users({
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
},
})
.handler(async ({ params }) => ({
status: 200,
body: await db.users.findById(params.id),
})),
});
```
### `RouterImpl` has no counterpart
ts-rest types a handler tree because the tree is where handlers live. In Kizuna the handler sits on the route, typed from the declaration above it, so there is nothing to annotate and no second tree to keep in step.
```ts title="ts-rest"
import type { RouterImpl } from '@ts-rest/express';
const router: RouterImpl = { ... };
```
```ts title="Kizuna"
getUser: k
.route({ ... })
.handler(async ({ params }) => { ... }),
```
## Express adapter
### `createExpressEndpoints` → `kizuna.api.mount`
```ts title="ts-rest"
createExpressEndpoints(contract, router, app);
```
```ts title="Kizuna"
import kizuna from '../kizuna.config';
kizuna.api.mount(app);
```
## Next.js adapter
### Route file setup
```ts title="ts-rest"
import { createNextHandler } from '@ts-rest/serverless/next';
import { contract } from '@/contract';
import { router } from './router';
const handler = createNextHandler(contract, router, {
basePath: '/api',
});
export { handler as GET, handler as POST, handler as PUT, handler as PATCH, handler as DELETE, handler as OPTIONS };
```
```ts title="Kizuna"
import kizuna from '../../../../kizuna.config';
export const { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } = kizuna.api.mount({
basePath: '/api',
});
```
## Authentication
ts-rest leaves authentication to your framework's middleware. Kizuna declares it: an [identity](/docs/reference/k-identity) says how the credential travels and what a passing guard provides, the guard sits on that identity, and a route's `auth` names the one it requires.
```ts title="src/identities.ts"
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny }) => {
const session = bearer ? await verifySession(bearer.token) : undefined;
if (!session) {
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
}
return {
userId: session.userId,
};
});
```
Handlers of a route with `auth: 'user'` then read `auth.user.userId`, typed, and the identity is emitted into your OpenAPI document as a security scheme. See [Authentication](/docs/authentication).
## Zod version
Kizuna targets **Zod 4 only**. ts-rest supports Zod 3 and 4.
If you are upgrading from ts-rest and Zod 3, migrate to Zod 4 alongside this change:
| Zod 3 / ts-rest | Zod 4 / Kizuna |
| ------------------------- | ---------------------------------- |
| `c.noBody()` | `z.void()` or omit `body` entirely |
| `z.ZodTypeAny` | `z.ZodType` |
| `ZodIssue` (from `'zod'`) | `z.core.$ZodIssue` |
## Error responses
Kizuna returns [RFC 9457 Problem Details](/docs/reference/problem-details-schema) (`application/problem+json`) for every error response. Error responses must use `ProblemDetailsSchema` (or `ProblemDetailsSchema.extend({...})` for extra fields), not an arbitrary shape. Validation errors are Problem Details with a `detail` string and an `errors` array, instead of ts-rest's `{ message, issues }`. If you are porting an API whose clients expect the old shape, see [Migrating an existing API](/docs/migration/existing-api) for how to keep old clients working during the transition.
## Method mismatch behaviour
ts-rest returns 404 for requests to a known path with an unsupported method. Kizuna returns **405 with an `Allow` header** per [RFC 9110 §15.5.6](https://www.rfc-editor.org/rfc/rfc9110#section-15.5.6).
---
# BinarySchema & FileSchema
Source: /docs/reference/binary-and-file-schemas
---
title: BinarySchema & FileSchema
description: Helper schemas for binary response bodies (BinarySchema) and multipart upload fields (FileSchema).
---
Two helper schemas for non-JSON bodies, both from `kizunajs/schemas`.
```ts
import { BinarySchema, FileSchema } from 'kizunajs/schemas';
```
**Sending or returning a blob of bytes, use `BinarySchema`. Taking a file uploaded through a form, use `FileSchema`.**
| Helper | Is | Use | Swift type |
| -------------- | -------------------------- | --------------------------------------------------------- | --------------- |
| `BinarySchema` | `z.instanceof(Uint8Array)` | Binary response bodies (PDF, images) and raw binary input | `Data` |
| `FileSchema` | `z.instanceof(File)` | `multipart/form-data` upload fields | `MultipartFile` |
The split follows what each type carries. A `File` has a filename and MIME type, which is what a multipart part needs. A `Uint8Array` is bytes alone, and a Node `Buffer` satisfies it.
## BinarySchema
Use it as a response `body` and pair it with a `contentType`. It defaults to `application/octet-stream`. The body goes to the wire as raw bytes (never JSON-serialized); the OpenAPI generator emits `type: string, format: binary`. The fetch client reads it as a `Uint8Array`, the Swift client as `Data`, and the Kotlin client as a `ByteArray`.
```ts title="routes/reports.ts"
import { BinarySchema } from 'kizunajs/schemas';
import { k } from './k';
export const reportsRoutes = k.routes.reports({
downloadReport: k
.route({
method: 'GET',
path: '/reports/:id.pdf',
responses: {
200: {
body: BinarySchema,
contentType: 'application/pdf',
},
},
})
.handler(/* ... */),
});
```
The handler returns the bytes, as a `Buffer` or `Uint8Array`. Set `Content-Disposition` as a normal response header if you want a download:
```ts title="src/routes/reports.ts"
downloadReport: async ({ params }) => {
const pdf = await renderReport(params.id);
return {
status: 200,
body: pdf,
headers: {
'content-disposition': `inline; filename="report-${params.id}.pdf"`,
},
};
},
```
## FileSchema
Use it inside a `multipart/form-data` request body for uploaded files:
```ts title="users.ts"
import { FileSchema } from 'kizunajs/schemas';
uploadAvatar: k
.route({
method: 'POST',
path: '/avatar',
contentType: 'multipart/form-data',
body: z.object({
file: FileSchema,
userId: z.string(),
}),
responses: {
200: z.object({
size: z.number(),
}),
},
})
.handler(/* ... */),
```
---
# createClient()
Source: /docs/reference/create-client
---
title: createClient()
description: Create a fully typed HTTP client from the file kizuna generate writes, using the native fetch API.
---
Every generated fetch client exports `createClient`. See the [fetch client guide](/docs/clients/fetch) for usage.
The generated file imports nothing, so calling it needs no package installed.
```ts
import { createClient } from './api-client.generated';
```
The file comes from naming `fetchClient({ output })` under `clients` on [`defineConfig`](/docs/reference/define-config) and running `kizuna generate`.
## Parameters
```ts
createClient(config: ClientConfig): Client
```
| Option | Type | Required | Description |
| ---------------- | ----------------------------------------------------- | -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `baseUrl` | `string` | Yes | Base URL prepended to every route path |
| `baseHeaders` | `Record` | No | Headers merged into every request |
| `credentials` | `RequestInit['credentials']` | No | Passed as `credentials` to every `fetch` call |
| `fetch` | `typeof fetch` | No | Custom fetch implementation (e.g. for testing or a polyfill) |
| `onRequest` | `(request: OutgoingRequest) => void \| Promise` | No | Callback before each request, receiving the request about to be sent as `{ url, method, headers, route }`, where `route` is the route's table entry. May be async. |
| `retry` | `RetryOptions` | No | Retry a `GET`, `HEAD`, `OPTIONS`, `PUT` or `DELETE` answered `429` or `503`, or lost on the network. See [Retries](/docs/clients/fetch#retries) |
| `reconnect` | `ReconnectOptions` | No | Reconnect a dropped event stream on a `GET`, `HEAD`, `OPTIONS`, `PUT` or `DELETE`, sending `Last-Event-ID`. See [Resuming](/docs/streaming#resuming) |
| `requestContext` | `RequestContext` | \* | Header values for your API's [request context](/docs/reference/k-request-context). Present only when your API declares one, and required when any of its headers is |
`requestContext` values are typed from the declared header schemas, so an optional header stays optional and a coerced one takes the schema's input type. The generated file exports that type as `RequestContext`.
## Returns
`createClient` returns the `Client`, mirroring your route groups. Each route becomes a function accepting `{ params?, query?, body?, headers?, fetchOptions? }` and returning a `Promise` resolving to `{ status, body, headers }`.
`params` is typed from the route's `pathParams` schema when one is declared, otherwise from the `:param` placeholders in the path. A request type reads what the caller sends, so a schema that transforms its value takes the value before the transform.
The response is a discriminated union over the route's declared status codes. Narrow on `status` to reach the correctly typed `body`.
Each method carries the route's `summary`, `description`, `@deprecated` and an `@example` as JSDoc, so an editor shows them at the call site.
## Example
When your routes name an identity with [identities](/docs/authentication), send the credential in `baseHeaders`:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'http://localhost:3000',
baseHeaders: {
Authorization: `Bearer ${token}`,
},
});
const result = await apiClient.users.createUser({
body: {
name: 'Alice',
email: 'alice@example.com',
},
});
if (result.status === 201) {
console.log(result.body.id);
} else {
console.error(result.body.detail);
}
```
## Per-request options
Pass `fetchOptions` to customize individual requests:
```ts title="users.ts"
const { body } = await apiClient.users.listUsers({
query: {
page: 1,
},
fetchOptions: {
signal: AbortSignal.timeout(5000),
},
});
```
## Named types
The generated file also exports `API`, the namespace holding every model and every route's `Params`, `Query`, `Body` and `Result`. The config's `namespace` option calls it something else:
```tsx
import type { API } from './api-client.generated';
export function UserCard({ user }: { user: API.User }) {
return {user.name};
}
```
See the [Fetch client guide](/docs/clients/fetch) for per-request headers, validation errors, refusals, and response type narrowing.
---
# createMcpServer
Source: /docs/reference/create-mcp-server
---
title: createMcpServer
description: Create a raw MCP server from a Kizuna API for use with any transport (stdio, SSE, etc.).
---
MCP support is new and still settling. `createMcpServer` and the generated tool surface may change while v2 is in beta, so pin your version if you depend on them.
Create a raw [MCP](https://modelcontextprotocol.io) server from a Kizuna API. Use this when you want full control over the transport, for example stdio for CLI tools or SSE for custom setups.
To serve it from your app, install [`mcpPlugin`](/docs/reference/mcp-plugin) instead.
```ts
import { createMcpServer } from '@kizunajs/mcp';
```
## Parameters
```ts
createMcpServer(api: ApiWithRouter, options?: McpServerOptions): McpServer
```
| Parameter | Type | Required | Description |
| --------- | ------------------ | -------- | -------------------------------------------------------------- |
| `api` | `ApiWithRouter` | Yes | The `api` from [`defineConfig`](/docs/reference/define-config) |
| `options` | `McpServerOptions` | No | Configuration options |
## Options
| Option | Default | Description |
| ------------------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------- |
| `name` | `'MCP Server'` | Human-readable name shown to AI assistants |
| `version` | `'1.0.0'` | Semantic version string |
| `onlyReadOnly` | `false` | Keep only the methods RFC 9110 calls safe, so nothing an assistant calls can change data |
| `instructions` | built from your groups | Appended to the generated overview |
| `handlerContext` | none | Extra context spread into every handler call |
| `credentialHeaders` | none | Headers of the MCP transport request, used to run guards on secured tools |
| `transportAuth` | none | A scheme the transport already verified: its guard is skipped, and `context` reaches handlers under `auth.` |
Which routes it publishes is each route's own business: the ones declaring [`tool`](/docs/tools), less the ones whose shape a tool call cannot carry. A route whose `contentType` is `multipart/form-data` or `application/x-www-form-urlencoded` never publishes, because tool input is JSON, and neither does one whose response [streams](/docs/streaming), because a tool result is one value.
## Secured routes
Each call to a secured tool runs the same [guard](/docs/reference/k-identity) pipeline as an HTTP request, extracting the credential from `credentialHeaders`.
Driving the transport yourself means passing those headers along. For stdio there is no HTTP request, so supply whatever the environment provides:
```ts title="src/mcp.ts"
const server = createMcpServer(kizuna.api, {
name: 'My API',
credentialHeaders: {
authorization: `Bearer ${process.env.API_TOKEN}`,
},
});
```
## Returns
An `McpServer` instance from `@modelcontextprotocol/sdk`. Connect it to any transport.
## Example
```ts title="src/mcp.ts"
import { createMcpServer } from '@kizunajs/mcp';
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import kizuna from '../kizuna.config';
const server = createMcpServer(kizuna.api, {
name: 'My API',
version: '1.0.0',
});
await server.connect(new StdioServerTransport());
```
See the [MCP guide](/docs/mcp) for connecting clients and tool input/output structure.
---
# defineConfig
Source: /docs/reference/define-config
---
title: defineConfig
description: Assemble everything one API is made of, and get back the api you mount.
---
`defineConfig({ adapter, routes, identities, ... })` is where an API comes together. It takes what you declared with `k`, resolves each route's `auth`, checks the pieces against one another, and hands back the `api` you mount.
It lives in `kizuna.config.ts` at the root of your app, which is where the CLI looks for it.
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { routes } from './src/routes';
import { user } from './src/identities';
export default defineConfig({
adapter: expressAdapter(),
routes,
auth: {
identities: {
user,
},
},
});
```
```ts title="src/index.ts"
import express from 'express';
import kizuna from '../kizuna.config';
const app = express();
kizuna.api.mount(app);
```
## What it takes
| Field | What it is |
| ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `adapter` | The framework this API is served on, as a call: `expressAdapter()`. Its request reaches every handler, typed. |
| `routes` | A list of what [`k.routes`](/docs/reference/k-routes) returned, in any order. Each route is keyed by its group, and carries its own handler. Omit it while setting up. |
| `auth` | Who may call this API: `identities`, each declared with [`k.identity`](/docs/reference/k-identity) and carrying its own guard, and the `guardSchema` their `deny()` produces. |
| `requestContext` | What every route resolves before its guards run, declared with [`k.requestContext`](/docs/reference/k-request-context). |
| `validation` | How a request is checked: `issueCodes`, the `code` values [`k.issue`](/docs/reference/k-issue) may emit beyond Zod's own. |
| `jobs` | Scheduled work, declared with [`k.jobs`](/docs/reference/k-jobs). |
| `jobRunner` | How this deployment runs them: `mode`, `path`, `method`, `transport`, `onError`. See [Jobs](/docs/jobs). |
| `plugins` | What this API installs beside its own routes, as a list. See [Create a Plugin](/docs/extend/create-plugin). |
| `groups` | The groups routes are filed under, from [`k.groups`](/docs/reference/k-groups). |
| `typescript` | Where `kizuna generate` writes the `Config`, as `{ outputFile }`. |
| `clients` | The clients `kizuna generate` writes from this API, each built with [`defineClient`](/docs/extend/create-client). |
`jobs` is what the jobs are, and `jobRunner` is how this deployment runs them: the first is shared by every config that serves these routes, the second differs between dev and production.
## What it hands back
The `api`: everything you declared, plus the ability to serve it. It carries `routes`, `securitySchemes`, `groups` and the rest, so anything that reads a declaration takes it directly:
```ts title="scripts/generate-openapi.ts"
import { generateOpenApi } from '@kizunajs/openapi';
import kizuna from '../kizuna.config';
const document = generateOpenApi(kizuna.api);
```
And `clients`, which the CLI reads when it generates.
## Access control
Every route carries its own [`auth`](/docs/reference/k-route): the identity it requires, and the roles it accepts or the permissions the caller has to hold. Once a config declares an identity, a route without an `auth` does not compile, so public takes an explicit `false`. See [Access Control](/docs/access-control) for the walkthrough.
```ts title="src/routes/workspace.ts"
export const workspaceRoutes = k.routes.workspace({
getWorkspace: k
.route({
method: 'GET',
path: '/workspace',
auth: 'member',
responses: {
200: WorkspaceSchema,
},
})
.handler(({ auth }) => ({
status: 200,
body: db.workspaces.find(auth.member.workspaceId),
})),
});
```
`defineConfig` resolves each `auth` onto that route's `security`, `roles` and `requires`, which the [guards](/docs/reference/k-identity), the [route handler](/docs/reference/k-route) types, and the [OpenAPI document](/docs/reference/generate-openapi) all read.
An identity a route names has to carry a guard, or the config refuses to assemble.
## Jobs
Jobs declared with [`k.jobs`](/docs/reference/k-jobs) go under `jobs`, beside `routes`:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
jobs,
jobRunner: {
mode: 'http',
},
});
```
`jobRunner` is required once `jobs` declares one, and its `mode` says how they run: `'http'` serves the two job endpoints, `'in-process'` leaves them unmounted for `startJobs` to tick. A job carries its own identity, so it declares no `auth`, and it stays out of `api.routes`, the OpenAPI document, and the generated Swift, Kotlin and MCP surfaces. See [Jobs](/docs/jobs).
## Plugins
Plugins go under `plugins`, as a list. Each carries the name your handlers read it under:
```ts title="kizuna.config.ts"
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
mcpPlugin({
name: 'My API',
}),
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
}),
],
});
```
Their routes are served by `api.mount`, and reach the clients like your own unless they're marked `hidden`. See [Create a Plugin](/docs/extend/create-plugin).
---
# generateKotlinClient
Source: /docs/reference/generate-kotlin-client
---
title: generateKotlinClient
description: Generate a native Kotlin client from a Kizuna API with OkHttp, kotlinx.serialization, and coroutines.
---
The Kotlin client is new and still settling. The generated API surface may change while v2 is in beta, so pin your version if you depend on it.
Generate a native Kotlin client from your routes. The generated client uses OkHttp for HTTP, kotlinx.serialization for JSON, and Kotlin coroutines for async.
```ts
import { generateKotlinClient } from '@kizunajs/kotlin';
```
## Parameters
```ts
generateKotlinClient(api: ApiDefinition, config: KotlinConfig): string
```
| Parameter | Type | Description |
| --------- | --------------- | -------------------------------------------------------------- |
| `api` | `ApiDefinition` | The `api` from [`defineConfig`](/docs/reference/define-config) |
| `config` | `KotlinConfig` | Generation configuration |
## `KotlinConfig`
| Option | Type | Required | Description |
| --------------------- | --------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| `namespaceName` | `string` | Yes | Name for the generated `object` and client class (e.g. `'API'`) |
| `packageName` | `string` | No | Package declaration for the generated file (e.g. `'com.example.api'`) |
| `camelCaseProperties` | `boolean` | No | Convert wire field names to camelCase properties, mapped back via `@SerialName`. Default `false` |
| `unknownEnumCase` | `boolean` | No | Emit enums as a `sealed interface` with an `Unknown(wireValue)` member so unrecognised wire values decode instead of throwing. Default `false` |
## Example
```ts title="generate-kotlin.ts"
import path from 'path';
import { writeFileSync } from 'fs';
import { generateKotlinClient } from '@kizunajs/kotlin';
import kizuna from '../kizuna.config';
const kotlin = generateKotlinClient(kizuna.api, {
namespaceName: 'API',
packageName: 'com.example.api',
});
writeFileSync('generated/APIClient.kt', kotlin);
```
See the [Kotlin client guide](/docs/clients/kotlin) for CLI usage and integration patterns.
---
# generateOpenApi
Source: /docs/reference/generate-openapi
---
title: generateOpenApi
description: Generate an OpenAPI 3.1.0 document from a Kizuna api.
---
Generate an [OpenAPI 3.1.0](https://spec.openapis.org/oas/v3.1.0) document from your api. Returns a renderer you call with `'json'` or `'yaml'`.
```ts
import { generateOpenApi } from '@kizunajs/openapi';
```
## Parameters
```ts
generateOpenApi(api: ApiDefinition, overrides?: Partial): OpenApiRenderer
```
| Parameter | Type | Description |
| ----------- | --------------------------------- | -------------------------------------------------------------- |
| `api` | `ApiDefinition` | The `api` from [`defineConfig`](/docs/reference/define-config) |
| `overrides` | `Partial` | Merged over the plugin's options, for what only a build knows |
It lives on `@kizunajs/openapi`, beside [`openApiPlugin`](/docs/reference/openapi-plugin) and the document types.
## Options
Options are declared on [`openApiPlugin`](/docs/reference/openapi-plugin), and `generateOpenApi` reads them off the api, so a build step cannot write a document that differs from the one your server serves. Pass `overrides` for what only a build step knows, such as the public `servers` list.
| Option | Type | Default | Description |
| ----------------- | ------------------------------------- | --------- | --------------------------------------------------------------------------------------- |
| `info` | `{ title, version, description? }` | required | OpenAPI `info` object |
| `openApiVersion` | `'3.1.0'` | `'3.1.0'` | OpenAPI specification version for the generated document |
| `servers` | `{ url, description? }[]` | none | Server URLs |
| `setOperationId` | `boolean \| 'concatenated-path'` | `false` | Set `operationId` from the route key. Use `'concatenated-path'` to include parent keys. |
| `externalDocs` | `{ url, description? }` | none | Top-level external documentation link |
| `operationMapper` | `(operation, route, id) => operation` | none | Callback to transform each operation before it is added to the spec |
| `derivedHead` | `boolean` | `false` | Document the derived `head` operation on every `GET` path without a declared one |
There are no security or tag options. Security is emitted from [each route's `auth`](#security-emission) and the document's tag list from [`k.groups`](/docs/reference/k-groups), so neither can disagree with what the server enforces.
## Returns
An `OpenApiRenderer` function:
```ts
renderer('json'); // OpenApiDocument object
renderer('yaml'); // YAML string
```
## Example
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { openApiPlugin } from '@kizunajs/openapi';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
servers: [
{
url: 'https://api.example.com',
description: 'Production',
},
],
setOperationId: true,
}),
],
});
```
```ts title="scripts/generate-openapi.ts"
import { generateOpenApi } from '@kizunajs/openapi';
import kizuna from '../kizuna.config';
const spec = generateOpenApi(kizuna.api);
app.get('/openapi.json', (_req, res) => {
res.json(spec('json'));
});
```
## Security emission
Security is generated from what you declared, not configured on the generator. Every [identity](/docs/reference/k-identity) named under `auth.identities` on [`defineConfig`](/docs/reference/define-config) is emitted under `components.securitySchemes`, and every route with an [`auth`](/docs/reference/k-route) references those names in its `security`, with the permissions an OAuth route requires as its scopes. Public routes (`false`) get none.
With the `user` (bearer) and `member` (API key) identities, and a workspace route declaring `auth: 'member'`, the document contains:
```yaml title="openapi.yaml"
components:
securitySchemes:
user:
type: http
scheme: bearer
member:
type: apiKey
name: x-workspace-token
in: header
paths:
/workspace:
get:
security:
- member: []
```
A [`custom`](/docs/reference/k-identity#custom-identities) identity is the exception: OpenAPI can't describe its credential, so it emits no `securityScheme` and no `security`. Its routes instead carry an `x-kizuna-guarded` extension, keeping a protected-out-of-band route distinct from a public one.
A route with `roles` carries them under `x-kizuna-roles`, `['owner']`, and one with `requires` carries the permissions under `x-kizuna-requires`, `{ workspace: ['delete'] }`, so a reader of the document sees who the caller has to be.
The spec and the runtime [guards](/docs/reference/k-identity) both derive from the same `auth`, so documented security is enforced security.
See the [OpenAPI guide](/docs/openapi) for Scalar integration, writing specs to disk, and breaking change detection.
---
# generateSwiftClient
Source: /docs/reference/generate-swift-client
---
title: generateSwiftClient
description: Generate a native Swift client from a Kizuna API with URLSession and Codable.
---
Generate a native Swift client from your routes, built on `URLSession` and `Codable`.
```ts
import { generateSwiftClient } from '@kizunajs/swift';
```
## Parameters
```ts
generateSwiftClient(api: ApiDefinition, config: SwiftConfig): string
```
| Parameter | Type | Description |
| --------- | --------------- | -------------------------------------------------------------- |
| `api` | `ApiDefinition` | The `api` from [`defineConfig`](/docs/reference/define-config) |
| `config` | `SwiftConfig` | Generation configuration |
## `SwiftConfig`
| Option | Type | Required | Description |
| --------------------- | --------- | -------- | --------------------------------------------------------------------------------------------------------------------- |
| `namespaceName` | `string` | Yes | Name for the generated Swift enum and client type (e.g. `'API'`) |
| `camelCaseProperties` | `boolean` | No | Convert wire field names to camelCase properties, mapped back via `CodingKeys`. Default `false` |
| `unknownEnumCase` | `boolean` | No | Emit enums with an `unknown(String)` fallback so unrecognised wire values decode instead of throwing. Default `false` |
## Example
```ts title="generate-swift-client.ts"
import { writeFileSync } from 'node:fs';
import { generateSwiftClient } from '@kizunajs/swift';
import kizuna from '../kizuna.config';
const source = generateSwiftClient(kizuna.api, {
namespaceName: 'API',
});
writeFileSync('generated/API.swift', source);
```
See the [Swift client guide](/docs/clients/swift) for CLI usage and integration patterns.
---
# API Reference
Source: /docs/reference
---
title: API Reference
description: Every function, schema and plugin kizuna exports, with its options and types.
---
## Declaring an API
The pieces one API is built from, in the order a config usually meets them.
The authoring surface, typed by the `Config` that `kizuna generate` writes.
Assemble the routes, identities and plugins into the api you mount.
One route and the handler that answers it.
Routes declared into one of your groups.
The groups routes are organised into, nested as deep as the API needs.
Name a Zod schema so every client generates a named type.
Typed request-scoped values, such as a logger or the caller's locale.
A validation issue with a code your config declares.
Scheduled jobs, with their inputs and results.
## Security
Who may call a route, and what they are allowed to do.
A kind of caller, the guard that authenticates it, and the context it provides.
The roles callers hold.
Every permission, for roles to hold and routes to require.
The RFC 9728 discovery document and its `WWW-Authenticate` challenge.
## Calling an API
The TypeScript client and the guards that narrow its errors.
A typed `fetch` client from the file `kizuna generate` writes.
TanStack Query options from that client.
Tell a kizuna validation error from your own `400`.
Catch a status the route does not declare.
## Schemas
The Zod schemas kizuna ships for bodies every API shares.
The RFC 9457 body every error response carries.
Binary response bodies and multipart upload fields.
## Generators and plugins
What kizuna writes and serves from your routes.
An OpenAPI 3.1.0 document.
Serve that document and a reference UI on any adapter.
A Swift client on `URLSession` and `Codable`.
A Kotlin client on OkHttp, kotlinx.serialization and coroutines.
An MCP endpoint that publishes your tool routes.
A bare MCP server for stdio or any other transport.
---
# isUndeclaredResponseError
Source: /docs/reference/is-undeclared-response-error
---
title: isUndeclaredResponseError
description: Narrow a TanStack Query error to a response whose status the route does not declare.
---
Narrows an `error` from a query or mutation to `UndeclaredResponseError`. See the [TanStack Query guide](/docs/clients/tanstack-query#error-handling).
```ts
import { isUndeclaredResponseError } from '@kizunajs/tanstack-query';
```
## Parameters
```ts
isUndeclaredResponseError(error: unknown): error is UndeclaredResponseError
```
| Parameter | Type | Description |
| --------- | --------- | ------------------------------------ |
| `error` | `unknown` | The `error` from a query or mutation |
## `UndeclaredResponseError`
| Property | Type | Description |
| --------- | ------------------------ | ------------------------------ |
| `status` | `number` | The status the server returned |
| `body` | `unknown` | The parsed response body |
| `headers` | `Record` | The response headers |
It extends `Error`, so `retry`, `throwOnError`, and error boundaries treat it as one.
## When it is thrown
A route's declared statuses are the keys of its `responses`, plus `400` when the route has a `body` or `query` schema. Those arrive as `data`. Every other status throws.
```ts
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(/* ... */),
```
A `200` or `404` is data. A `500` throws.
## Example
```ts
const { data, error } = useQuery(
api.users.getUser.queryOptions({
input: {
params: {
id: 'usr_abc123',
},
},
})
);
if (data?.status === 404) {
return ;
}
if (error !== null && isUndeclaredResponseError(error)) {
console.error(error.status, error.body);
}
```
## See also
- [TanStack Query client](/docs/clients/tanstack-query)
- [`new KizunaTanstackQuery()`](/docs/reference/kizuna-tanstack-query)
- [`isValidationError`](/docs/reference/is-validation-error)
---
# isValidationError
Source: /docs/reference/is-validation-error
---
title: isValidationError
description: Type guard to distinguish Kizuna validation errors from custom 400 responses on the client.
---
Distinguish a Kizuna validation error from a route's own `400` body. Every generated fetch client exports it:
```ts
import { isValidationError } from './api-client.generated';
```
## Parameters
```ts
isValidationError(body: unknown): body is API.ValidationError
```
## `ValidationError` shape
An RFC 9457 Problem Details body with an `errors` extension:
```ts
interface ValidationError {
type: string;
title: string;
status: number;
detail: string;
errors: Array<{
code: ValidationIssueCode;
path: string[];
message: string;
}>;
}
```
`code` is typed as `ValidationIssueCode`, so the built-in Zod codes are offered as autocomplete suggestions, while any custom string (e.g. one emitted via [`k.issue`](/docs/reference/k-issue)) is still assignable.
Common error codes: `invalid_type`, `too_small`, `too_big`, `invalid_string_format`, `unrecognized_keys`, `not_multiple_of`, `custom`. To emit your own machine-readable code from a `.superRefine()` check, see [`k.issue`](/docs/reference/k-issue).
## Example
When a route declares its own `400` response, the client sees a union of your type and `ValidationError`. Use `isValidationError` to distinguish them:
```ts title="users.ts"
import { isValidationError } from './api-client.generated';
const result = await client.users.createUser({
body: {
name: '',
email: 'not-an-email',
},
});
if (result.status === 400) {
if (isValidationError(result.body)) {
for (const error of result.body.errors) {
console.log(error.code, error.path, error.message);
}
} else {
console.error(result.body.detail);
}
}
```
A route that declares no `400` of its own needs no guard: `result.status === 400` already narrows to `ValidationError`.
See the [Fetch client guide](/docs/clients/fetch#validation-errors) for more details.
---
# k.groups
Source: /docs/reference/k-groups
---
title: k.groups
description: Declare the groups routes are organised into, nested as deep as the API needs.
---
Declare the groups routes are organised into. Name the result under `groups` on [`defineConfig`](/docs/reference/define-config), and declare routes into a group with [`k.routes`](/docs/reference/k-routes).
## Parameters
```ts
k.groups(groups: Record): GroupSet
```
Each entry is keyed by a name you choose. A value is either a `GroupOptions` object or a plain title string:
| Option | Type | Required | Description |
| -------------- | -------- | -------- | ------------------------------------------------------- |
| `title` | `string` | Yes | The group's name in the docs. Unique among its siblings |
| `description` | `string` | No | Shown beside the tag in the OpenAPI document |
| `externalDocs` | `object` | No | `{ url, description? }` external docs for the group |
| `groups` | `object` | No | The groups nested under this one, in the same shape |
A group is addressed by its dotted path, `workspaces.members`. `k.groups` throws when two siblings share a title, since a reader could not tell them apart.
## Returns
A `GroupSet`. Once your `Config` carries it, `k.routes` offers every group by name, and a route's own `groups` completes their dotted paths. The generated OpenAPI document lists each top-level group as a tag.
## Example
```ts title="src/groups.ts"
import { k } from './k';
export const groups = k.groups({
workspaces: {
title: 'Workspaces',
description: 'Shared spaces and the people in them',
groups: {
members: 'Members',
invites: 'Invites',
},
},
health: 'Health',
});
```
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { groups } from './src/groups';
import { routes } from './src/routes';
export default defineConfig({
groups,
routes,
});
```
```ts title="src/routes/members.ts"
import { k } from '../k';
import { listMembers } from './list-members';
import { removeMember } from './remove-member';
export const memberRoutes = k.routes.workspaces.members({
listMembers,
removeMember,
});
```
The group is also the route's key: `listMembers` is `workspaces.members.listMembers`, so clients call routes where the documentation files them. List the trees on `defineConfig` in any order, `routes: [memberRoutes, inviteRoutes]`. [`kizuna routes`](/docs/cli#group-problems) fails when a route is in no group once groups exist, and when a group holds no routes.
## Nested groups in OpenAPI
OpenAPI 3.1 has no nested tags, so each top-level group becomes a tag and a route in a nested group is listed under the group at the top of its path. `listMembers` shows under Workspaces.
A title only has to differ from its siblings, since nested titles never become tags of their own. `workspace.notes` and `assistant.notes` can both be titled "Notes".
## Listing a route under more groups
A route's own `groups` adds it to more groups, by dotted path, with completion:
```ts title="src/routes/list-my-invites.ts"
export const listMyInvites = k
.route({
method: 'GET',
path: '/me/invites',
auth: 'user',
groups: ['workspaces.invites'],
// ...
})
.handler(/* ... */);
```
See the [Routes guide](/docs/routes#splitting-routes-across-files) for laying groups out across files.
---
# k.identity
Source: /docs/reference/k-identity
---
title: k.identity
description: Declare who can call your API, the context a passing guard provides, the roles its callers hold, and the guard that authenticates them.
---
Authentication is still settling. `k.identity` may change while v2 is in beta, so pin your version if you depend on it.
An identity describes one kind of authenticated caller: an OpenAPI security scheme (how the credential travels), an optional `context` schema (what a passing guard provides to handlers), and optionally the `roles` its callers hold, which a route's [`auth`](/docs/reference/k-route) is checked against. See [Authentication](/docs/authentication) and [Access Control](/docs/access-control) for the walkthroughs.
```ts
import { k } from './k';
```
## Builders
| Builder | Credential source | OpenAPI scheme |
| -------------------------- | -------------------------------------------- | ------------------------------------ |
| `k.identity.bearer` | `Authorization: Bearer ` | `{ type: 'http', scheme: 'bearer' }` |
| `k.identity.apiKey` | A named header, query parameter, or cookie | `{ type: 'apiKey', name, in }` |
| `k.identity.basic` | `Authorization: Basic `, decoded | `{ type: 'http', scheme: 'basic' }` |
| `k.identity.oauth2` | `Authorization: Bearer `, with scopes | `{ type: 'oauth2', flows }` |
| `k.identity.openIdConnect` | `Authorization: Bearer ` | `{ type: 'openIdConnect', ... }` |
| `k.identity.custom` | Read by the guard (e.g. a path segment) | none, emits `x-kizuna-guarded` |
Each builder hands back the identity, waiting for its `guard`. Every one takes `context` (optional), `roles` (optional), `description` (optional), and `scheme` (optional, where identities sharing one credential set the same `scheme` name and emit a single OpenAPI scheme). Method-specific fields:
| Builder | Extra fields |
| -------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `k.identity.bearer` | `bearerFormat?` (e.g. `'JWT'`) |
| `k.identity.apiKey` | `name`, `in: 'header' \| 'query' \| 'cookie'` |
| `k.identity.oauth2` | `flows` (OpenAPI OAuth Flows object), `issuer?` (the authorization server's RFC 8414 issuer identifier), `resourceMetadata?` (this API's RFC 9728 metadata URL, sent in every `Bearer` challenge) |
| `k.identity.openIdConnect` | `openIdConnectUrl`, `resourceMetadata?` |
## Example
```ts title="identities.ts"
import { z } from 'zod';
import { k } from './k';
export const user = k.identity
.bearer({
context: z.object({
userId: z.string(),
}),
})
.guard(async ({ bearer, deny }) => {
const session = bearer ? await db.sessions.findByToken(bearer.token) : null;
if (!session)
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
return {
userId: session.userId,
};
});
export const member = k.identity
.apiKey({
name: 'x-workspace-token',
in: 'header',
context: z.object({
workspaceUserId: z.string(),
}),
roles,
})
.guard(async ({ apiKey, deny }) => {
const membership = apiKey ? await db.memberships.findByApiKey(apiKey.value) : null;
if (!membership)
return deny({
status: 403,
body: {
detail: 'Forbidden',
},
});
return membership;
});
```
## The guard
`guard` is what runs before the handler of every route whose `auth` names this identity. It receives the credential the method extracted, the path params the identity declares, your framework's own request, and `deny`. Return the identity's `context`, or call `deny({ status, body })` to refuse.
It sits on the identity because that is the one place it belongs to. An identity with no guard cannot authenticate anyone, and [`defineConfig`](/docs/reference/define-config) refuses to assemble an API whose routes name one.
## `context` vs `roles`
- **`context`** is who the caller is. A guard must return it, and handlers of secured routes receive it under `auth`, keyed by the identity's name (`auth.user`, `auth.member`).
- **`roles`** is who the caller can be, declared with [`Kizuna.roles`](/docs/reference/kizuna-roles). The guard returns the caller's `role` beside the context, a route's `roles` or `requires` is checked against it, and handlers read `auth.member.role`. Roles built from a permission catalog add `auth.member.permissions`, everything the caller holds.
An identity with neither can still be required by a route's `auth` (`'user'`), just not narrowed.
## Authentication-only identities
An identity that only proves the caller is known, such as an API key, has nothing to hand the handler. Omit `context` and `roles`:
Its guard returns nothing on success, or `deny(...)` to reject:
```ts title="identities.ts"
export const apiConsumer = k.identity
.apiKey({
name: 'x-api-key',
in: 'header',
})
.guard(async ({ apiKey, deny }) => {
if (!apiKey || !(await isKnownKey(apiKey.value)))
return deny({
status: 401,
body: {
detail: 'Unauthorized',
},
});
});
```
A route secured only by such an identity gets no `auth` entry for it.
## Custom identities
Some credentials don't fit any OpenAPI security scheme. A capability URL is the common case: you email or SMS a link like `/invites/:token`, and the path token _is_ the credential. OpenAPI's `apiKey` can't describe it, since its `in` allows only `header`, `query`, and `cookie` with no `path` option, so declaring one would emit a scheme a generated client would act on incorrectly.
`k.identity.custom` is the escape hatch. It has no OpenAPI scheme; its guard reads the credential itself from wherever it lives:
```ts title="identities.ts"
export const inviteToken = k.identity
.custom({
context: z.object({
inviteId: z.string(),
}),
params: z.object({
token: z.string(),
}),
})
.guard(async ({ params, deny }) => {
const inviteId = await resolveInvite(params.token);
if (!inviteId)
return deny({
status: 404,
body: {
detail: 'Not found',
},
});
return {
inviteId,
};
});
```
The guard receives the usual `{ params, deny }` (plus your framework's handler context) with no credential key, since there is nothing for the runtime to pre-extract. Everything else is ordinary typed auth: the identity is named under `identities`, a route's `auth` references it, handlers read `auth.inviteToken.inviteId`, and `roles` work as usual.
Because it emits no `security`, a custom-guarded route would otherwise look public in the spec. To keep the distinction honest, [`generateOpenApi`](/docs/reference/generate-openapi) marks the operation with an `x-kizuna-guarded` extension listing the custom identities, so a genuinely public route (no `security`, no extension) stays distinguishable from one protected out-of-band.
Reach for `custom` only when the credential is truly inexpressible. A token belongs in `bearer`, a signature header in `apiKey`; mutual TLS has its own OpenAPI type.
## Naming identities
Name identities in [`defineConfig`](/docs/reference/define-config) under `identities`. Their keys become the names everything else uses: a route's `auth`, and the handler context keys:
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { user, member } from './src/identities';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
auth: {
identities: {
user,
member,
},
},
});
```
## Securing routes
A route's `auth` names the identity it requires, keyed by the names above:
```ts title="src/routes/workspace.ts"
export const workspaceRoutes = k.routes.workspace({
getWorkspace: k
.route({
method: 'GET',
path: '/workspace',
auth: 'member',
responses: {
200: WorkspaceSchema,
},
})
.handler(({ auth }) => ({
status: 200,
body: db.workspaces.find(auth.member.workspaceId),
})),
});
```
See [`k.route`](/docs/reference/k-route) for every value form.
## OpenAPI emission
[`generateOpenApi`](/docs/reference/generate-openapi) emits identities under `components.securitySchemes`, and each secured route references them in its `security`, with the permissions an OAuth route requires as its scopes, the roles it accepts under `x-kizuna-roles`, and the permissions it requires under `x-kizuna-requires`.
---
# k.issue
Source: /docs/reference/k-issue
---
title: k.issue
description: Emit a validation issue with a machine-readable code, checked against the codes your config declares.
---
Custom issue codes are new and still settling. `k.issue` and the `validation.issueCodes` option may change while v2 is in beta, so pin your version if you depend on them.
Emit a single Zod validation issue carrying a custom machine-readable `code`. The code is surfaced verbatim in the `errors[].code` field of Kizuna's [`ValidationErrorSchema`](/docs/reference/is-validation-error).
The code is checked against the `validation.issueCodes` you declared on [`defineConfig`](/docs/reference/define-config), so a typo is a compile error.
Zod's types restrict `ctx.addIssue()` to its built-in issue union, so a custom code needs a cast at every call site. `k.issue` holds that cast.
## Parameters
```ts
k.issue(
ctx: z.core.$RefinementCtx,
issue: { code: string; message: string; input: Input },
): void
```
| Parameter | Type | Description |
| --------------- | ------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `ctx` | `z.core.$RefinementCtx` | The refinement context from `.superRefine()`. |
| `issue.code` | `Codes \| BuiltinIssueCode` | One of the `validation.issueCodes` declared on `defineConfig`, or a built-in Zod code. Surfaced in `errors[].code`. |
| `issue.message` | `string` | Human-readable description of the failure. |
| `issue.input` | `Input` | The value that failed validation. |
## Example
```ts title="routes/contacts.ts"
import { z } from 'zod';
import { isValidPhoneNumber } from 'libphonenumber-js';
const CreateContactSchema = z.object({
phone: z.string().superRefine((value, ctx) => {
if (isValidPhoneNumber(value)) return;
k.issue(ctx, {
code: 'invalid_phone_number',
message: 'Invalid phone number',
input: value,
});
}),
});
```
A request whose body fails this refinement returns `400` with the custom code in the response:
```json
{
"type": "about:blank",
"title": "Bad Request",
"status": 400,
"detail": "Request validation failed",
"errors": [
{
"code": "invalid_phone_number",
"path": ["phone"],
"message": "Invalid phone number"
}
]
}
```
## Typed codes on the client
By default `errors[].code` is typed as [`ValidationIssueCode`](/docs/reference/is-validation-error), so the built-in Zod codes are suggested in autocomplete and any custom string is accepted, but your `invalid_phone_number` is not _suggested_ (it lives only inside the refinement callback, where TypeScript can't see it).
To make the client suggest your custom codes, declare them under `validation.issueCodes` on `defineConfig` and regenerate the [fetch client](/docs/clients/fetch):
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { groups } from './src/groups';
import { routes } from './src/routes';
export default defineConfig({
groups,
routes,
validation: {
issueCodes: ['invalid_phone_number'],
},
});
```
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'http://localhost:3000',
});
```
Now `errors[].code` on a `400` response is widened to `ValidationIssueCode | 'invalid_phone_number'`, so `invalid_phone_number` shows up in autocomplete when you read or compare it:
```ts title="lib/contacts.ts"
const result = await apiClient.contacts.createContact({
body: {
phone: 'nope',
},
});
if (result.status === 400 && isValidationError(result.body)) {
for (const issue of result.body.errors) {
if (issue.code === 'invalid_phone_number') {
// ^ autocompleted, type-checked
}
}
}
```
Each API has its own config, so codes stay scoped to it.
See [`isValidationError`](/docs/reference/is-validation-error) for how clients consume these codes.
---
# k.jobs
Source: /docs/reference/k-jobs
---
title: k.jobs
description: Declare your API's scheduled jobs, with their schedules, inputs, and results.
---
Jobs are new and still settling. `k.jobs` may change while v2 is in beta, so pin your version if you depend on it.
Declares your API's scheduled jobs. The first argument is the identity every job requires, the credential your scheduler sends. Pass the result to `defineConfig` under `jobs`, alongside `routes`.
```ts title="jobs.ts"
import { z } from 'zod';
import { cron } from 'kizunajs';
export const jobs = k.jobs('scheduler', {
sendDigests: {
schedule: cron.daily('05:00'),
summary: 'Send the daily digest to every user',
result: z.object({
sent: z.int(),
}),
},
billing: {
reconcileInvoices: {
schedule: cron.every('15m'),
input: z.object({
since: z.string(),
}),
},
},
});
```
Jobs nest to any depth. Because a job carries its own identity, it declares no `auth` of its own.
Omit the identity argument only for jobs that run in process, with `jobRunner: { mode: 'in-process' }`. Otherwise `/jobs/run` would let anyone trigger them, so `defineConfig` throws.
```ts title="jobs.ts"
export const jobs = k.jobs({
sendDigests: {
schedule: cron.daily('05:00'),
},
});
```
See the [Scheduled jobs guide](/docs/jobs) for handlers, triggering, and local development.
## Job fields
| Field | Type | Notes |
| ------------- | ---------------------------------- | ----------------------------------------------------------------------------------------------------------------------- |
| `schedule` | `string \| { cron, timezone }` | A five-field cron expression, UTC unless a `timezone` is given. Omit it for a job that is only ever queued from code. |
| `retry` | `number` | How many attempts a failed run deserves, at least `1`. Handed to the transport, which is what retries. Defaults to `1`. |
| `input` | `z.ZodType` | Schema for the payload the job is queued with. Validated on `run` and `queue`, and again at the run endpoint. |
| `result` | `z.ZodType` | Schema for what the job reports on success. Omit it and the job answers `204`. |
| `summary` | `string` | |
| `description` | `string` | |
| `responses` | `{ [status]: ResponseDefinition }` | Extra responses beyond the synthesized ones. |
## Synthesized responses
Every job answers with the same set. A scheduler reads the status code to decide whether to retry.
| Status | Meaning |
| ------------------------------------- | ------------------------------- |
| `200` with `result`, or `204` without | Done |
| `422` | Permanent failure; do not retry |
| `500` | Unexpected throw; retry |
| `503` | Transient failure; retry |
`422`, `500`, and `503` take an RFC 9457 Problem Details body, so a handler supplies `detail` plus any extension members.
## Schedule helpers
Exported from `kizunajs`. Each returns a plain cron string.
| Helper | Expression |
| ----------------------------- | -------------- |
| `cron.every('15m')` | `*/15 * * * *` |
| `cron.every('2h')` | `0 */2 * * *` |
| `cron.hourly(30)` | `30 * * * *` |
| `cron.daily('05:00')` | `0 5 * * *` |
| `cron.weekly('mon', '09:00')` | `0 9 * * 1` |
| `cron.monthly(1, '05:00')` | `0 5 1 * *` |
`nextRun(schedule, from?)` returns the next time a schedule fires, or `undefined` for a schedule that never can (`0 0 30 2 *`). `nextRuns(schedule, count, from?)` returns several.
## Reaching a job
Every handler receives a `jobs` runner shaped like the declaration, with two methods per job. `run` resolves to what the handler returned, as `{ status, body }`; `queue` resolves once the job is in line.
```ts title="src/routes/users.ts"
const result = await jobs.billing.reconcileInvoices.run({ since });
await jobs.indexUser.queue({
input: {
userId,
},
dedupeKey: `index:${userId}`,
runAt: tomorrow,
});
```
Input is validated against the job's `input` schema either way. Where a queued job goes is the [transport's](/docs/extend/create-job-transport) business; with none configured it runs in this process.
## Validation
`k.jobs` throws on:
- an invalid cron expression, naming the field
- an unknown time zone
- a `retry` that is not a whole number, or is below `1`
- a job with a `schedule` **and** an `input` its schema will not accept as empty. A scheduler sends no body, so that job could only ever fail validation
---
# k.requestContext
Source: /docs/reference/k-request-context
---
title: k.requestContext
description: Provide request-scoped values to every handler, typed, such as analytics ids, loggers, and the caller's locale.
---
Request-scoped values every handler receives, typed, such as analytics ids, loggers, and the caller's locale. Declare one with `k.requestContext`, give it the `handler` that fills it, and name it in [`defineConfig`](/docs/reference/define-config). Handlers read them under `requestContext`, keyed by name. See the [Request Context guide](/docs/request-context) for the full walkthrough.
A declaration that reads no headers takes the context schema on its own:
```ts title="request-context.ts"
export const logger = k
.requestContext(
z.object({
requestId: z.string(),
})
)
.handler(() => ({
requestId: crypto.randomUUID(),
}));
```
A declaration can also read request `headers`. They stay off the routes and out of the OpenAPI document, and the clients type them, so a caller sets them once and the resolver reads them validated.
```ts title="request-context.ts"
import { z } from 'zod';
import { k } from './k';
export const analytics = k
.requestContext({
headers: z.object({
'x-posthog-session-id': z.string().optional(),
}),
context: z.object({
sessionId: z.string().nullable(),
}),
})
.handler(({ headers }) => ({
sessionId: headers['x-posthog-session-id'] ?? null,
}));
```
```ts title="kizuna.config.ts"
import { analytics } from './src/request-context';
export default defineConfig({
adapter: expressAdapter(),
routes,
requestContext: {
analytics,
},
});
```
```ts title="users.ts"
listUsers: k.route({ ... }).handler(({ query, requestContext }) => {
track(requestContext.analytics.sessionId, 'listUsers');
// ...
}),
```
## Sending values from a client
The fetch client takes the declared headers under `requestContext` and sends them with every request:
```ts title="src/lib/api-client.ts"
import { createClient } from './api-client.generated';
export const apiClient = createClient({
baseUrl: 'https://api.example.com',
requestContext: {
'x-posthog-session-id': sessionId,
},
});
```
The Swift and Kotlin clients take a `RequestContext` in their initializer:
```swift title="APISetup.swift"
let client = APIClient(
baseURL: url,
requestContext: .init(
xPosthogSessionId: sessionId
)
)
```
```kotlin title="APISetup.kt"
val client = APIClient(
baseUrl = baseUrl,
requestContext = APIClient.RequestContext(
xPosthogSessionId = sessionId
)
)
```
Resolvers run on every route, public ones included, before the guards, which read their values too, and never deny a request. They receive the adapter's native request objects, the route's `params`, and the declared `headers` (validated). The return is checked against the `context` schema. Request context never appears in the OpenAPI document.
---
# k.route
Source: /docs/reference/k-route
---
title: k.route
description: Define one route and the handler that answers it, with inputs, auth and the return all typed from the route.
---
`k.route(definition)` takes a route and hands back its handler. `body`, `params`, `query` and `headers` are typed from what the route declares, and the return is checked against its `responses`.
```ts title="users/create-user.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../k';
import { UserSchema } from './schemas';
export const createUser = k
.route({
method: 'POST',
path: '/users',
auth: 'user',
body: z.object({
name: z.string().min(1),
email: z.email(),
}),
responses: {
201: UserSchema,
400: ProblemDetailsSchema,
},
})
.handler(async ({ body }) => ({
status: 201,
body: await db.users.create(body),
}));
```
Group routes with [`k.routes`](/docs/reference/k-routes), which takes the routes `k.route` returns:
```ts title="users/index.ts"
import { k } from '../k';
import { createUser } from './create-user';
import { getUser } from './get-user';
export const usersRoutes = k.routes.users({
createUser,
getUser,
});
```
## Fields
Every field of a route definition, plus `auth`. See [`k.routes`](/docs/reference/k-routes) for the rest.
| Field | Required | Description |
| ------ | ---------------------------- | ------------------------------------- |
| `auth` | Once an identity is declared | What the route requires of its caller |
### `auth`
| Value | Meaning |
| --------------------------------- | ---------------------------------------- |
| `false` | Public |
| `'member'` | Requires the `member` identity, any role |
| `['user', 'member']` | Either identity |
| `{ identity, roles?, requires? }` | The same, narrowed |
`defineConfig` resolves it onto the route's `security`, `roles` and `requires`, which the OpenAPI document and the generated clients read. A role or permission the route names must be one the identity declares, so a typo does not compile.
An instance that declares no identities has nothing to state, so `auth` is optional there and every route is public.
## Nothing runs at import
`kizuna generate` imports your route files to read them, so whatever a module does at the top level, it does on every generate. Importing a database client is fine. Opening a connection, reading a file, or throwing on a missing environment variable is not, so keep that inside the handler.
## Reference
- [`k.routes`](/docs/reference/k-routes)
- [`defineConfig`](/docs/reference/define-config)
- [Access control](/docs/access-control)
---
# k.routes
Source: /docs/reference/k-routes
---
title: k.routes
description: Declare routes into one of your groups, with full path-param and response checking.
---
`k.routes.(routes)` declares routes into a group from [`k.groups`](/docs/reference/k-groups). Reach a nested group through its parents, `k.routes.workspaces.members(...)`. TypeScript completes every group your `Config` carries. Call `k.routes(routes)` for routes in no group.
A route's key is its group's path, then its place inside the call: `listUsers` below is `users.listUsers`. Pass what `k.routes` returns to `defineConfig` as a list, `routes: [usersRoutes, healthRoutes]`. A call declared into a group can't be nested inside another call, since its key already comes from its group.
```ts title="users.ts"
import { z } from 'zod';
import { k } from './k';
export const usersRoutes = k.routes.users({
listUsers: k
.route({
method: 'GET',
path: '/users',
query: z.object({
page: z.number().int().min(1).default(1),
limit: z.number().int().min(1).max(100).default(10),
}),
responses: {
200: z.object({
users: z.array(UserSchema),
total: z.number(),
}),
},
})
.handler(/* ... */),
createUser: k
.route({
method: 'POST',
path: '/users',
body: z.object({
name: z.string().min(1),
email: z.email(),
}),
responses: {
201: UserSchema,
400: ProblemDetailsSchema,
},
})
.handler(/* ... */),
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(/* ... */),
});
```
## Route definition fields
| Field | Required | Type |
| -------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------- |
| `method` | Yes | `'GET'` `'POST'` `'PUT'` `'PATCH'` `'DELETE'` `'HEAD'` `'OPTIONS'` |
| `path` | Yes | URL path. Use `:name` for path parameters |
| `pathParams` | No | Zod schema for the path parameters, keyed by placeholder name |
| `body` | No | Zod schema for the request body |
| `query` | No | Zod schema for the query string |
| `headers` | No | Zod schema for request headers |
| `responses` | Yes | Response schemas keyed by status code. A schema, `{ body, headers?, contentType? }`, or `{ stream, headers?, contentType? }` |
| `contentType` | No | `'application/json'` (default), `'multipart/form-data'`, `'application/x-www-form-urlencoded'` |
| `summary` | No | Short description shown in OpenAPI |
| `description` | No | Longer description shown in OpenAPI |
| `externalDocs` | No | `{ url, description? }`, emitted on the operation |
| `groups` | No | More groups to list the route under, as dotted paths from [`k.groups`](/docs/reference/k-groups) |
| `deprecated` | No | `boolean \| string \| { message?, date?, link? }`, see [Deprecations](/docs/deprecations) |
| `sunset` | No | `string \| { date, link? }`, see [Deprecations](/docs/deprecations) |
| `rawBody` | No | `true` to receive the unparsed body as `rawBody` beside `body`, see [Routes](/docs/routes#verifying-signed-requests) |
| `hidden` | No | `true` to leave it out of the generated clients and the OpenAPI document, see [Routes](/docs/routes#hidden-routes) |
Use the `{ body, headers?, contentType?, cache?, etag? }` form of a response to declare [typed response headers](/docs/routes#response-schemas), a [binary body](/docs/reference/binary-and-file-schemas), or a [cache policy and entity tag](/docs/caching). Use `{ stream, headers?, contentType? }` to send the response piece by piece, see [Streaming](/docs/streaming).
A route's `security` is resolved from its [`auth`](/docs/reference/k-route); writing it here is a type error.
## Validation
`pathParams` keys must be exactly the `:name` placeholders in `path`. A mismatch is a type error on `pathParams`, and `k.routes` throws on it at runtime.
`defineConfig` throws on a route in a group its `groups` does not declare, and on two routes that claim the same key. `k.routes` also throws on:
- an empty `z.object({})` as a `body`
- any `z.coerce` schema, anywhere in the route
- a structured path parameter (object, array, record, tuple, map, or set)
- a `stream` on a `4xx` or `5xx` status, beside a `body`, or on a `HEAD` route
- a `stream` whose schema does not fit its `contentType`: a `text/*` type takes `z.string()`, any other non-JSON type takes `BinarySchema`
- a `stream` event name that is empty or contains a line break
---
# Kizuna.brand
Source: /docs/reference/kizuna-brand
---
title: Kizuna.brand
description: Give a Zod schema a brand so the handler and every generated client type its values as that brand.
---
Give a Zod schema a brand, so the handler and every generated client type its values as that brand.
```ts
import { Kizuna } from 'kizunajs';
```
## Parameters
```ts
Kizuna.brand(brand: string, schema: ZodType): ZodType
```
| Parameter | Type | Description |
| --------- | --------- | -------------------------------------------------------- |
| `brand` | `string` | The name used in generated output (`UserId`, `CenterId`) |
| `schema` | `ZodType` | A string, number, bigint, boolean or date schema |
## Returns
The schema with `.brand()` applied and the brand recorded in its metadata. It validates exactly as `schema` does.
## Example
```ts title="user-id.ts"
import { Kizuna } from 'kizunajs';
import { z } from 'zod';
export const UserId = Kizuna.brand('UserId', z.string());
```
## Why not `.brand()`
Zod's `.brand()` exists only in the types, so the generators cannot see it. `Kizuna.brand` also records the name in `.meta()`, which they read.
## Effect on generators
- **TypeScript**: `export type UserId = string & $brand<"UserId">` in the `API` namespace, and a `toUserId('usr_k7f3q9')` function beside `createClient`
- **Swift**: `public struct UserId: RawRepresentable, Codable, Hashable, Sendable`, encoded as the bare value
- **Kotlin**: `@Serializable @JvmInline value class UserId(val value: String)`, serialized as the bare value
- **OpenAPI**: `x-kizuna-brand: UserId` on the schema
- **MCP**: nothing, a tool's input stays a plain string
A brand wraps a scalar, so `Kizuna.brand` throws on an object, an enum or a transform. Put `.optional()` or `.nullable()` on the brand rather than inside it:
```ts
parentId: UserId.nullable(),
```
See the [Zod guide](/docs/zod#branded-ids) for using one in each client.
---
# Kizuna.model
Source: /docs/reference/kizuna-model
---
title: Kizuna.model
description: Give a Zod schema a name so the OpenAPI document and every generated client produce named types instead of inline definitions.
---
Give a Zod schema a name, so the OpenAPI document and every generated client emit a named type for it.
```ts
import { Kizuna } from 'kizunajs';
```
## Parameters
```ts
Kizuna.model(options: ModelOptions): ZodType
```
| Option | Type | Required | Description |
| ------------- | --------- | -------- | --------------------------------------------------------- |
| `title` | `string` | Yes | The name used in generated output (`User`, `Event`, etc.) |
| `description` | `string` | No | Description included in the OpenAPI spec |
| `schema` | `ZodType` | Yes | The Zod schema defining the shape and validation |
## Returns
The Zod schema with metadata attached, usable anywhere a Zod schema is.
## Example
```ts title="users.ts"
import { Kizuna } from 'kizunajs';
import { z } from 'zod';
export const UserSchema = Kizuna.model({
title: 'User',
description: 'A user in the system',
schema: z.object({
id: z.string(),
name: z.string(),
email: z.email(),
}),
});
```
## Effect on generators
With `Kizuna.model`:
- **OpenAPI**: the schema is extracted into `components.schemas.User` and every usage becomes a `$ref` reference
- **TypeScript**: the schema becomes `export type User` in the `API` namespace, and every route that uses it references the name
- **Swift**: an object becomes `public struct User`, a `z.enum` becomes `public enum EventKind`, and a `z.discriminatedUnion` becomes an enum with one case per branch, shared across all routes that reference it
- **Kotlin**: an object becomes `@Serializable data class User`, a `z.enum` becomes `enum class EventKind`, and a `z.discriminatedUnion` becomes a sealed class, shared across all routes that reference it
## Extracting TypeScript types
Export a type alongside the schema with `z.infer`:
```ts title="types.ts"
export type User = z.infer;
```
See the [Routes guide](/docs/routes#naming-schemas-with-models) for more details.
---
# Kizuna.permissions
Source: /docs/reference/kizuna-permissions
---
title: Kizuna.permissions
description: Declare every permission an API has, for roles to hold and routes to require.
---
The least settled part of kizuna. `Kizuna.permissions` may change shape, move elsewhere, or be removed while v2 is in beta. Pin your version, and expect to rewrite what you build on it.
`Kizuna.permissions(catalog)` declares every permission that exists, grouped by what it acts on. [Roles](/docs/reference/kizuna-roles) are built from it, routes name what they require from it, and nothing outside it can be required or held.
```ts title="permissions.ts"
import { Kizuna } from 'kizunajs';
export const permissions = Kizuna.permissions({
workspace: ['read', 'update', 'delete'],
project: ['create', 'read', 'update', 'delete', 'share'],
invite: ['send', 'cancel', 'accept'],
});
```
| Property | Description |
| --------------------- | ---------------------------------------------------------- |
| `permissions.catalog` | The catalog as declared. |
| `permissions.names` | Every permission as `resource:verb`. |
| `permissions.schema` | A zod enum of `names`, for a body that sends a permission. |
Pass it to [`Kizuna.roles`](/docs/reference/kizuna-roles) to build roles that hold permissions. See [Access Control](/docs/access-control).
---
# Kizuna.roles
Source: /docs/reference/kizuna-roles
---
title: Kizuna.roles
description: Declare the roles callers hold, as names or built from a permission catalog.
---
The least settled part of kizuna. `Kizuna.roles` may change shape, move elsewhere, or be removed while v2 is in beta. Pin your version, and expect to rewrite what you build on it.
`Kizuna.roles(names)` declares the roles callers hold:
```ts title="roles.ts"
import { Kizuna } from 'kizunajs';
export const roles = Kizuna.roles(['member', 'admin', 'owner']);
```
Put them on the identity whose callers hold them, under `roles`. Its guard returns `role`, one name or an array of them, and a route's `roles` in its [`auth`](/docs/reference/k-route) is checked against it before the handler runs.
| Property | Description |
| -------------- | ---------------------------------------------------------------------- |
| `roles.names` | The role names, in declaration order. |
| `roles.schema` | A zod enum of the names, for a response that tells a client who it is. |
## From a permission catalog
`Kizuna.roles(permissions, definitions)` builds the roles from a [permission catalog](/docs/reference/kizuna-permissions), so a route can name the permission it requires instead of the role. Every entry is checked against the catalog, and `'all'` means every permission declared:
```ts title="roles.ts"
export const roles = Kizuna.roles(permissions, {
member: {
workspace: ['read'],
project: ['read', 'update'],
},
admin: {
workspace: ['read', 'update'],
project: ['create', 'read', 'update', 'delete', 'share'],
},
owner: 'all',
});
```
A route's `requires` is checked against what the caller's role holds, or the subset the guard returns as `permissions`, and the handler reads the list under `auth.member.permissions`.
| Property | Description |
| ----------------------------- | --------------------------------------------------------------- |
| `roles.permissions` | The catalog the roles are built from. |
| `roles.definitions` | Each role and what it holds, as declared. |
| `roles.of(role)` | What one role holds, or the union for several. |
| `roles.holds(role, requires)` | Whether the role holds every permission in `requires` outright. |
See [Access Control](/docs/access-control) for the walkthrough.
---
# new KizunaTanstackQuery()
Source: /docs/reference/kizuna-tanstack-query
---
title: new KizunaTanstackQuery()
description: Build TanStack Query options from a Kizuna fetch client.
---
The TanStack Query client is new and still settling. Its API surface may change while v2 is in beta, so pin your version if you depend on it.
Build TanStack Query options from your routes. See the [TanStack Query guide](/docs/clients/tanstack-query) for usage.
```ts
import { KizunaTanstackQuery } from '@kizunajs/tanstack-query';
```
## Parameters
```ts
new KizunaTanstackQuery(client: Client): KizunaQueryProxy
```
| Parameter | Type | Description |
| --------- | -------- | ------------------------------------------------------------------------ |
| `client` | `Client` | A [fetch client](/docs/clients/fetch), from the generated `createClient` |
Every client method carries the route it answers, so nothing else is needed: each route's `method` decides which factories it gets, and its `responses` decide which statuses are data.
## Returns
An object mirroring your route groups.
**`GET` and `HEAD` routes**
| Factory | Description |
| -------------------------- | ----------------------------------------------------- |
| `queryOptions(options)` | For `useQuery`, `useSuspenseQuery`, `prefetchQuery` |
| `infiniteOptions(options)` | For `useInfiniteQuery`, `prefetchInfiniteQuery` |
| `queryKey({ input })` | The query's full key |
| `infiniteKey({ input })` | The infinite query's full key |
| `key()` | The partial key matching every operation on the route |
| `call(args)` | Calls the route, bypassing the cache |
**Every other method**
| Factory | Description |
| -------------------------- | ---------------------------------- |
| `mutationOptions(options)` | For `useMutation` |
| `mutationKey()` | The mutation's full key |
| `key()` | The partial key matching the route |
| `call(args)` | Calls the route |
**Routes whose response [streams](/docs/streaming)**, whatever their method
| Factory | Description |
| ------------------------ | ----------------------------------------------------------------------------------------- |
| `streamOptions(options)` | For `useQuery`, over `experimental_streamedQuery`. `data` is the messages received so far |
| `streamKey({ input })` | The stream query's full key |
| `key()` | The partial key matching the route |
| `call(args)` | Calls the route, returning the async iterable |
**Groups and the root** carry `key()`. Where a route is named the same as a factory, the route wins.
## Options
| Option | Type | Description |
| ------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------- |
| `input` | `Args \| SkipToken` | What the client method takes: `{ params, query, body, headers, fetchOptions }`. Optional when every argument is optional. |
| … | TanStack Query options | Passed through untouched |
For `infiniteOptions`, `input` is a function of the page parameter. `skipToken` disables the query. `streamOptions` also takes `refetchMode`, `'reset'` (default), `'append'`, or `'replace'`.
## Query keys
```ts
type KizunaQueryKey = readonly [readonly string[], { input?: unknown; type: 'query' | 'infinite' | 'stream' }];
type KizunaPathKey = readonly [readonly string[]];
```
Segments are the route's path through your routes, so `api.users.key()` prefixes every key under `users`. `fetchOptions` is stripped from the input first.
## Errors
Declared statuses come back as data. Anything else throws [`UndeclaredResponseError`](/docs/reference/is-undeclared-response-error). A streamed route that answers a declared status other than its stream throws `NonStreamResponseError`, narrowed with `isNonStreamResponseError`.
## Example
```ts
import { useQuery } from '@tanstack/react-query';
import { KizunaTanstackQuery } from '@kizunajs/tanstack-query';
import { apiClient } from './api-client';
const api = new KizunaTanstackQuery(apiClient);
const { data } = useQuery(
api.users.listUsers.queryOptions({
input: {
query: {
page: 1,
limit: 10,
},
},
staleTime: 60_000,
})
);
```
## See also
- [TanStack Query client](/docs/clients/tanstack-query)
- [`createClient()`](/docs/reference/create-client)
- [`isUndeclaredResponseError`](/docs/reference/is-undeclared-response-error)
---
# new Kizuna()
Source: /docs/reference/kizuna
---
title: new Kizuna()
description: The authoring surface for one API, typed by the Config that kizuna generate writes.
---
`new Kizuna()` is what you declare routes with. It takes nothing at runtime: its type parameter is the `Config` generated from your `kizuna.config.ts`, and that is what types everything a handler receives and checks every name you write.
Keep the instance as `k`, usually in `src/k.ts`, and import it wherever you declare.
```ts title="src/k.ts"
import { Kizuna } from 'kizunajs';
import type { Config } from '../kizuna.types';
export const k = new Kizuna();
```
## What it gives you
| Member | Signature | Description |
| ------------------ | ---------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------- |
| `k.route` | `(definition) => RouteBuilder` | Declare one route and the [`handler`](/docs/reference/k-route) that answers it. |
| `k.routes` | `.(routes) => Routes` | File [routes](/docs/reference/k-routes) into one of your groups. |
| `k.groups` | `(groups) => GroupSet` | Declare the [groups](/docs/reference/k-groups) routes are filed under. |
| `k.identity` | `.bearer`, `.apiKey`, `.basic`, `.oauth2`, `.openIdConnect`, `.custom` | Declare an [identity](/docs/reference/k-identity) and the `guard` that authenticates it. |
| `k.requestContext` | `(config) => RequestContextBuilder` | Declare a [request-scoped value](/docs/reference/k-request-context) and the `handler` that fills it. |
| `k.job` | `(definition) => JobBuilder` | Declare one job and the handler that runs it. |
| `k.jobs` | `(identity, definitions) => Jobs` | Group [jobs](/docs/reference/k-jobs) and name the identity they require. |
| `k.issue` | `(ctx, issue) => void` | Raise a [typed validation code](/docs/reference/k-issue) inside a Zod refinement. |
## Statics
Some declarations are shared across APIs rather than bound to one, so they stay on the class:
| Member | Description |
| -------------------- | ----------------------------------------------------------------------------------- |
| `Kizuna.model` | Name a [schema](/docs/reference/kizuna-model) so every client reuses one type. |
| `Kizuna.brand` | [Brand](/docs/reference/kizuna-brand) a schema, so no other value stands in for it. |
| `Kizuna.permissions` | Declare a [permission catalog](/docs/reference/kizuna-permissions). |
| `Kizuna.roles` | Declare the [roles](/docs/reference/kizuna-roles) callers hold. |
## What Config carries
`kizuna.types.ts` is written by `kizuna generate` from your config. Every name you write against `k` is checked against it, and everything a handler receives comes from it.
```ts title="kizuna.types.ts"
export interface Config {
adapter: ReturnType;
groups: typeof groups;
auth: {
identities: {
user: typeof user;
member: typeof member;
};
};
requestContext: {
analytics: typeof analytics;
};
validation: {
issueCodes: 'invalid_phone_number';
};
jobs: typeof jobs;
}
```
So a route's `auth` only accepts a declared identity, `k.routes.users(...)` only reaches a declared group, and a handler reads `auth.user`, `requestContext.analytics`, `jobs.indexUser` and your framework's own request without importing any of them.
## Example
```ts title="src/routes/users.ts"
import { z } from 'zod';
import { k } from '../k';
export const usersRoutes = k.routes.users({
getUser: k
.route({
method: 'GET',
path: '/users/:id',
auth: 'user',
responses: {
200: UserSchema,
},
})
.handler(async ({ params, auth, req }) => ({
status: 200,
body: await db.users.find(params.id, auth.user.userId),
})),
});
```
Assemble them with [`defineConfig`](/docs/reference/define-config). See the [Config guide](/docs/routes) for response schemas, deprecation, typed response headers, and nesting.
---
# mcpPlugin
Source: /docs/reference/mcp-plugin
---
title: mcpPlugin
description: Install an MCP (Model Context Protocol) endpoint so AI assistants can call your API as tools.
---
MCP support is new and still settling. The plugin options and the published tool surface may change while v2 is in beta, so pin your version if you depend on them.
Serve an [MCP (Model Context Protocol)](https://modelcontextprotocol.io) endpoint as part of your API. Name it under `plugins` on [`defineConfig`](/docs/reference/define-config) and `api.mount` serves it, on every adapter.
```ts
import { mcpPlugin } from '@kizunajs/mcp';
```
## Parameters
```ts
mcpPlugin(props?: McpPluginProps): PluginDeclaration
```
| Parameter | Type | Required | Description |
| --------- | ---------------- | -------- | --------------------- |
| `props` | `McpPluginProps` | No | Configuration options |
## Props
| Option | Default | Description |
| -------------- | ---------------------- | ----------------------------------------------------------------------------- |
| `slug` | `'mcp'` | What handlers reach this plugin under |
| `path` | `'/mcp'` | Path the endpoint is served from |
| `name` | `'MCP Server'` | Human-readable name shown to AI assistants |
| `version` | `'1.0.0'` | Semantic version string |
| `instructions` | built from your groups | Appended to the generated overview |
| `oauth` | off | Serve the endpoint as an OAuth 2.1 resource server ([guide](/docs/mcp#oauth)) |
## Which routes it publishes
The plugin takes no list of routes. Each route decides for itself, by declaring [`tool`](/docs/tools):
```ts title="src/routes/weather.ts"
getForecast: k
.route({
method: 'GET',
path: '/forecast/:city',
summary: 'Look up tomorrow forecast for one city',
tool: true,
responses: {
200: ForecastSchema,
},
})
.handler(/* ... */),
```
A route with no `tool` is an HTTP endpoint and nothing more. Two shapes never publish even with it: a route whose `contentType` is `multipart/form-data` or `application/x-www-form-urlencoded`, because tool input is JSON, and a route whose response [streams](/docs/streaming), because a tool result is one value. A [hidden](/docs/routes#hidden-routes) route can't say `tool`: the two together are a type error.
## Example
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { mcpPlugin } from '@kizunajs/mcp';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
mcpPlugin({
name: 'My API',
}),
],
});
```
```ts title="src/index.ts"
import kizuna from '../kizuna.config';
kizuna.api.mount(app);
```
## Next.js
The endpoint is served by the catch-all route file that already serves your routes, so `path` resolves under its `basePath`:
```ts title="src/app/api/[...kizuna]/route.ts"
export const { GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS } = kizuna.api.mount({
basePath: '/api',
});
```
With the default `path`, the endpoint is at `/api/mcp`.
## Secured routes
Each tool call runs the same [guard](/docs/reference/k-identity) pipeline as an HTTP request, reading credentials from the MCP transport request's headers. A `deny(...)` becomes a tool error result; with [`oauth`](/docs/mcp#oauth) configured, denials from that identity answer at the HTTP level instead. See the [MCP guide](/docs/mcp) for configuring clients to send credentials.
## Plugin route
The endpoint is a [plugin route](/docs/extend/create-plugin#routes), which is hidden, so your fetch client, the OpenAPI document, and the generated Swift and Kotlin clients never list it.
## See also
- [Tools](/docs/tools) for what a route's `tool` declares
- [`createMcpServer`](/docs/reference/create-mcp-server) to drive the transport yourself
---
# openApiPlugin
Source: /docs/reference/openapi-plugin
---
title: openApiPlugin
description: Serve your OpenAPI document and an API reference UI for it, on any adapter.
---
Write the OpenAPI document generated from your API on `kizuna generate`, and serve it with a reference UI. Name it under `plugins` on [`defineConfig`](/docs/reference/define-config) and `api.mount` serves its routes. See the [OpenAPI guide](/docs/openapi).
```ts
import { openApiPlugin } from '@kizunajs/openapi';
```
## Parameters
```ts
openApiPlugin(props: OpenApiPluginProps): PluginDeclaration
```
| Parameter | Type | Required | Description |
| --------- | -------------------- | -------- | ---------------------------------------------------------------------------------------------- |
| `props` | `OpenApiPluginProps` | Yes | Everything [`generateOpenApi`](/docs/reference/generate-openapi) takes, plus the options below |
## Props
`OpenApiPluginProps` extends `GenerateOpenApiOptions`, so `info`, `servers`, `setOperationId` and the rest work exactly as they do on `generateOpenApi`. On top of those:
| Option | Default | Description |
| --------------- | ------------------ | -------------------------------------------------------- |
| `slug` | `'openApi'` | What handlers reach this plugin under |
| `output` | none | Where `kizuna generate` writes the document |
| `includeHidden` | `false` | Document [hidden](/docs/routes#hidden-routes) routes too |
| `docsPath` | off | The reference UI. Give it a path to serve it |
| `jsonPath` | off | The document. A path ending in `.json` |
| `yamlPath` | off | The document as YAML. A path ending in `.yaml` |
| `provider` | `'scalar'` | Which reference UI to render, `'scalar'` or `'swagger'` |
| `cdnUrl` | the provider's CDN | Where to load the UI's assets from |
| `pageTitle` | the document title | The page's `` |
| `configuration` | none | Extra config merged into the UI's initializer |
They are also the options [`generateOpenApi`](/docs/reference/generate-openapi) uses when you call it without any, so a build step and the served document cannot disagree.
Each path prop is off until you give it a path. The document paths carry their extension in the type, so `jsonPath: '/docs'` does not compile.
## Example
```ts title="kizuna.config.ts"
import { defineConfig } from 'kizunajs';
import { expressAdapter } from '@kizunajs/express';
import { openApiPlugin } from '@kizunajs/openapi';
import { routes } from './src/routes';
export default defineConfig({
adapter: expressAdapter(),
routes,
plugins: [
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
docsPath: '/docs',
setOperationId: true,
}),
],
});
```
```ts title="src/index.ts"
import kizuna from '../kizuna.config';
kizuna.api.mount(app);
```
## Two documents
A plugin installs once, so a second document goes under `documents`. Each entry takes the same options as the plugin, and the plugin's own values are its defaults:
```ts title="kizuna.config.ts"
openApiPlugin({
info: {
title: 'My API',
version: '1.0.0',
},
documents: [
{
output: './openapi.yaml',
docsPath: '/docs',
},
{
info: {
title: 'My API, internal',
version: '1.0.0',
},
output: './openapi.internal.yaml',
docsPath: '/internal/docs',
includeHidden: true,
},
],
}),
```
## Plugin routes
These are [plugin routes](/docs/extend/create-plugin#routes) marked `hidden`, so your fetch client, the generated Swift and Kotlin clients, and the document itself never list them.
## Public by default
Nothing guards these routes. Gate them with your framework's own middleware if your document should not be public.
## Air-gapped and strict CSP
`cdnUrl` points the page at a self-hosted copy of the UI's assets. For `'scalar'` it is the script URL; for `'swagger'` it is the directory holding `swagger-ui.css` and `swagger-ui-bundle.js`.
## Serving it yourself
[`generateOpenApi`](/docs/reference/generate-openapi) is exported, so you can skip the plugin and serve the document from your own route. Mixing works: leave a path unset and the plugin stays off it. Set `jsonPath` but not `docsPath` to serve the document while rendering your own UI.
---
# ProblemDetailsSchema
Source: /docs/reference/problem-details-schema
---
title: ProblemDetailsSchema
description: RFC 9457 Problem Details error response schema (ProblemDetailsSchema) used across kizuna.
---
The standard [RFC 9457 Problem Details](https://www.rfc-editor.org/rfc/rfc9457) error response shape used by kizuna. Matches the format produced by [`deny()`](/docs/reference/k-identity) in guards and all built-in error responses (404, 405, 415, etc.).
```ts
import { ProblemDetailsSchema } from 'kizunajs/schemas';
```
## Shape
```json
{
"type": "about:blank",
"title": "Not Found",
"status": 404,
"detail": "User not found"
}
```
| Field | Description |
| -------- | --------------------------------------------------------------------------------------- |
| `type` | Problem type URI. `about:blank` means "no additional semantics beyond the status code." |
| `title` | Short human-readable summary matching the HTTP status phrase. |
| `status` | HTTP status code. |
| `detail` | Human-readable explanation specific to this occurrence. |
## Usage in routes
Use `ProblemDetailsSchema` in a route's `responses` to document error status codes:
```ts title="src/routes/users.ts"
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from './k';
const usersRoutes = k.routes.users({
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(/* ... */),
});
```
A route whose [`auth`](/docs/access-control) names an identity gets `401` and `403` as Problem Details. See [what it drives](/docs/authentication#what-it-drives).
## Usage in handlers
Handlers supply `detail`; `type`, `title`, and `status` are filled in:
```ts title="src/routes/users.ts"
getUser: k
.route({
method: 'GET',
path: '/users/:id',
responses: {
200: UserSchema,
404: ProblemDetailsSchema,
},
})
.handler(({ params, throwError }) => {
const user = userStore.get(params.id);
if (!user) {
return throwError({
status: 404,
body: {
detail: 'User not found',
},
});
}
return {
status: 200,
body: user,
};
}),
```
The client receives the full envelope shown under [Shape](#shape).
## Extension members
RFC 9457 lets a problem carry extra fields, called **extension members**, alongside the standard envelope. `ProblemDetailsSchema` is a plain Zod object schema, so add them with `.extend()`:
```ts title="src/routes/users.ts"
import { z } from 'zod';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
import { k } from '../k';
const users = k.routes.users({
createUser: k
.route({
method: 'POST',
path: '/users',
body: CreateUserSchema,
responses: {
201: UserSchema,
409: ProblemDetailsSchema.extend({
conflictingId: z.string(),
}),
},
})
.handler(/* ... */),
});
```
To reuse the extended schema across routes, and give it a name in the generated OpenAPI spec, wrap it in [`Kizuna.model`](/docs/reference/kizuna-model):
```ts title="src/routes/users.ts"
import { z } from 'zod';
import { Kizuna } from 'kizunajs';
import { ProblemDetailsSchema } from 'kizunajs/schemas';
const ConflictError = Kizuna.model({
title: 'ConflictError',
schema: ProblemDetailsSchema.extend({
conflictingId: z.string(),
}),
});
// responses: { 409: ConflictError }
```
The handler supplies `detail` plus the declared extensions:
```ts title="src/routes/users.ts"
return throwError({
status: 409,
body: {
detail: 'A user with that email already exists',
conflictingId: existing.id,
},
});
```
```json
{
"type": "about:blank",
"title": "Conflict",
"status": 409,
"detail": "A user with that email already exists",
"conflictingId": "usr_abc123"
}
```
Extension members are how you preserve an existing API's error fields when moving onto kizuna. See [Migrating an existing API](/docs/migration/existing-api).
## Checking for a Problem Details body
`isProblemDetails` is a type guard for the shared error shape, the sibling of [`isValidationError`](/docs/reference/is-validation-error):
```ts title="lib/users.ts"
import { isProblemDetails } from 'kizunajs';
if (isProblemDetails(response.body)) {
console.error(`${response.body.status}: ${response.body.detail}`);
}
```
## The rule
Every response with status `>= 400` must be Problem Details, and the type system enforces it. For extra fields, use extension members. For an error that isn't JSON, such as proxying an upstream body or an HTML error page, use the adapter's `raw-response` escape hatch.
## Migrating to a legacy wire shape
Adapters accept a `formatError` option to reshape the outgoing bytes for clients that can't move to Problem Details yet. It receives the request, so during a transition you serve the legacy shape to old clients and Problem Details to new ones, branching on whatever signal your API has:
```ts title="src/index.ts"
api.mount(app, {
formatError: (problem, { request }) => {
// new clients opt in via a signal you control, here a version header
if (request.headers.get('x-api-version') === '2') {
return { contentType: 'application/problem+json', body: problem };
}
// old clients keep the legacy shape
return {
contentType: 'application/json',
body: { ok: false, error: { code: problem.status, message: problem.detail } },
};
},
});
```
The input is always the canonical problem; only the outgoing bytes change, so what you declared stays Problem Details. Reach for it when extension members can't reproduce the old body. See [Migrating an existing API](/docs/migration/existing-api).
## What produces it
| Source | Example |
| ---------------------- | ------------------------------------------------------ |
| Guards (`deny`) | `deny({ status: 403, body: { detail: 'Forbidden' } })` |
| Route not found | 404 for unmatched paths |
| Method not allowed | 405 with `Allow` header |
| Unsupported media type | 415 for wrong `Content-Type` |
| Handler errors | 500 for unhandled exceptions |
All built-in error responses use `application/problem+json` as the content type.
## OpenAPI
`ProblemDetailsSchema` is a named model, so it appears as `ProblemDetails` in the generated OpenAPI spec under `components/schemas`, keeping your API documentation clean and consistent.
---
# ProtectedResourceMetadataSchema
Source: /docs/reference/protected-resource-metadata-schema
---
title: ProtectedResourceMetadataSchema
description: RFC 9728 Protected Resource Metadata schema, builder, and challenge formatting.
---
The [RFC 9728 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728) document an OAuth 2.0 protected resource serves at `/.well-known/oauth-protected-resource`. It tells clients which authorization servers issue tokens for the resource.
```ts
import { ProtectedResourceMetadataSchema } from 'kizunajs/schemas';
```
## Shape
```json
{
"resource": "https://api.example.com",
"authorization_servers": ["https://auth.example.com"],
"scopes_supported": ["users:read"],
"bearer_methods_supported": ["header"]
}
```
| Field | Description |
| -------------------------- | ------------------------------------------------------------------------- |
| `resource` | Canonical URI of the resource, the RFC 8707 audience tokens are bound to. |
| `authorization_servers` | Issuer URLs of the authorization servers that mint tokens for it. |
| `scopes_supported` | Baseline scopes a client requests before any per-operation challenge. |
| `bearer_methods_supported` | How the resource accepts bearer tokens. Kizuna always answers `header`. |
It is a plain Zod object schema. To name it in a generated OpenAPI spec, wrap it in [`Kizuna.model`](/docs/reference/kizuna-model).
## buildProtectedResourceMetadata
Builds the document from the resource's canonical URI and the identity whose authorization server it advertises. The `authorization_servers` entry is the identity's issuer (`issuer` on an `oauth2` identity, derived from `openIdConnectUrl` on an `openIdConnect` one) and `scopes_supported` is the flows' scope catalogue. Throws when the identity names no authorization server.
```ts
import { buildProtectedResourceMetadata } from 'kizunajs';
import { user } from './identities';
const metadata = buildProtectedResourceMetadata({
resource: 'https://api.example.com',
scheme: user,
});
```
## assertCanonicalResourceUri
Throws unless the value is a canonical resource URI per RFC 8707 section 2: absolute, no fragment. A query component is allowed.
```ts
import { assertCanonicalResourceUri } from 'kizunajs';
assertCanonicalResourceUri('https://api.example.com');
assertCanonicalResourceUri('/v1'); // throws
```
## authorizationServerIssuer and declaredScopes
The derivations behind the builder, exported for reading the identity directly. `authorizationServerIssuer` returns an `oauth2` identity's `issuer`, or derives it from an `openIdConnect` identity's `openIdConnectUrl`; `declaredScopes` collects the scopes an `oauth2` identity's flows declare. Both return `undefined` when the identity has nothing to say.
```ts
import { authorizationServerIssuer, declaredScopes } from 'kizunajs';
authorizationServerIssuer(user); // 'https://auth.example.com'
declaredScopes(user); // ['users:read', 'users:write']
```
## bearerChallenge
Formats the `WWW-Authenticate` header a resource server answers `401` and `403` with. Parameter values become RFC 9110 quoted strings, `undefined` parameters are omitted, and with none left the bare scheme remains.
```ts
import { bearerChallenge } from 'kizunajs/adapter';
bearerChallenge({
error: 'insufficient_scope',
scope: 'users:write',
resource_metadata: 'https://api.example.com/.well-known/oauth-protected-resource',
});
// Bearer error="insufficient_scope", scope="users:write", resource_metadata="..."
```