Featured image of post Introduction to full-stack WebAPI created with Next.js and HonoFeatured image of post Introduction to full-stack WebAPI created with Next.js and Hono

Introduction to full-stack WebAPI created with Next.js and Hono

Development revolution brought about by Next.js App Router × Hono

Next.js’ Route Handlers are powerful, but the complexity of boilerplate and type sharing that comes with increasing endpoints tends to be an issue.

By incorporating the web standards-compliant ultra-lightweight framework “Hono” into the API layer, you can easily create a sophisticated end-to-end, type-safe RPC (Remote Procedure Call) environment.


Step 1: Hono initialization with Catch-all Route

Place a wildcard route in App Router and delegate all /api/* to Hono.

// app/api/[[...route]]/route.ts
import { Hono } from 'hono';
import { handle } from 'hono/vercel';
import { zValidator } from '@hono/zod-validator';
import { z } from 'zod';

export const runtime = 'edge';
const app = new Hono().basePath('/api');

const routes = app.get('/users/:id',
  zValidator('param', z.object({ id: z.string() })),
  (c) => c.json({ id: c.req.valid('param').id, name: 'Alice' })
);

export type AppType = typeof routes;
export const GET = handle(app);

Step 2: Type-safe data fetching with hc

A major strength of Hono is that the server-side route definition (AppType) can be imported as a type on the client.

// クライアント側コンポーネント
import { hc } from 'hono/client';
import type { AppType } from '@/app/api/[[...route]]/route';

const client = hc<AppType>('http://localhost:3000');

export async function getUser(id: string) {
  const res = await client.api.users[':id'].$get({ param: { id } });
  return await res.json(); // 返り値の型が自動推論される
}

Three major points for production operation

  1. Using Edge Runtime: Minimize cold starts and achieve low latency.
  2. OpenAPI automatic generation: Completely automatically output documentation with @hono/zod-openapi.
  3. Error unification: Centrally manage error formats for all APIs with app.onError().