Prerequisites
-
Choose a Code Editor:
It is recommended to use Visual Studio Code (VS Code) for its powerful features, extensive extensions, and excellent support for JavaScript and Node.js.
Alternatives include Sublime Text, Atom, or any other code editor of your choice.
1. Installing Node.js
-
Download & Install:
Download Node.js from the official website and install the LTS version for stability. -
Verification:
Confirm the installation by running:node -v npm -v
Both commands should return valid version numbers.
2. Setting Up PostgreSQL
-
Installation:
Download and install PostgreSQL from postgresql.org/download. -
Configuration:
Set a password for thepostgres
superuser during installation. -
Verification:
Verify the installation by running:psql -U postgres
Enter your password to confirm access.
If you encounter an error (e.g., “could not connect to server” or “password authentication failed”), ensure that the PostgreSQL service is running and that your credentials are correct. Check your system’s service status (using `sudo service postgresql status` on Linux or `brew services list` on macOS) and review your `pg_hba.conf` configuration if necessary. -
Database & User Setup:
Create a database and a dedicated user (if not done already):CREATE DATABASE my_test_db; CREATE USER my_app_user WITH PASSWORD 'mypassword'; GRANT ALL PRIVILEGES ON DATABASE my_test_db TO my_app_user;
-
Additional Resources:
For a detailed guide on setting up PostgreSQL with PGAdmin, check out
How to Set Up a PostgreSQL Database in PGAdmin: A Step-by-Step Guide.
3. Setting Up the Project Directory
-
Initialize Project Directory:
mkdir my-backend-project cd my-backend-project npm init -y
Project structure after this step:
my-backend-project/ └── package.json
-
Install Required Dependencies:
npm install pg dotenv
Why these packages?
-
pg
: PostgreSQL client to connect and interact with the PostgreSQL database. -
dotenv
: Securely manages sensitive information through environment variables.
Project structure after installing dependencies:
my-backend-project/ ├── node_modules/ ├── package-lock.json └── package.json
-
4. Configuring Environment Variables
-
Create
.env
file:
Add database credentials securely to.env
:DB_HOST=localhost DB_PORT=5432 DB_USER=my_app_user DB_PASSWORD=mypassword DB_NAME=my_test_db
Updated project structure after adding
.env
:my-backend-project/ ├── .env ├── node_modules/ ├── package-lock.json └── package.json
5. Writing Database Connection Script
-
Create
index.js
:
Add a connection test script inindex.js
:require('dotenv').config(); const { Pool } = require('pg'); const pool = new Pool({ host: process.env.DB_HOST, port: process.env.DB_PORT, user: process.env.DB_USER, password: process.env.DB_PASSWORD, database: process.env.DB_NAME }); async function testConnection() { try { const result = await pool.query('SELECT NOW()'); console.log('Connection successful:', result.rows[0]); } catch (error) { console.error('Connection error:', error); } finally { await pool.end(); } } testConnection();
Updated project structure after creating
index.js
:my-backend-project/ ├── .env ├── index.js ├── node_modules/ ├── package-lock.json └── package.json
6. Testing the Database Connection
-
Run your script:
node index.js
The output will be displayed in your terminal (console). You should see output similar to:
Connection successful: { now: '2025-03-22T10:15:00.000Z' }
7. Common Debugging Steps
-
Issue:
Connection refused
orcould not connect to server
- Cause: PostgreSQL service isn’t running.
- Solution: Start PostgreSQL:
# Linux: sudo service postgresql start # macOS (Homebrew): brew services start postgresql # Windows: # Use Windows Services tool to start PostgreSQL.
-
Issue:
password authentication failed
- Cause: Incorrect username/password.
- Solution: Verify or reset credentials:
ALTER USER my_app_user WITH PASSWORD 'mypassword';
-
Issue:
relation "table_name" does not exist
- Cause: Querying a non-existent table.
- Solution: Create the table first:
CREATE TABLE test_table ( id SERIAL PRIMARY KEY, name VARCHAR(255) NOT NULL );
-
General Debugging Tips:
- Read the full error messages carefully.
- Check database host, port, and credentials.
- Ensure the PostgreSQL service is active.
High-Level Interaction Diagram
The diagram below illustrates the interactions among Node.js, PostgreSQL, and the environment configuration:
Explanation:
- Node.js: Loads sensitive configurations from
.env
and establishes a connection with PostgreSQL using thepg
module. - .env: Contains sensitive information like database host, port, user, password, and name.
- PostgreSQL: Handles the database queries and returns results to Node.js.
Next Steps
- Create basic REST API endpoints using frameworks like Express.js.
- Handle CRUD operations with PostgreSQL.
- Implement better error handling, logging, and additional security features.
Further Parts in the “Learning Backend” Series
- Part 2: Building a REST API with Express.js
- Part 3: Implementing Database CRUD Operations
- Part 4: Authentication, Authorization, and Security
Join the Conversation
Share your experiences and insights with other learners and developers:
- What resources or techniques helped you the most?
- What challenges did you face?
- Do you have recommendations to share?
Happy coding! 🚀
Pingback: Learning Backend – Part 2: Building a REST API with Express.js – Minhaz Panara