Published on

Hono + Next.js

Authors
  • avatar
    Name
    Shelton Ma
    Twitter
  1. Install packages

    pnpm install hono 
    # Hono Validation https://hono.dev/docs/guides/validation
    pnpm install zod @hono/zod-validator
    
  2. Create basic route

    // src/app/api/[[...route]]/route.js
    import { Hono } from "hono";
    
    import { handle } from "hono/vercel";
    
    // Set "edge" if planning on planning with edge on Vercel
    // export const runtime = "nodejs";
    export const runtime = "edge";
    
    const app = new Hono().basePath("/api");
    
    export const GET = handle(app);
    export const POST = handle(app);
    export const PATCH = handle(app);
    export const DELETE = handle(app);
    
  3. Create variable route

    // src/app/api/[[...route]]/hello.ts
    import { Hono } from "hono";
    const app = new Hono().get("/", (c) => {
      return c.json({ message: "Hello World" });
    });
    
    export default app;
    
    // src/app/api/[[...route]]/route.ts
    // eslint-disable-next-line @typescript-eslint/no-unused-vars
    const routes = app.route("/hello", hello).route("/more", more);
    
  4. Hono RPC: allows sharing of the API specifications between the server and the client.

    // https://hono.dev/docs/guides/rpc
    export type AppType = typeof route
    
  5. Create HonoClient

    // src/lib/hono.ts
    import { AppType } from "@/app/api/[[...route]]/route";
    import { hc } from "hono/client";
    
    export const client = hc<AppType>(process.env.NEXT_PUBLIC_APP_URL!);
    
  6. Access /api/hello