Hono Tutorial Pt. 2

Aug 6, 2024

In this article, we are going to connect the database in Hono application. For the purpose of demonstration, we are going to use PostgreSQL database and postgres as npm package. You are free to use any other package and database as steps will be similar except you need to consult the respected documentation for initial setup.

Let’s install a postgres package.

npm i -E postgres

As per postgres package documentation, we first need to import the postgres function. This function accepts the connection options, and we can save the connection within sql variable as follows.

import { serve } from "@hono/node-server";
import { Hono } from "hono";
import postgres from "postgres";

const sql = postgres({
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "password",
  database: "hono",
});

const app = new Hono();

app.get("/", async (c) => {
  return c.text("Hello!");
});

serve(app, (info) => {
  console.log(`Listening on http://localhost:${info.port}`);
});

You need to adjust the connection options to the postgres() function based on your PostgreSQL setup. Once done, you now have the active connection within sql variable.

Let’s execute the simple SELECT 1 + 1 query within root route and print the result of it. The query returns the promise, and due to this we need to update the signature of the callback function to async/await.

import { serve } from "@hono/node-server";
import { Hono } from "hono";
import postgres from "postgres";

const sql = postgres({
  host: "localhost",
  port: 5432,
  username: "postgres",
  password: "password",
  database: "hono",
});

const app = new Hono();

app.get("/", async (c) => {
  const result = await sql`SELECT 1 + 1`;
  console.log(result);
  return c.text("Hello!");
});

serve(app, (info) => {
  console.log(`Listening on http://localhost:${info.port}`);
});

That’s it! Run the application using the following command.

npm run dev

Visit http://localhost:3000 in the browser and check the terminal. You should see the following console message.

Result(1) [ { '?column?': 2 } ]

We got the result 2 as 1+1 and when you don’t define the column name in SELECT clause in PostgreSQL, PostgreSQL by default gives ?column? as column name.

With these changes, our Hono application is connected with database. You might say that this is boring and nothing specific to Hono. That is right! As Hono doesn’t re-invent wheel in every aspect of the web development and database connection is one such a case!

Note: The code is available at GitHub. Checkout chapter02 branch for the code of this chapter.

Tags: hono