Hono Adapter
The @zenstackhq/server/hono module provides a quick way to install a full set of CRUD API onto Hono apps. Combined with ZenStack's powerful access policies, you can achieve a secure data backend without manually coding it.
Installation​
- npm
- pnpm
- bun
- yarn
npm install @zenstackhq/server@next
pnpm add @zenstackhq/server@next
bun add @zenstackhq/server@next
yarn add @zenstackhq/server@next
Mounting the API​
You can use the createHonoHandler API to create a Hono middleware that handles CRUD requests automatically:
import { Context, Hono } from 'hono';
import { createHonoHandler } from '@zenstackhq/server/hono';
import { RPCApiHandler } from '@zenstackhq/server/api';
import { getSessionUser } from '~/auth';
import { client } from '~/db';
import { schema } from '~/zenstack/schema';
const app = new Hono();
app.use(
'/api/model/*',
createHonoHandler({
apiHandler: new RPCApiHandler({ schema }),
// getSessionUser extracts the current session user from the request,
// its implementation depends on your auth solution
getClient: (ctx) => client.$setAuth(getSessionUser(ctx)),
})
);
The middleware factory takes the following options to initialize:
-
getClient (required)
(ctx: Context) => ClientContract<Schema> | Promise<ClientContract<Schema>>
A callback for getting a ZenStackClient instance for talking to the database. Usually you'll return a client instance with access policy enabled and user identity bound.
-
apiHandler (required)
ApiHandler
The API handler instance that determines the API specification.
Error Handling​
Refer to the specific sections for RPC Handler and RESTful Handler.