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.
Let’s define the following environment variables within this created .env
file.
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.
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.
Import dotenv/config
in app.js
and we are good to go.
Now, replace the hard-coded database connection options within app.js
with the env vars using process.env
as follows.
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!
Visit the http://localhost:3000 in the web browser and you should see the following output in terminal while displaying Hello!
in the browser.