Skip to Content
hono-bento

Getting started

Install hono-bento and build your first feature, one file at a time.

This page builds a todos feature in the recommended layout, one file at a time, in a single package. When another app needs the schemas, the same code moves into a monorepo.

Start from a working app

hono-bento init writes a new app in that layout: an API with one notes feature, its schemas, its tests, and hono-bento check wired into them. Its data lives in memory, so there's nothing else to install:

bun x hono-bento init my-api

Pass --db prisma to keep the data in Postgres through Prisma instead, with a Docker Compose file for a local database and a Postgres schema per test run. Pass --monorepo to start with the schemas in a workspace package that other apps can import, and --scope @acme to name the workspace packages (it defaults to @ plus the folder's name). The app's AGENTS.md lists the layout's rules and the steps for adding an endpoint or a feature. The CLI has every option, and the add commands that grow the app.

For a bigger app to read, see the example monorepo. To build one by hand, read on.

Install

bun add hono-bento hono zod

hono and zod are peer dependencies. hono-bento needs Hono 4.11+ and Zod 4.

Build a feature

Write the schemas

A feature's schemas are its wire contract, so they get a folder of their own, src/schemas, that imports nothing from the app. Use z from hono-bento/zod: it's Zod with .openapi() added, for descriptions and examples in the generated docs.

Code imports them by name, as #schemas/todos, through a subpath import in package.json. Node, Bun, Deno, bundlers and TypeScript all resolve it, and moving the schemas into a shared package later only changes the name:

package.json
{
  "type": "module",
  "imports": { "#schemas/*": "./src/schemas/*.ts" }
}
src/schemas/todos.ts
import { z } from 'hono-bento/zod';

export const todoSchema = z
  .object({
    object: z.literal('todo'),
    id: z.string().openapi({ example: 'todo_a1b2c3' }),
    title: z.string(),
    done: z.boolean(),
  })
  .openapi('Todo');

export const todoListSchema = z
  .object({
    object: z.literal('list'),
    data: z.array(todoSchema),
    count: z.number().int(),
    has_more: z.boolean(),
  })
  .openapi('TodoList');

export const todoCreateSchema = z.object({
  title: z.string().min(1).openapi({ description: 'Short description of the task.' }),
});

export type Todo = z.infer<typeof todoSchema>;
export type TodoCreate = z.infer<typeof todoCreateSchema>;

Define who's calling

A strategy turns a request into your own identity type, or returns null if the request isn't for it. An authorizer decides whether that identity has a route's required scopes. Both are app-level code that every feature shares. See Authentication for the details.

src/auth.ts
import { type AuthStrategy, type Authorizer, HttpError } from 'hono-bento';

export interface Session {
  userId: string;
  role: 'admin' | 'editor' | 'viewer';
}

// Demo tokens, to start. Verify real ones here, with a JWT library or a sessions table.
const TOKENS: Record<string, Session> = {
  'demo-editor': { userId: 'u_1', role: 'editor' },
  'demo-viewer': { userId: 'u_2', role: 'viewer' },
};

const bearer: AuthStrategy<Session> = {
  name: 'bearer',
  authenticate(c) {
    const header = c.req.header('authorization');
    if (!header?.startsWith('Bearer ')) return null; // not this strategy
    const session = TOKENS[header.slice('Bearer '.length)];
    if (!session) throw HttpError.unauthorized('Invalid token.');
    return session;
  },
};

const ROLES: Record<Session['role'], string[]> = {
  admin: ['*'],
  editor: ['todos.read', 'todos.write'],
  viewer: ['todos.read'],
};

export const strategies = [bearer];

export const authorizer: Authorizer<Session> = {
  authorize(session, { scopes = [] }) {
    const granted = ROLES[session.role];
    return granted.includes('*') || scopes.every((scope) => granted.includes(scope));
  },
};

Declare the routes

spec.ts is the feature's routing table. Each route's contract says who may call it, what it accepts and what it returns for each status. It holds no logic. route() joins each contract to its handler, and defineSpec accepts nothing else.

src/features/todos/spec.ts
import { todoCreateSchema, todoListSchema, todoSchema } from '#schemas/todos';
import { contract, defineSpec, route } from 'hono-bento';

import { createTodo } from './create';
import { listTodos } from './list';

export const contracts = {
  list: contract({
    operation: 'list',
    method: 'get',
    path: '/',
    summary: 'List todos',
    auth: { scopes: ['todos.read'] },
    responses: { 200: { description: 'A list of todos.', schema: todoListSchema } },
  }),
  create: contract({
    operation: 'create',
    method: 'post',
    path: '/',
    summary: 'Create a todo',
    auth: { scopes: ['todos.write'] },
    validation: { body: todoCreateSchema },
    responses: { 201: { description: 'The created todo.', schema: todoSchema } },
  }),
};

export const spec = defineSpec({
  basePath: '/v1/todos',
  name: 'Todos',
  collection: 'todos',
  routes: [route({ ...contracts.list, handler: listTodos }), route({ ...contracts.create, handler: createTodo })],
});

Routes require authentication unless they set auth: { allowAnonymous: true }, so leaving auth out never ships a public endpoint.

Write a handler per operation

Each route's handler gets its own file, named after the route's operation. defineHandler<Session, typeof contracts.create> takes every argument type from the route's contract, so the handler restates nothing:

  • body is the request body after validation.body has parsed it, so the handler never sees invalid input;
  • respond(status, data) sends JSON, and only accepts the statuses the contract documents, with data matching their schemas;
  • identity is your Session, never null on an authenticated route.

Handlers stay thin: the feature's data access goes in its store.ts. This one keeps todos in memory; Database swaps it for Postgres.

src/features/todos/store.ts
import type { Todo, TodoCreate } from '#schemas/todos';

const todos: Todo[] = [];

export const store = {
  list: (): Todo[] => [...todos].reverse(),
  create(input: TodoCreate): Todo {
    const todo: Todo = {
      object: 'todo',
      id: `todo_${crypto.randomUUID().slice(0, 8)}`,
      title: input.title,
      done: false,
    };
    todos.push(todo);
    return todo;
  },
};
src/features/todos/create.ts
import { defineHandler } from 'hono-bento';

import type { Session } from '../../auth';
import type { contracts } from './spec';
import { store } from './store';

export const createTodo = defineHandler<Session, typeof contracts.create>(({ body, respond }) =>
  respond(201, store.create(body))
);
src/features/todos/list.ts
import { defineHandler } from 'hono-bento';

import type { Session } from '../../auth';
import type { contracts } from './spec';
import { store } from './store';

export const listTodos = defineHandler<Session, typeof contracts.list>(({ respond }) => {
  const data = store.list();
  return respond(200, { object: 'list', data, count: data.length, has_more: false });
});

The import type creates no runtime cycle with spec.ts. If a handler drifts from its route, route() reports what doesn't fit:

Type 'RouteHandler<Session, ...>' is not assignable to type 'HandlerMismatch<"The handler responds
with a status the route's responses don't document, or with data that doesn't match that status's schema.", ...>'.

List the feature and mount it

specs.ts is the only list of features. mountSpecs mounts each one at its basePath, and generateOpenApiDocument documents the same list.

src/specs.ts
import { spec as todos } from './features/todos/spec';

export const specs = [todos];
src/app.ts
import { Hono } from 'hono';
import { mountSpecs } from 'hono-bento';
import { generateOpenApiDocument } from 'hono-bento/openapi';

import { authorizer, strategies } from './auth';
import { specs } from './specs';

export const app = mountSpecs(new Hono(), specs, {
  strategies,
  authorizer,
  // Check every response against its documented schema while developing.
  validateResponses: process.env.NODE_ENV !== 'production',
});

const document = generateOpenApiDocument(specs, { info: { title: 'Todos API', version: '1.0.0' } });
app.get('/openapi.json', (c) => c.json(document));

Run it

Hono apps run on any runtime. With Bun:

src/server.ts
import { app } from './app';

export default { port: 3000, fetch: app.fetch };
bun run src/server.ts
curl localhost:3000/v1/todos -H 'Authorization: Bearer demo-viewer'

Next steps

On this page