Build a web application with Hono
Tags: webdev
Published: 2022-10-18 14:26:39

**Written by [Clara Ekekenta](https://blog.logrocket.com/author/claraekekenta/)✏️**

Choosing the right tool for a web application can be challenging given the abundance of available options. Speed is one consideration that is often top of mind when selecting a framework. Fast load time is a priority for web applications, as users dislike excessive wait times. 

This article introduces [Hono](https://honojs.dev), a new, flexible web application framework that is very fast. According to [test results published on the framework’s website](https://honojs.dev), Hono is faster than other routers for Cloudflare Workers, such as [Sunder](https://sunderjs.com), [Itty Router](https://itty-router.dev/#/), and [Worktop](https://github.com/lukeed/worktop#readme), and also faster than other frameworks for Deno and Bun. 

In the tutorial portion of this post, we’ll demonstrate how to make a blog app using Cloudflare Workers and Hono.

## Contents

*   [Prerequisites](#prerequisites)
*   [What is Hono?](#what-is-hono)
*   [Why use Hono?](#why-use-hono)
*   [Demo: Building a blog app with Hono](#demo-building-a-blog-app-with-hono)
    *   [Getting started](#getting-started)
    *   [Installing Hono](#installing-hono)
    *   [Creating routes](#creating-routes)
    *   [Adding authentication](#adding-authentication)
    *   [Rendering static files](#rendering-static-files)
    *   [Handling CORS](#handling-cors)
    *   [Deploying the application](#deploying-the-application)

## Prerequisites

To get the most out of this tutorial, ensure you have the following:

*   Prior knowledge of [Cloudflare Workers](https://developers.cloudflare.com/workers/) and a [Cloudflare](https://dash.cloudflare.com/) account
*   Node.js v14 or higher installed

## What is Hono?

Hono is a lightweight, simple, and fast web framework for Cloudflare Workers, Deno, Bun, and other applications. It is a modern web application that is both fast and flexible. It offers inbuilt support for TypeScript, and easy development in a local environment. Using Hono, It is easy to create publishable web applications with Deno, Bun, and Cloudflare Workers.

## Why use Hono?

Hono has many cool features, which is why it is loved and used by many developers. Here are some of Hono’s features:

*   Ultrafast router without linear loops
*   Inbuilt support for TypeScript
*   Uses Service Workers and Web Standard API with zero dependencies
*   Allows use of inbuilt middleware, custom middleware, and third-party middleware
*   Integrates with multiple platforms, such as Cloudflare Workers, Fastfly, Compute@Edge, Deno, and Bun

## Demo: Building a blog app with Hono

Let’s create a web application while we explore Hono's features. We'll set up the project with Cloudflare Workers, create a to-do API, perform CRUD operations, implement authentication, and add middleware.

### Getting started

To get started, let’s create our first Hono application with Cloudflare Workers. 

First, create a new folder for the project, like so:

```typescript
mkdir hono-app && cd hono-app
```

Then, initialize a new project with [Wrangler](https://developers.cloudflare.com/workers/wrangler/), the Cloudflare Workers command-line tool:

```typescript
npx wrangler init -y
```

The above command will generate the following folder structure:

```json
hono-example
 ┣ src
 ┃ ┗ index.ts
 ┣ .gitignore
 ┣ package-lock.json
 ┣ package.json
 ┣ tsconfig.json
 ┗ wrangler.toml
```

### Installing Hono

To set up the application, start by installing the Hono package by running the following command:

```typescript
npm install hono
```

Next, create a Hono server, like so:

```typescript
import { Hono } from 'hono'
const app = new Hono()

app.get('/', (c) => c.text('Hello from Hono'))

app.fire()
```

In the above code, we imported the Hono package and initialized a new Hono app instance. With the app instance, we have access to all of Hono’s available features. We also exported the app instance, so that Cloudflare Workers can run the application in a service worker mode. 

Next, run the following command in the project root directory to start the application:

```typescript
npx wrangler dev
```

This command will run the application on `localhost:8787`. You can test that out on your browser.

### Creating routes

Hono makes routing as flexible and intuitive as possible; it is very similar to the way you'd handle routing with a framework like Express.js. 

Let's create an API route to perform some CRUD operations. We'll create a blog API to read and create blogs. 

We’ll start by creating a type and a variable for the blogs. Add the following code to the `index.ts` file:

```typescript
type BLOG = {
  id: number,
  title: string,
  content: string
}

const blogs: BLOG[] = []
```

Next, we'll define the API routes with the below code:

```typescript
app.get('/api/blogs', (c) => c.json(blogs))

app.get('/api/blogs/:id', (c) => {
  const { id } = c.req.param()
  const blog = blogs.filter(data => data.id === parseInt(id))
  return c.json(blog)
})

app.post('/api/blogs', async (c) => {
  const body = await c.req.parseBody() as BLOG;
  if (!body) return c.json({ status: 401, message: "The request payload is required" })
  const newBlog = {
    id: blogs.length + 1,
    title: body.title,
    content: body.content
  }
  blogs.push(newBlog)
  return c.json({ data: newBlog })
})
```

Like Express.js, Hono provides several methods (e.g., `get`, `post`, `update`, `delete`) for us to perform operations. Each of these methods has a callback that takes `c` as a parameter. The `c` parameter gives the user access to the method we need to access the request parameters and payloads, as well as to respond to requests.

### Adding authentication

Hono provides middleware to add authentication to our application in a snap. Hono offers three kinds of authentication middleware: basic authentication, bearer authentication, and JWT authentication. Details on each of these types of authentication can be found [here](https://honojs.dev/docs/builtin-middleware/). 

For this demonstration, we'll implement the basic authentication. To get started, import the `basicAuth` middleware from Hono and use the following code:

```typescript
import { basicAuth } from 'hono/basic-auth'
...

app.use(
  '/api/*',
  basicAuth({
    username: 'clinton',
    password: '1234',
  })
)
```

This middleware will prevent unauthorized users from requesting any endpoint that starts with `/api`. Also, it will display a sign-in UI that users must log in to before access will be granted: ![Sign-in UI](https://blog.logrocket.com/wp-content/uploads/2022/10/sign-in-ui.png) 

If the username and password the user enters match the username and password in the middleware, Hono will create a session and allow access to the routes on subsequent requests.

### Rendering static files

Hono provides `serveStatic` middleware to allow the rendering of static files located in the directory specified in the middleware’s root option. 

To get started, create an `assets` file in the project’s root directory. Then, update the `wrangler.toml` file to specify the assets directory, like so:

```typescript
[site]
bucket = "./assets"
```

Next, we’ll need to create or add our asset files to the assets folder. 

For this demonstration, we'll render an HTML page. So, create an `index.html` file in the assets folder with the below markup:

```xml
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="/static/style.css">
</head>
<body>
    <h4>Hello from Hono </h4>
</body>
</html>
```

Now, set up the static middleware in the `index.ts` file, like so:

```typescript
app.use('/static/*', serveStatic({ root: './' }))
app.get('/', serveStatic({ path: './index.html' }));
```

In the above code, we created a Hono middleware that will serve static content on the `/static` endpoint. We also used the `serverStatic` middleware to specify the root location of our assets directory.

### Handling CORS

To allow our application to interact with a frontend framework, we need to implement CORS. Hono provides us with a `cors` middleware. Import and set up the middleware in the `index.ts` file:

```typescript
import { cors } from 'hono/cors'
app.use('/api/*', cors())
```

In the above code, we implement CORS on all endpoints in our application that begin with `/api`. By doing so, there won’t be any CORS blocking when a user makes requests to these endpoints.

### Deploying the application

Now, let's deploy the application to Cloudflare by running the following command:

```typescript
npx wrangler publish ./src/index.ts
```

The above command will prompt you to authorize the application to access your Cloudflare account. 

After authorizing the application, wait for the deployment to complete. Once the deployment is completed, you’ll see the worker URL of your application, similar to that shown below: ![Worker URL](https://blog.logrocket.com/wp-content/uploads/2022/10/worker-url.png) 

Copy the link and test it out.

## Conclusion

In this tutorial, we explored how to build a web application with Hono. We discussed what Hono is all about and why developers should consider using this framework. To illustrate this point, we showed how to build a blog application using Cloudflare Workers and Hono. 

To learn more about Hono’s features, visit the [official documentation](https://honojs.dev). 

Now that you've been introduced to Hono, how will you use it in your next project?

---
## [LogRocket](https://lp.logrocket.com/blg/signup): Full visibility into your web and mobile apps

[![LogRocket signup](https://blog.logrocket.com/wp-content/uploads/2017/03/1d0cd-1s_rmyo6nbrasp-xtvbaxfg.png)](https://lp.logrocket.com/blg/signup)

[LogRocket](https://lp.logrocket.com/blg/signup) is a frontend application monitoring solution that lets you replay problems as if they happened in your own browser. Instead of guessing why errors happen, or asking users for screenshots and log dumps, LogRocket lets you replay the session to quickly understand what went wrong. It works perfectly with any app, regardless of framework, and has plugins to log additional context from Redux, Vuex, and @ngrx/store.

In addition to logging Redux actions and state, LogRocket records console logs, JavaScript errors, stacktraces, network requests/responses with headers + bodies, browser metadata, and custom logs. It also instruments the DOM to record the HTML and CSS on the page, recreating pixel-perfect videos of even the most complex single-page and mobile apps.

[Try it for free](https://lp.logrocket.com/blg/signup).