Fixing PostgreSQL + Node.js Setup Issues: A Debugging Journey
Fixing PostgreSQL + Node.js Setup Issues: A Debugging Journey
When I first set up a Node.js + PostgreSQL project, I didn’t realize how many little pitfalls were waiting for me. From port conflicts to authentication failures, the process was full of surprises. This article documents the exact problems I faced and how I solved them — so if you’re a beginner dealing with the same errors, you won’t have to spend hours debugging like I did.
---
Problem 1: Port Already in Use (EADDRINUSE)
When I ran my server with:
npm run dev
I got this error:
Error: listen EADDRINUSE: address already in use :::3000
Cause
Port 3000 was already being used by another Node process.
Solution
1. Find which process is using port 3000:
sudo lsof -i :3000
2. Kill the process by its PID:
kill -9 <PID>
3. Restart the server:
npm run dev
---
Problem 2: PostgreSQL Cluster Not Running
At first, running psql -U postgres gave me:
connection to server on socket "/var/run/postgresql/.s.PGSQL.5432" failed
Cause
The PostgreSQL cluster (17-main) wasn’t running properly.
Solution
Restart the cluster:
sudo systemctl restart postgresql@17-main
sudo systemctl status postgresql@17-main
Now the database service was up and running ✅
---
Problem 3: Password Authentication Failed
When connecting from Node.js, I saw this:
❌ Database connection error: password authentication failed for user "postgres"
Cause
The Node.js app was using the wrong credentials. By default, my db.js had:
const pool = new Pool({
user: "postgres",
host: "localhost",
database: "url_shortener",
password: "password", // ❌ wrong
port: 5432
});
Solution
1. Reset the password for the postgres user:
sudo -i -u postgres psql
ALTER USER postgres WITH PASSWORD 'my_strong_password';
\q
2. Create a .env file in the root of the project:
DB_USER=postgres
DB_PASSWORD=my_strong_password
DB_HOST=localhost
DB_PORT=5432
DB_NAME=url_shortener
3. Update the config to use environment variables:
require('dotenv').config();
const pool = new Pool({
user: process.env.DB_USER,
host: process.env.DB_HOST,
database: process.env.DB_NAME,
password: process.env.DB_PASSWORD,
port: process.env.DB_PORT,
});
---
The Sweet Moment 🎉
After restarting the server again:
npm run dev
I finally saw:
Server running on port 3000
✅ Successfully connected to PostgreSQL!
---
Key Takeaways
EADDRINUSE → means the port is already occupied. Kill the process or change the port.
Always check if your PostgreSQL cluster is running with systemctl status postgresql@<version>-main.
Manage credentials with a .env file — don’t hardcode passwords.
Use ALTER USER to reset the Postgres password if authentication fails.
---
💡 If you’re just starting out with Node.js + PostgreSQL, don’t be discouraged by these errors. They’re common, and once you’ve fixed them once, you’ll know how to handle them quickly in future projects.
