DEV Community

Murtuzaali Surti
Murtuzaali Surti

Posted on • Originally published at syntackle.com

Create a Node Server using Hono

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

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"
Enter fullscreen mode Exit fullscreen mode
  1. Initialize a new Hono app.
const app = new Hono()
Enter fullscreen mode Exit fullscreen mode
  1. Handle a simple GET route.
app.get("/", (context) => context.json({ "hello": "world" }))
Enter fullscreen mode Exit fullscreen mode
  1. Serve the app using the nodejs adapter.
serve({ port: 3000, fetch: app.fetch }, (i) => console.log(`listening on port ${i.port}...`))
Enter fullscreen mode Exit fullscreen mode

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

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.

Top comments (2)

Collapse
 
raz41 profile image
Razor

is it effective for live streaming?

Collapse
 
murtuzaalisurti profile image
Murtuzaali Surti

not completely sure but it does support server side events hono.dev/docs/helpers/streaming#st...