Deploying Hono on Cloudflare Workers

By

Updated

Tagged: Cloudflare

Deploy a Hono API on Cloudflare Workers with wrangler dev, typed D1 bindings, and a tiny REST endpoint. The final post in the Bun and Hono series.

If you’ve been following my Cloudflare Workers series, you already know the platform. A Worker is a function that takes a request and returns a response. Hono is built for exactly that model.

Why Hono on Workers

Hono was born on Cloudflare Workers. The name means “flame” in Japanese, and the project started as a tiny framework for the edge.

Workers give you a fetch handler. Hono adds routing, middleware, and helpers on top of it without requiring an adapter.

That’s why it’s my go-to when I need a small API on Cloudflare.

Create the project

The Hono team ships a Cloudflare Workers template. Run the scaffolder:

npm create hono@latest my-api

When it asks for a template, pick cloudflare-workers. Or skip the prompt:

npm create hono@latest my-api -- --template cloudflare-workers

Move into the folder and install dependencies:

cd my-api
npm install

You get a minimal project. The entry point is src/index.ts:

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.text('Hello Hono!')
})

export default app

Hono exports the app directly. Cloudflare calls app.fetch under the hood.

The other important file is wrangler.jsonc:

{
  "$schema": "node_modules/wrangler/config-schema.json",
  "name": "my-api",
  "main": "src/index.ts",
  "compatibility_date": "2025-08-03"
}

That’s your Worker config. Bindings for D1, KV, or R2 go here too.

Run locally and deploy

The template wires up npm scripts for you. Start the local dev server:

npm run dev

That runs wrangler dev. Open http://localhost:8787 and you’ll see your hello message. Edit the code, save, and it reloads.

When you’re ready to ship:

npm run deploy

Wrangler bundles your code and uploads it. You get a *.workers.dev URL in seconds. The first time, it opens a browser so you can log in to Cloudflare.

Access bindings with types

On Workers, databases and storage show up on env. In Hono you read them from c.env.

Say you already created a D1 database and added it to wrangler.jsonc, like in my Cloudflare D1 post:

{
  "d1_databases": [
    {
      "binding": "DB",
      "database_name": "my-app-db",
      "database_id": "your-database-id"
    }
  ]
}

Pass the binding types to Hono as a generic:

type Bindings = {
  DB: D1Database
}

const app = new Hono<{ Bindings: Bindings }>()

Now c.env.DB is typed.

You don’t have to write that type by hand. The template has a cf-typegen script, which runs wrangler types --env-interface CloudflareBindings:

npm run cf-typegen

It reads wrangler.jsonc and writes a worker-configuration.d.ts file. Inside there’s a CloudflareBindings interface with all your bindings, plus the types of the Workers runtime, like D1Database.

Pass it to Hono:

const app = new Hono<{ Bindings: CloudflareBindings }>()

Run the script again every time you add or change a binding. The file is overwritten each time, so don’t edit it.

A tiny posts API

Let’s wire up two routes against a posts table. Check the D1 post for migrations and schema setup.

Read all posts:

app.get('/api/posts', async (c) => {
  const { results } = await c.env.DB.prepare(
    'select * from posts order by created_at desc'
  ).all()

  return c.json(results)
})

Create a post:

app.post('/api/posts', async (c) => {
  const { title, body } = await c.req.json()

  await c.env.DB.prepare(
    'insert into posts (title, body, created_at) values (?, ?, ?)'
  ).bind(title, body, Date.now()).run()

  return c.json({ ok: true }, 201)
})

These two routes give us JSON parsing and D1 queries in one file.

Validate the input

The POST route above trusts whatever the client sends.

If the body is not valid JSON, c.req.json() throws and the client gets a 500 Internal Server Error. If title is missing, undefined goes straight into the database query.

Hono has a small validator built in. It’s a middleware: you check the value, then return the clean data or a response with an error.

import { validator } from 'hono/validator'

app.post(
  '/api/posts',
  validator('json', (value, c) => {
    const { title, body } = value

    if (typeof title !== 'string' || title.trim() === '') {
      return c.json({ error: 'title is required' }, 400)
    }

    if (typeof body !== 'string') {
      return c.json({ error: 'body must be a string' }, 400)
    }

    return { title: title.trim(), body }
  }),
  async (c) => {
    const { title, body } = c.req.valid('json')

    await c.env.DB.prepare(
      'insert into posts (title, body, created_at) values (?, ?, ?)'
    ).bind(title, body, Date.now()).run()

    return c.json({ ok: true }, 201)
  }
)

The handler reads the data with c.req.valid('json'), and it’s typed from what the validator returned.

One thing to know: the request must have the Content-Type: application/json header. Without it Hono does not parse the body, and the validator gets an empty object.

With a broken JSON body the validator answers with a 400 on its own.

Secrets and variables

Workers don’t have process.env by default. Variables and secrets are on c.env, like the bindings.

Let’s protect the write routes with a token.

For local development, create a .dev.vars file next to wrangler.jsonc:

API_TOKEN=dev-token

Add .dev.vars to .gitignore, so it never ends up in the repository.

For production, save the secret with Wrangler:

npx wrangler secret put API_TOKEN

It asks for the value, then deploys a new version of the Worker with the secret set.

Add it to the types (or run npm run cf-typegen again):

type Bindings = {
  DB: D1Database
  API_TOKEN: string
}

Then check the token in a middleware. Add it before the routes:

app.use('/api/*', async (c, next) => {
  if (c.req.method !== 'GET') {
    const header = c.req.header('Authorization')

    if (header !== `Bearer ${c.env.API_TOKEN}`) {
      return c.json({ error: 'Unauthorized' }, 401)
    }
  }

  await next()
})

Reading is open to everyone, writing needs the token:

curl -X POST http://localhost:8787/api/posts \
  -H 'Authorization: Bearer dev-token' \
  -H 'Content-Type: application/json' \
  -d '{"title":"Hello","body":"My first post"}'

Notice that c.env only exists inside a handler. You can’t read c.env.API_TOKEN at the top of the file, because there is no request yet. That’s why the check is inside the middleware function.

I wrote more about this in Cloudflare Workers: secrets and environments.

Return JSON errors

By default Hono answers with plain text: 404 Not Found for a route that doesn’t exist, Internal Server Error when a handler throws.

For an API you want JSON every time. Set the two handlers on the app:

import { HTTPException } from 'hono/http-exception'

app.notFound((c) => {
  return c.json({ error: 'Not found' }, 404)
})

app.onError((err, c) => {
  if (err instanceof HTTPException) {
    return c.json({ error: err.message }, err.status)
  }

  console.error(err)
  return c.json({ error: 'Internal server error' }, 500)
})

HTTPException is how you stop a request with a specific status code from anywhere in your code:

app.get('/api/posts/:id', async (c) => {
  const post = await c.env.DB.prepare(
    'select * from posts where id = ?'
  ).bind(c.req.param('id')).first()

  if (!post) {
    throw new HTTPException(404, { message: 'Post not found' })
  }

  return c.json(post)
})

first() returns null when no row matches, so the client gets {"error":"Post not found"} with a 404.

Test the routes

You don’t need a running server to test a Hono app. app.request() takes a path and gives you back the Response.

Its third argument is the env object, so you can pass fake bindings and secrets.

Install Vitest:

npm install -D vitest

Then create src/index.test.ts:

import { expect, test } from 'vitest'
import app from './index'

const env = {
  API_TOKEN: 'test-token',
}

test('POST /api/posts needs the token', async () => {
  const res = await app.request('/api/posts', { method: 'POST' }, env)

  expect(res.status).toBe(401)
})

test('POST /api/posts needs a title', async () => {
  const res = await app.request(
    '/api/posts',
    {
      method: 'POST',
      headers: {
        Authorization: 'Bearer test-token',
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ body: 'No title here' }),
    },
    env
  )

  expect(res.status).toBe(400)
  expect(await res.json()).toEqual({ error: 'title is required' })
})

Run it with npx vitest run.

These 2 tests stop before the database, so there’s nothing to fake. For tests that run real D1 queries, Cloudflare has a Vitest integration that runs them inside the Workers runtime.

Middleware and other bindings

Middleware works the same on Workers as anywhere else. Everything about cookies, headers, and CORS from the middleware post applies here unchanged.

Other bindings follow the same pattern. Add a KV namespace to wrangler.jsonc, type it on Bindings, and use c.env.SESSIONS (or whatever you named it). You can do the same with an R2 bucket. I covered KV in a separate post.

Cron jobs and queues in the same Worker

export default app works because a Hono app has a fetch method, and that’s all a Worker needs to answer HTTP requests.

A Worker can also run on a schedule, or read from a queue. Those are other handlers, and Hono does not know about them.

When you need one, export an object and give Hono the fetch part:

export default {
  fetch: app.fetch,
  async scheduled(event, env, ctx) {
    // runs on the schedule you set in wrangler.jsonc
  },
}

See Cloudflare Cron Triggers for how to set the schedule.

My preferred stack for small APIs

For a small API on Cloudflare, I use Hono on Workers. I add D1 when I need SQL and KV for simple key lookups. I later followed one request through Hono to show how its router, middleware, context, and adapters fit together.

If you want to go deeper, the Hono Cloudflare Workers guide and the Wrangler docs are the next stop.

Want me to talk about your product? You can sponsor this site.

Related posts about cloudflare: