Introduction to hono.dev - Building a Serverless API Easily

Introduction to hono.dev - Building a Serverless API Easily

Daily short news for you
  • Zed is probably the most user-centric developer community on the planet. Recently, they added an option to disable all AI features in Zed. While many others are looking to integrate deeper and do more with AI Agents. Truly a bold move 🤔

    You Can Now Disable All AI Features in Zed

    » Read more
  • Today I have tried to walk a full 8k steps in one session to show you all. As expected, the time spent walking reached over 1 hour and the distance was around 6km 🤓

    Oh, in a few days it will be the end of the month, which means it will also mark one month since I started the habit of walking every day with the goal of 8k steps. At the beginning of next month, I will summarize and see how it goes.

    » Read more
  • It's been a long time since I've read such a heartfelt article The many, many, many JavaScript runtimes of the last decade. In the article, the author recounts the journey of the development of the JavaScript runtime environment, noting that today we have and are seeing JavaScript present in many areas. Additionally, the author also touches on a lot of peripheral knowledge; just a little reading opens up so many new discoveries 🤓

    » Read more

The Problem

Express.js is certainly a library that any JavaScript/Node.js developer knows. It helps us build a REST API server quickly. Besides, there are many libraries and middleware created to be compatible and easily integrated into projects using express.js, making it increasingly popular and well-known.

Starting with express.js is not difficult. Just go through a few steps to install the library and write a little code, then use the node command to start the server. The deployment process is not much harder. Push the code to git, pull it back to the server, use a process management tool like pm2 to start it up, and that's it.

This is a nearly obvious process to apply when writing and deploying a Node server. Even later, when working for many companies, the process of pushing code to git, pulling it back to the server, and then "pm2 restart" - which I jokingly call the 3P process to operate the server - is still the same.

Until one day, my CTO mentioned Cloudflare Workers, a form of serverless. He said it could do this and that... a little bit each day, and it made me curious. Occasionally, I would read about it, but honestly, it was hard to understand. Although everyone knows the concept of serverless, its practical application is unknown.

What is mentioned many times will also attract attention. I started reading about serverless more seriously, but I still didn't know how to deploy the code to serverless. Because serverless has no server, where do the push-pull-pm2 restart happen?

It turned out that there was a separate process for deploying everything to serverless. Moreover, this process is even simpler than the traditional 3P. All you need to do is run the deploy command on your machine. When that's done, all the code will be uploaded to the serverless server and be ready to run immediately.

In this article, I won't discuss the process of deploying code to serverless. Before that, we need to know about a library that helps us build an API on serverless. Why? Because express.js and similar libraries cannot run on many serverless servers.

hono.dev

hono.dev is a library similar to express.js, providing solutions for building APIs. But why hono? Look at Cloudflare Workers' simple endpoint guide below:

export default {  
  async fetch(request, env, ctx) {  
    return new Response("Hello World!");  
  },  
};  

This code will respond with the phrase "Hello World!". If you want to add a POST method, you need to check the condition:

export default {  
  async fetch(request, env, ctx) {  
    if (request.method === "GET") {  
      return new Response("Hello World!");  
    } else if (request.method === "POST") {  
      const data = await request.json();  
      return new Response(`Hello, ${data.name}!`);  
    }  
  },  
};  

Too cumbersome and complex, an API server is not that simple, but a collection of dozens, hundreds of different endpoints. That's when hono shines.

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

app.get('/', (c) => c.text('Hello World!'))  
app.post('/', (c) => c.text(`Hello ${(await c.req.body()).name}`))  

export default app  

Isn't it quick and easy?

Hono.dev is quite similar to express.js or koa.js. Hono focuses on simplicity, routing, and middleware. Using hono is similar to the REST API libraries you've been using for a long time.

For example, a simple middleware to measure the request processing time:

app.use(async (c, next) => {  
  const start = Date.now()  
  await next()  
  const end = Date.now()  
  c.res.headers.set('X-Response-Time', `${end - start}`)  
});  

Hono is very lightweight, only 14kb for the hono/tiny package, making it ideal for environments with many limitations like serverless. In traditional server applications, package size or library size doesn't matter because system resources are abundant and easy to upgrade. However, in serverless environments, resources are scarce, so finding fast and lightweight libraries is essential.

You may have heard of the term "universal module" and "adapter", which are often used to describe a module that can work in multiple environments. From servers, browsers, or even serverless environments. To achieve this, universal modules utilize APIs supported by the environment to adapt and create adapters for us to choose from. Even if the project structure is good enough, we don't need to modify too much code to run in different environments.

Hono supports many adapters, making it perfect for serverless environments. Some notable names include Cloudflare Workers, Vercel, Netlify, AWS Lambda... or even Service Worker in browsers.

For example, this code snippet runs well in Cloudflare Worker:

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

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

export default app  

And to switch to Netlify's serverless environment, we need to change the adapter:

import { Hono } from 'jsr:@hono/hono'  
import { handle } from 'jsr:@hono/hono/netlify'  

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

export default handle(app)  

Note that since the serverless environment has different deployment methods, the best way to choose a suitable configuration for each environment is to refer to Hono's documentation.

Hono's documentation is very simple and concise, and we can start building a project after just a few reads. Its own "homegrown" middleware is constantly being added to enhance the experience for developers, so we don't need to reinvent the wheel. Additionally, Hono is receiving attention from the community with impressive growth on Github.

This is a short introduction to Hono and what it can do. In the next article, we'll deploy a serverless API server to Cloudflare Workers from scratch!

Premium
Hello

The secret stack of Blog

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

As a developer, are you curious about the technology secrets or the technical debts of this blog? All secrets will be revealed in the article below. What are you waiting for, click now!

View all

Subscribe to receive new article notifications

or
* The summary newsletter is sent every 1-2 weeks, cancel anytime.

Comments (0)

Leave a comment...