DEV Community

Cover image for Introduction to hono.dev - Building a Serverless API Easily
hoaitx
hoaitx

Posted on • Originally published at 2coffee.dev

Introduction to hono.dev - Building a Serverless API Easily

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!");  
  },  
};  
Enter fullscreen mode Exit fullscreen mode

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}!`);  
    }  
  },  
};  
Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

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}`)  
});  
Enter fullscreen mode Exit fullscreen mode

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  
Enter fullscreen mode Exit fullscreen mode

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)  
Enter fullscreen mode Exit fullscreen mode

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!

Top comments (0)