Create a Node Server using Hono under 10 Lines of Code

Murtuzaali Surti
Murtuzaali Surti

• 1 min read

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

  1. Create a file named index.mjs and then, import Hono and its nodejs adapter.
import { Hono } from "hono"
import { serve } from "@hono/node-server"
  1. Initialize a new Hono app.
const app = new Hono()
  1. Handle a simple GET route.
app.get("/", (context) => context.json({ "hello": "world" }))
  1. 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.


Integrate Pagefind's Search with Astro: A Complete Setup Guide

Previous

I tried "window.ai" in Chrome

Next