Tidy up Worker endpoints with Hono

Tidy up Worker endpoints with Hono

In this Article

Overview

Workers are Cloudflare solutions to SAAF. They execute as a function and are meant to be small, however I have found myself using them to write small apis with a few endpoints. Checking on path and http request methods can get messy and I find myself writing code that’s not necessarily related to my application logic. This is one of the reasons why I like to use Hono. So I can focus on writing the code that’s necessary to build my application. Here is a peek of what a simple worker with Hono looks like.

Typing the Environment

I’d like for my Worker environment to be typed so here I have an environment.ts that looks like this:

import { Context } from 'hono'

export type Env = {
  APP_NAME: string
}

/**
 * Declare type for Hono context
 */
export type HonoContext = Context<{
  Bindings: Env;
}>

Creating the Hono Application

Creating the hono application is as simple as it comes:

import { Hono } from 'hono'
import { Env, HonoContext } from '@/environment'

// create the hono app
const app: Hono<{ Bindings: Env }> = new Hono<{ Bindings: Env }>()

// register the app get endpoint
app.get('/app', (context: HonoContext): Response => {
  return context.json({
    name: context.env.APP_NAME
  }, 200)
})

// register the app post endpoint
app.post('/app', async (context: HonoContext): Promise<Response> => {
  const json = await context.req.json()
  return context.json(json, 201)
})

// export the hono application
export default {
  ...app
}

That is it! Checkout the complete running example in the Cloudflare Series repository.