- Published on
PostgreSQL and Node.js with TypeScript: A Practical Guide to Building Robust Applications
- Authors
- Name
- Jonas de Oliveira
In today's demanding development landscape, having a robust and high-performing relational database is essential for creating scalable and secure applications. PostgreSQL stands out by offering advanced features, high SQL compliance, and consistent performance. When combined with Node.js and TypeScript, you gain a powerful stack that merges the productivity of modern JavaScript with the safety of static typing.
In this article, we'll walk you through how to set up and use PostgreSQL with Node.js using TypeScript. We'll present a practical example demonstrating CRUD (Create, Read, Update, Delete) operations using the pg
package, complete with detailed code comments to help you understand every step.
Why PostgreSQL?
PostgreSQL is an open-source relational database renowned for its robustness, scalability, and adherence to SQL standards. Its key advantages include:
- ACID Compliance: Ensures transaction integrity and reliability.
- Advanced Features: Supports complex indexing, advanced queries, replication, and partitioning.
- Flexibility: Allows the creation of functions and stored procedures in multiple languages.
- Active Community: Benefits from a large support community and a wealth of extensions to enhance functionality.
Setting Up the Environment
1. Install PostgreSQL
Ensure PostgreSQL is installed on your machine or use a cloud instance such as Heroku Postgres or ElephantSQL.
2. Create a Node.js Project with TypeScript
Open your terminal and run the following commands to create and configure your project:
mkdir postgres-node-ts
cd postgres-node-ts
npm init -y
3. Install Required Dependencies
Install the pg
package and development dependencies:
npm install pg
npm install --save-dev typescript ts-node @types/node @types/pg
4. Create a TypeScript Configuration File
Create a tsconfig.json
file in the project root with the following content:
{
"compilerOptions": {
"target": "es6",
"module": "commonjs",
"strict": true,
"esModuleInterop": true,
"outDir": "./dist"
},
"include": ["src"]
}
Practical Example: CRUD Operations with PostgreSQL
In this example, we'll create a file src/index.ts
to demonstrate basic CRUD operations using the pg
package and TypeScript.
// src/index.ts
import { Client } from 'pg';
// Define the connection string for PostgreSQL.
// It's recommended to store sensitive credentials in environment variables.
const connectionString = process.env.DATABASE_URL || 'postgresql://user:password@localhost:5432/mydb';
// Create an instance of Client to manage the database connection.
const client = new Client({ connectionString });
async function main() {
try {
// Connect to the PostgreSQL database.
await client.connect();
console.log('Connected to PostgreSQL');
// --- CREATE: Insert a new record into the "users" table ---
// Ensure that the "users" table exists. For example, you can create it with:
// CREATE TABLE users (id SERIAL PRIMARY KEY, email VARCHAR(255) UNIQUE, name VARCHAR(255));
const insertQuery = 'INSERT INTO users (email, name) VALUES ($1, $2) RETURNING *';
const insertValues = ['john.doe@example.com', 'John Doe'];
const insertResult = await client.query(insertQuery, insertValues);
const newUser = insertResult.rows[0];
console.log('New user created:', newUser);
// --- READ: Retrieve all records from the "users" table ---
const selectQuery = 'SELECT * FROM users';
const selectResult = await client.query(selectQuery);
console.log('Users found:', selectResult.rows);
// --- UPDATE: Update a user's name ---
const updateQuery = 'UPDATE users SET name = $1 WHERE id = $2 RETURNING *';
const updateValues = ['Johnathan Doe', newUser.id];
const updateResult = await client.query(updateQuery, updateValues);
console.log('User updated:', updateResult.rows[0]);
// --- DELETE: Remove a user ---
const deleteQuery = 'DELETE FROM users WHERE id = $1 RETURNING *';
const deleteValues = [newUser.id];
const deleteResult = await client.query(deleteQuery, deleteValues);
console.log('User removed:', deleteResult.rows[0]);
} catch (error) {
console.error('Error performing CRUD operations:', error);
} finally {
// Close the connection to the database.
await client.end();
console.log('Disconnected from PostgreSQL');
}
}
// Execute the main function.
main().catch((err) => {
console.error('General error:', err);
});
Code Comments Explained
- Connection Setup:
- We import the
Client
from thepg
package and set up the connection string for PostgreSQL. - It’s best practice to store your credentials securely using environment variables.
- We import the
- CRUD Operations:
- CREATE: Inserts a new user into the
users
table and returns the newly created record. - READ: Retrieves all users from the
users
table. - UPDATE: Updates the
name
field of the newly inserted user and returns the updated record. - DELETE: Removes the user record from the database and returns the deleted record.
- CREATE: Inserts a new user into the
- Error Handling and Cleanup:
- The
try...catch...finally
block ensures that errors are handled gracefully and that the database connection is properly closed, preventing resource leaks.
- The
Running the Code
To compile and run the example, execute the following command in your project root:
npx ts-node src/index.ts
You should see console logs confirming the connection to PostgreSQL and the results of the CRUD operations, followed by a confirmation that the connection has been closed.
Final Thoughts
Integrating PostgreSQL with Node.js using TypeScript is a practical and efficient way to build robust and scalable applications.