Introduction to hono.dev - Building a Serverless API Easily

Introduction to hono.dev - Building a Serverless API Easily

Daily short news for you
  • Wow, I really didn't know about Gemini Code Assist before. I just heard that it's completely free for everyone now.

    When I checked it out, I saw that it’s similar to Github Copilot. Looking at the pricing table, free users have more limited features than paid users, but it still has basic features like suggestions and chat. Has anyone used Gemini Code Assist? What do you think about it? 😅

    Get coding help from Gemini Code Assist — now for free

    » Read more
  • If you want to quickly generate a UUID string on Linux/Unix:

    $ uuidgen 6AAB63E9-8C2E-4D74-B593-E53A67E0B88F

    If you frequently need to create a secret string or password:

    $ openssl rand -base64 24 6yCcJke/HbYzooOHkK7xVkvf0PXm8jeJ

    where 24 is the length of the string

    Or if you need a stronger encrypted string, install pwgen. Then

    $ pwgen -y 24 Sal5eguPh*aetah7giethoh3 aiv!ah2ohP.aiC8ei1lei2ei ood4Ea_shiel,ees9sor0tha ...

    » Read more
  • bolt.new has just been updated with "vision", everyone. For those who don't know, this is a tool that helps create interfaces by chatting with it. Just point and it will follow.

    Previously, you may have noticed that every time you asked it to make a change, it replaced the entire old code with new code, which was quite token-consuming. With the "vision" update, now you only need to precisely highlight the area that needs fixing and tell it, and it will only modify the code in that section. It's faster and more economical 😇

    x.com/boltdotnew/status/1892620446106886396

    » 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

Me & the desire to "play with words"

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member now!

Have you tried writing? And then failed or not satisfied? At 2coffee.dev we have had a hard time with writing. Don't be discouraged, because now we have a way to help you. Click to become a member 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...