Clara Ekekenta Software Engineer and perpetual learner with a passion for OS and expertise in Python, JavaScript, Go, Rust, and Web 3.0.

Build a web application with Hono

4 min read 1368

Hono Logo

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, a new, flexible web application framework that is very fast. According to test results published on the framework’s website, Hono is faster than other routers for Cloudflare Workers, such as Sunder, Itty Router, and Worktop, 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

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

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, [email protected], 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:

mkdir hono-app && cd hono-app

Then, initialize a new project with Wrangler, the Cloudflare Workers command-line tool:

npx wrangler init -y

The above command will generate the following folder structure:

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:

npm install hono

Next, create a Hono server, like so:

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:

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:

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

const blogs: BLOG[] = []

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

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.

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

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

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:

[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:

<!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:

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:

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:

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

Copy the link and test it out.


More great articles from LogRocket:


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.

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

: Full visibility into your web and mobile apps

LogRocket 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.

.
Clara Ekekenta Software Engineer and perpetual learner with a passion for OS and expertise in Python, JavaScript, Go, Rust, and Web 3.0.

One Reply to “Build a web application with Hono”

  1. Thank you for this really easy to follow tutorial. I’m going to try this later today.

    If your app needs to have a database, how does it fit into the development flow?

    I would appreciate any elaborate info.

Leave a Reply