Heroku is a cloud platform as a service (PaaS) supporting several programming languages as well as RDBMS like Postgres
In this blog, you're going to learn "How to set up your application with Heroku's Database"
Prerequisites
- Basic JS, Postgres knowledge
- Account on heroku
- Heroku CLI installed locally
So we will start by creating an application on Heroku
You can do this either using CLI or through their website. We will create using CLI
Before that, you will need to login to Heroku
heroku login
After you are logged in, run the following command for creating our app using buildpack
heroku create yourappname --buildpack heroku/nodejs
Now let's integrate our app with the database, for this, hit your Heroku app, and go to the Resources tab
Search for Heroku Postgres
and click to add it. Heroku also provides a good interface for managing datastores
Our next step is to deploy our code, don't worry I have a specific repository for such
Deployment
For Deployment, run the following commands in order
Initialize git in your directory
git init
Clone my repo
git clone https://github.com/eklavyadev/PostgreSQL-API-Heroku.git
cd
Git add
git add .
Git commit
git commit -m "Testing"
Push to Heroku
git push heroku main
In case you are stuck to any error at this moment, run heroku git:remote -a yourherokuappname
and push to Heroku again
Open your app
heroku open
Congratulations! You have deployed your app on Heroku integrated with PostgreSQL
But actually how it is connected with DB?
const dbConfig = parseDbUrl(process.env.DATABASE_URL);
If you look at this code in database.js
, we are loading connection string using environment variables in Heroku which you may find in the settings tab
The rest of the code is dealing with connection, creating tables, and serving data, which is quite easy
Thanks
I hope you find this blog useful, also make sure to follow me on github
If you have any errors/complaints regarding this, tell me in the contact section