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.
To get the most out of this tutorial, ensure you have the following:
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.
Hono has many cool features, which is why it is loved and used by many developers. Here are some of Hono’s features:
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.
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
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.
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.
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:
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.
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.
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.
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:
Copy the link and test it out.
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?
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowThe useReducer React Hook is a good alternative to tools like Redux, Recoil, or MobX.
Node.js v22.5.0 introduced a native SQLite module, which is is similar to what other JavaScript runtimes like Deno and Bun already have.
Understanding and supporting pinch, text, and browser zoom significantly enhances the user experience. Let’s explore a few ways to do so.
Playwright is a popular framework for automating and testing web applications across multiple browsers in JavaScript, Python, Java, and C#. […]
One Reply to "Build a web application with Hono"
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.