DEV Community

Murtuzaali Surti
Murtuzaali Surti

Posted on • Originally published at syntackle.com

3

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.

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

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...

The Most Contextual AI Development Assistant

Pieces.app image

Our centralized storage agent works on-device, unifying various developer tools to proactively capture and enrich useful materials, streamline collaboration, and solve complex problems through a contextual understanding of your unique workflow.

👥 Ideal for solo developers, teams, and cross-company projects

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay