If you’re working on a Node.js app, you often need a database to store information. PostgreSQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your Postgres database with your Node.js app.
In order to use PostgreSQL databases with NodeJS, you’ll need to use a Node library. There are multiple options, but the most popular Node.js library to connect to Postgres is node-pg
. Simply use npm to install it to your package.json
npm install pg
You can find additional documentation for node-pg
on the project’s GitHub repository.
You’ll need to have your Postgres credentials. You can use this guide to find your credentials.
Once you have your credentials, import the node-pg
package and create a new connection. In the example below, we pass in our credentials to create the connection.
const { Client } = require('pg');
var connectionString = "postgres://myUser:myPassword@localhost:5432/myDB";
const client = new Client({
host: 'localhost',
port: 5334,
user: 'database-user',
password: 'secretpassword!!',
})
We can then initialize the connection using node-pg
’s client.connect()
method:
client.connect()
Once you have established your connection, you can query your Postgres database using Node. To create and run a query, use client.query(text, values)
like this:
client.query(‘SELECT $1::text as message’, [‘Arctype Archive: Your #1 Database Resource’], (err, res) => {
console.log(err ? err.stack : res.rows[0].message
client.end()
})
You can also pass variables to client.query()
for both the text and values parameters like this:
const text = 'INSERT INTO Users(username, email) VALUES($1, $2) RETURNING *'
const values = ['Arctype', 'test@Arctype.com']
client.query(text, values, (err, res) => {
if (err) {
console.log(err.stack)
} else {
console.log(res.rows[0])
// { username: Arctype', email: 'test@Arctype.com' }
}
})
Now that you’ve connected Postgres to your Node.js app, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up Postgres with Arctype in this tutorial.