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.
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.
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
.
That’s it! Run the application using the following command.
Visit http://localhost:3000 in the browser and check the terminal. You should see the following console message.
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.