Next.js Zero to Advanced #5: Setting Up PostgreSQL
In Part 4 we styled DigiStore with Tailwind CSS, next/image and next/font. It now looks like a real store, but its data is still an array in lib/products.ts. Data like that disappears on every server restart, cannot be edited by an admin and cannot store users' orders. In Part 5 we will set up PostgreSQL, the database that will store all of DigiStore's data permanently.
This part intentionally contains no Next.js code at all. We focus on the foundation: running PostgreSQL 16 locally (with or without Docker), creating the digistore database, connecting with psql, and storing the connection address safely in .env. Prisma will use this foundation in Part 6.
What is a relational database?
A relational database stores data in tables made of rows and columns, similar to a spreadsheet but much stricter and more reliable. Each table has a primary key (for example an id column) that is unique for every row. Tables can be connected through foreign keys: columns that store the id of a row in another table. That is what "relation" means.
For DigiStore we will have three main tables:
| Table | Contents | Example columns |
|---|---|---|
User | Buyer and admin accounts | id, email, role |
Product | Digital products | id, slug, price |
Order | Orders: who bought what | id, userId, productId |
The Order table stores a userId and a productId. With these relations we can answer questions such as "which products did user X buy?" without copying user and product data into every order.
Why PostgreSQL?
- Open source and mature: used from small projects to large companies.
- Reliable: supports transactions (ACID), constraints and indexes that keep data consistent.
- Available everywhere: almost every cloud provider offers managed PostgreSQL, which we will use when deploying in Part 12.
- Fully supported by Prisma, the ORM we will use from Part 6.
This part covers just enough PostgreSQL for DigiStore. If you want to understand SQL more deeply (tables, constraints, JOINs, indexes), read the PostgreSQL Zero to Advanced series, especially the part on relations and JOINs.
Option 1: Running PostgreSQL 16 with Docker
Docker is the most practical way: PostgreSQL runs inside an isolated container, doesn't clutter your system, and the version is exactly the same on every team member's machine. Install Docker Desktop (macOS/Windows) or Docker Engine (Linux), then make sure Docker is running:
docker --version
docker info
If docker info shows a "Cannot connect to the Docker daemon" error, open the Docker Desktop app first.
Preparing a password without typing it into the command
PostgreSQL in Docker needs a password for the database user. Don't type the password directly into the docker run command, because commands are saved in your terminal history. We generate a random password and store it in an environment variable for the terminal session:
# macOS / Linux: generate a random local password for this terminal session
export POSTGRES_PASSWORD="$(openssl rand -hex 16)"
echo "$POSTGRES_PASSWORD" # copy this value, you will need it for .env
We use openssl rand -hex 16 because the output only contains the letters a-f and digits. Characters like @, /, # or $ in a password cause trouble when written in a connection URL later. Windows users can generate a random password with a password manager and run $env:POSTGRES_PASSWORD="..." in PowerShell. Remember: this password is only for the local database on your laptop; never reuse it in production.
Running the container
docker run -d \
--name digistore-db \
-e POSTGRES_USER=digistore \
-e POSTGRES_PASSWORD="$POSTGRES_PASSWORD" \
-e POSTGRES_DB=digistore \
-p 127.0.0.1:5432:5432 \
-v digistore-pgdata:/var/lib/postgresql/data \
postgres:16
What each option does:
-d: runs in the background.--name digistore-db: a container name that is easy to refer to.POSTGRES_USER,POSTGRES_PASSWORD,POSTGRES_DB: automatically create thedigistoreuser and thedigistoredatabase when the container is first created.-p 127.0.0.1:5432:5432: opens port 5432 only to your own computer (localhost). Without127.0.0.1:, the database could be reached from other devices on the same network, such as café Wi-Fi.-v digistore-pgdata:/var/lib/postgresql/data: stores data in a Docker volume, so it isn't lost when the container is stopped or recreated.postgres:16: the official PostgreSQL 16 image.
Check that the container is running:
docker ps --filter name=digistore-db
Result:
CONTAINER ID IMAGE STATUS PORTS NAMES
3f2a1b9c8d7e postgres:16 Up 10 seconds 127.0.0.1:5432->5432/tcp digistore-db
Everyday commands
docker stop digistore-db # stop the database
docker start digistore-db # start it again (data is kept in the volume)
docker logs digistore-db # read the logs if something goes wrong
# Danger: deletes the container AND all data in the volume
docker rm -f digistore-db
docker volume rm digistore-pgdata
After a computer restart the container usually stops. Just run docker start digistore-db before npm run dev. The docker volume rm command deletes all data permanently, so use it carefully.
Option 2: Without Docker
If you can't or don't want to use Docker, install PostgreSQL 16 directly:
- macOS: Postgres.app or Homebrew.
- Windows: the official installer from postgresql.org. The installer asks for a password for the
postgresuser; keep it in a password manager. - Linux: packages from your distribution or the official PostgreSQL repository.
# macOS (Homebrew)
brew install postgresql@16
brew services start postgresql@16
# Ubuntu / Debian
sudo apt install postgresql
sudo systemctl start postgresql
Then create a user and a database for DigiStore. Open psql as a superuser and run:
-- run as a PostgreSQL superuser, e.g.: psql -d postgres (or: sudo -u postgres psql)
CREATE USER digistore WITH PASSWORD 'replace-with-your-local-password';
CREATE DATABASE digistore OWNER digistore;
Replace replace-with-your-local-password with your own local password (use a random one as shown above). The end result is the same as the Docker option: a digistore user and a digistore database on localhost:5432.
Connecting with psql
psql is PostgreSQL's official command-line client. With Docker, you can use the psql that already lives inside the container:
docker exec -it digistore-db psql -U digistore -d digistore
Inside psql, try the following commands. Commands starting with a backslash (\) are psql meta-commands, while the rest is regular SQL ending with a semicolon:
-- inside psql
SELECT version();
\conninfo
\l
\dt
\q
SELECT version();: shows the PostgreSQL version (should be 16.x).\conninfo: information about the current connection.\l: lists databases.\dt: lists tables in the current database.\q: quits.
Result:
digistore=# \conninfo
You are connected to database "digistore" as user "digistore" via socket in "/var/run/postgresql" at port "5432".
digistore=# \dt
Did not find any relations.
"Did not find any relations" means the database is still empty, which is exactly what we expect. The User, Product and Order tables will be created by Prisma Migrate in Part 6, not written by hand.
Storing DATABASE_URL in .env
Our app (and Prisma) needs to know how to connect to the database. This information is written as a single string called a connection URL, in this format:
postgresql://USER:PASSWORD@HOST:PORT/DATABASE?schema=public
USERandPASSWORD: the database credentials (digistoreand your local password).HOSTandPORT:localhostand5432.DATABASE:digistore.?schema=public: the PostgreSQL schema Prisma uses (defaultpublic).
Create a .env file in the root of the digistore folder (next to package.json):
# .env (NEVER commit this file)
# TODO: Securely load this value from an environment variable or secrets vault. Do not hardcode.
DATABASE_URL="postgresql://digistore:YOUR_LOCAL_PASSWORD@localhost:5432/digistore?schema=public"
Replace YOUR_LOCAL_PASSWORD with the $POSTGRES_PASSWORD value you generated earlier. Next.js automatically loads .env* files into process.env, and because the variable name doesn't start with NEXT_PUBLIC_, its value is only available on the server and never sent to the browser. Never add the NEXT_PUBLIC_ prefix to secrets such as DATABASE_URL.
Testing the connection URL
If psql is installed on your machine (the non-Docker option, or a separately installed psql client), test the exact same URL that is in .env:
# if psql is installed on your machine
psql "postgresql://digistore:YOUR_LOCAL_PASSWORD@localhost:5432/digistore" -c "SELECT current_database(), current_user;"
Result:
current_database | current_user
------------------+--------------
digistore | digistore
(1 row)
If this command works, Prisma in Part 6 will be able to connect too.
Never commit secrets
The .env file contains the database password. If it ends up in Git and gets pushed to GitHub, anyone with access to the repository can read the password, even after you delete it in a later commit, because it stays in Git history.
Check .gitignore
Open .gitignore. The create-next-app template usually already contains a .env* line. Make sure it is there, then add an exception for the example file:
# env files (can opt-in for committing if needed)
.env*
!.env.example
Then prove that Git really ignores .env:
git check-ignore -v .env
git status
Result (the line number may differ):
.gitignore:34:.env* .env
If git check-ignore prints nothing, .env is not ignored. Fix .gitignore before committing anything.
Create .env.example for your team
So teammates know which variables are required, create .env.example with the variable names and value formats, but no real values:
# .env.example (safe to commit: no real values)
DATABASE_URL="postgresql://USER:PASSWORD@localhost:5432/digistore?schema=public"
The !.env.example line in .gitignore lets this example file be committed, while the real .env stays ignored.
If a password was ever committed by accident, deleting the file is not enough. Treat the password as leaked: change the database password, then clean up Git history if needed.
Common mistakes
- Port 5432 is already in use. Usually another PostgreSQL is running. Stop it, or run the container with
-p 127.0.0.1:5433:5432and change the port inDATABASE_URLto5433. - A password with special characters. Characters like
@,:,/or#must be URL-encoded in a connection URL (for example@becomes%40). In addition, Next.js expands$NAMEin.envfiles as a reference to another variable, so a password containing$can silently change. A hexadecimal password avoids both problems. - Changing
POSTGRES_PASSWORDafter the container was created. This variable is only used while the volume is empty. If you recreate the container with a new password but the old volume, the old password still applies. - Forgetting to start the container after a restart, which leads to a "connection refused" error. Run
docker start digistore-db. - Exposing the port to the whole network with
-p 5432:5432. For local development, bind to127.0.0.1. - Committing the
.envfile or adding theNEXT_PUBLIC_prefix toDATABASE_URL. Both leak credentials.
Exercises
- In psql, create a test table
CREATE TABLE coba (id serial PRIMARY KEY, nama text);, insert two rows, show them withSELECT, then remove it withDROP TABLE coba;so the database is clean again for Part 6. - Stop the container with
docker stop, start it again withdocker start, then prove that thedigistoredatabase still exists with\l. - Create a new Git repository (or use the existing one), run
git status, and make sure.envdoes not appear while.env.exampledoes.
Summary
- A relational database stores data in tables connected through primary keys and foreign keys.
- PostgreSQL 16 can run with Docker (
postgres:16, port bound to127.0.0.1, data in a volume) or be installed directly. - The database password is generated randomly and read from an environment variable, not typed into commands or code.
psqlis used to connect and inspect the database:\conninfo,\l,\dt,\q.DATABASE_URLlives in.env, is only available on the server and must never get aNEXT_PUBLIC_prefix..envis ignored by Git; a.env.examplewithout real values is committed as documentation.
The database is running and its address is stored safely. In Part 6 we will install Prisma, define the User, Product and Order models, run our first migration, and fill the database with initial data using a seed script. See you there!
Related articles
PostgreSQL Zero to Advanced #1: Introduction & Setup
Start the series by understanding what a relational database is, installing PostgreSQL locally, and getting comfortable with psql commands like \l, \c and \dt.
PHP Zero to Advanced #5: Arrays & Array Functions
Master PHP arrays: indexed and associative arrays, nested data, destructuring, and the essential functions array_map, array_filter, array_reduce, usort, and friends.
Ruby on Rails Zero to Advanced #5: Routing, Controllers & Views
Follow a request through Rails: define routes, use resources, read params in controllers, and render dynamic HTML with ERB views and partials.