CodingNic

Connecting Node.js to PostgreSQL

Installing PostgreSQL and Creating a Database

Connecting Node.js to PostgreSQL 10 min read

Installing PostgreSQL and Creating a Database

Objectives

By the end of this lesson, you should be able to:

  • Install PostgreSQL on your own machine
  • Create a new, empty database ready for a Node.js project to connect to

💡 Why this matters: Every lesson from here on assumes a real PostgreSQL server is running somewhere Node.js can reach it, on your own machine, or in a container. This lesson gets one running, with a database ready to use.

⚠️ A note on verification: the installation steps below are standard, current instructions from postgresql.org. The Node.js and SQL code in every other lesson in this course was verified against a real, running PostgreSQL server, but the install steps themselves weren’t executed inside this course’s own tooling. If a step looks different on your system, PostgreSQL’s official documentation for your operating system is the definitive source.

Installing on macOS

Using Homebrew:

bash
brew install postgresql@18
brew services start postgresql@18

Installing on Windows

Download the installer from postgresql.org/download and run it. It installs the server, psql (the command-line client), and sets a password for the default postgres superuser account, keep that password, it’s needed to connect.

Installing on Linux (Debian/Ubuntu-based)

bash
sudo apt update
sudo apt install postgresql postgresql-contrib

This starts the PostgreSQL service automatically on most distributions.

Creating a Database

Once PostgreSQL is running, create a database for this course’s projects using psql, the command-line client that ships with PostgreSQL:

bash
psql -U postgres

At the psql prompt:

sql
CREATE DATABASE school;
text
CREATE DATABASE

List existing databases to confirm it was created:

sql
\l
text
                                  List of databases
   Name    |  Owner   | Encoding | ...
-----------+----------+----------+-----
 postgres  | postgres | UTF8     | ...
 school    | postgres | UTF8     | ...

Exit psql with \q. The school database is what the rest of this module connects Node.js to.

Try It

  1. Install PostgreSQL on your machine, following the instructions for your operating system.
  2. Confirm it’s running (psql -U postgres should connect without error).
  3. Create a database named school, following the steps above.
  4. List your databases with \l and confirm school appears.

Recap

  • PostgreSQL installs as a background service, plus psql, its command-line client.
  • A database is created with CREATE DATABASE, and \l lists existing databases from psql.
  • The school database created here is used throughout the rest of this module.

Next lesson: connecting to that database from Node.js, using the pg driver.