Hono Tutorial Pt. 3

Aug 7, 2024

Before we go further and learn more about the Hono framework, the one thing that is bothering me is database credentials written in code. We should adjust the existing code by removing the credentials from the code and put it within the .env file. We should never hard-code the secret(s) as per 12factor app.

Go ahead and create a .env file in the root of the project.

touch .env

Let’s define the following environment variables within this created .env file.

DB_NAME="hono"
DB_HOST="localhost"
DB_PORT=5432
DB_USER="postgres"
DB_PASS="password"

We should not commit this file in the Git. The file should be added within .gitignore file. But, to give and idea about the existence of the .env file, we should have the .env.example file in the repo with same content as we have in .env file but with dummy environment variables or env vars.

cp .env .env.example

Hono has an adapter to read the env vars from the .env file. But, unfortunately it is not working for the Node and outside of c or context. For now, we are going to use the dotenv package. Let’s first install the dotenv package.

npm i -E dotenv

Import dotenv/config in app.js and we are good to go.

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

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}`);
});

Now, replace the hard-coded database connection options within app.js with the env vars using process.env as follows.

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

const sql = postgres({
  host: process.env.DB_HOST,
  port: process.env.DB_PORT,
  username: process.env.DB_USER,
  password: process.env.DB_PASS,
  database: process.env.DB_NAME,
});

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}`);
});

With these changes, we have removed the hard-coded secrets from our code. These changes should not effect the output. Run the application to confirm the same!

npm run dev
Listening on http://localhost:3000

Visit the http://localhost:3000 in the web browser and you should see the following output in terminal while displaying Hello! in the browser.

Result(1) [ { '?column?': 2 } ]
Note
The code is available at GitHub. Checkout chapter03 branch for the code of this chapter.
Tags: hono