Postgres Connection String

Shihab Sikder Oct 12, 2023
  1. The General Format for the PostgresSQL Connection String
  2. Create a Postgres Database Connection in Heroku
Postgres Connection String

The database connection string is a kind of expression where all the parameters required to establish a connection from the end device to the database are present.

It contains database username, password, name, host address, and port.

This connection string can be for localhost and the remote database running on the hosting.

The General Format for the PostgresSQL Connection String

const connectionString =
    'postgres://<database_username>:<database_userpassword>@<hostaddress>:<port_no>/<database_name>'

You can put the connection string to the .env file. Ensure that the given user has the permission to perform the operation you’re calling.

If the user doesn’t exist or the port number is incorrect, the database connection will not be established.

The default port address is 5432 for the Postgres database. If running the database on your device, you can replace the hostname with localhost.

For example, your username is tester, the password is test123, the database name is contact, and you’re running the Postgres in localhost with the default port no.

const URI = 'postgres://tester:test123@localhost:5432/contact'
Note
It’s a good practice to declare the connection string or the URI as CONST because you don’t want to change the credential accidentally by any function or code segment.

Create a Postgres Database Connection in Heroku

Heroku provides a free Postgres database. You can create and run it remotely.

Host: ec2 - ....- 8 - 220.compute-1.amazonaws.com
Database: d3...dk
User: ips....kgfgu
Port: 5432
Password: ce6b.....cea5bf
URI: postgres:
        // ips....kgfgu:ce6b.....cea5bf@ec2-....-8-220.compute-1.amazonaws.com:5432/d3...dk
    Heroku CLI: heroku pg: psql postgresql - opaque - 10916 --app my_app

Here you can see the credentials; some portions are replaced with dot and the URI for security purposes. The URI is the connection string.

It would help put this URI as a parameter for the database connection function. If you notice, you’ll see that the URI is just a formatted way to represent the parameters.

More details can be found on the official documentation.

Shihab Sikder avatar Shihab Sikder avatar

I'm Shihab Sikder, a professional Backend Developer with experience in problem-solving and content writing. Building secure, scalable, and reliable backend architecture is my motive. I'm working with two companies as a part-time backend engineer.

LinkedIn Website