Hono, as per the docs, was originally built for Cloudflare Workers. It's an application framework designed to work the best for cloudflare pages and workers as well as javascript runtimes Deno and Bun. Although not built specifically for Node, an adapter can be used to run it in Node.
In this tutorial, you will get to know how you can create a simple HTTP server in Node using Hono in less than 10 lines of code.
Prerequisites
Create a bare bones node environment using npm init -y
.
Setting Up Hono
Install hono from npm
along with its nodejs adapter.
npm i hono @hono/node-server
Creating A Server
- Create a file named
index.mjs
and then, import Hono and its nodejs adapter.
import { Hono } from "hono"
import { serve } from "@hono/node-server"
- Initialize a new Hono app.
const app = new Hono()
- Handle a simple GET route.
app.get("/", (context) => context.json({ "hello": "world" }))
- Serve the app using the nodejs adapter.
serve({ port: 3000, fetch: app.fetch }, (i) => console.log(`listening on port ${i.port}...`))
Here's a snippet of all the code combined:
import { Hono } from "hono"
import { serve } from "@hono/node-server"
const app = new Hono()
app.get("/", (context) => context.json({ "hello": "world" }))
serve({ port: 3000, fetch: app.fetch }, (i) => console.log(`listening on port ${i.port}...`))
Conclusion
One highlight of Hono is its Regexp router. It allows you to define routes which match a regex pattern. Apart from that, it also offers multiple built-in authentication modules for implementing various authentication methods such as basic, bearer, and jwt.