Connect Node.js to NeonDB(PSQL)

RohitRohit
3 min read

If you're building a Node.js application and looking to connect it to a modern, serverless PostgreSQL database like Neon, this guide walks you through a simple, functional setup using the pg library.

In this example, we build a basic Student Management API using Express.js and PostgreSQL hosted on NeonDB.

Prerequisites

Before jumping in, ensure you have:

  • Node.js and npm installed (I have used node v20)

  • A NeonDB project and database created

  • Your Neon connection string (from the Neon dashboard)

  • A .env file in your project with:

DATABASE_URL=your_neon_connection_string

Setting Up the Database Connection

We use the pg library to connect to Neon. The configuration is simple and uses a connection string from the .env file:

api-handler.js

const pg = require("pg");
const { Pool } = pg;
const dotenv = require("dotenv");
dotenv.config();

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

This initializes a pool of connections to NeonDB. This setup is scalable and production-friendly.

API Endpoints Overview

Here's what the API supports:

MethodEndpointDescription
GET/v1/healthcheckChecks DB connection
GET/v1/studentsGet all students
GET/v1/students/:idGet student by ID
POST/v1/studentsAdd new student
PUT/v1/students/:idUpdate student
DELETE/v1/students/:idDelete student

All these handlers are defined in api-handler.js, making use of async/await and parameterized queries to avoid SQL injection.

Example: Add a Student

To add a student, the handler dynamically builds the insert query based on the request body:

exports.addStudentEntry = (req, res) => {
  const { name, age, department } = req.body;
  const dbArgs = Object.keys(req.body);
  const dbVals = [name, age, department];

  const query = `INSERT INTO students(${dbArgs.join(",")}) VALUES($1,$2,$3) RETURNING *;`;

  pool.query(query, dbVals)
    .then((result) => res.send(result.rows[0]))
    .catch((e) => console.log("Insert error:", e));
};

This is clean, safe, and works perfectly with PostgreSQL on Neon.

Starting the Express Server

The Express app is simple and loads routes directly from api-handler.js.

index.js

const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
dotenv.config();

const {
  getHealthCheck,
  getStudentById,
  getAllStudents,
  addStudentEntry,
  updateStudentEntry,
  deleteStudentEntry,
} = require("./api-handler");

const app = express();
const port = 3000;

app.use(cors({ origin: "*" })); // this is for illustration purpose DO NOT THIS ON PRODUCTION
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

app.get("/v1/healthcheck", getHealthCheck);
app.get("/v1/students/:id", getStudentById);
app.route("/v1/students")
  .get(getAllStudents)
  .post(addStudentEntry);
app.route("/v1/students/:id")
  .put(updateStudentEntry)
  .delete(deleteStudentEntry);

app.listen(port, () => {
  console.log(`Server running at http://127.0.0.1:${port}`);
});

Testing Your Setup

  1. Ensure your .env has the correct NeonDB connection string.

  2. Run the app:

node index.js
  1. Use curl, Postman, or a browser to test endpoints like:
curl http://localhost:3001/v1/students
0
Subscribe to my newsletter

Read articles from Rohit directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Rohit
Rohit

I'm a results-driven professional skilled in both DevOps and Web Development. Here's a snapshot of what I bring to the table: ๐Ÿ’ป DevOps Expertise: AWS Certified Solutions Architect Associate: Proficient in deploying and managing applications in the cloud. Automation Enthusiast: Leveraging Python for task automation, enhancing development workflows. ๐Ÿ”ง Tools & Technologies: Ansible, Terraform, Docker, Prometheus, Kubernetes, Linux, Git, Github Actions, EC2, S3, VPC, R53 and other AWS services. ๐ŸŒ Web Development: Proficient in HTML, CSS, JavaScript, React, Redux-toolkit, Node.js, Express.js and Tailwind CSS. Specialized in building high-performance websites with Gatsby.js. Let's connect to discuss how my DevOps skills and frontend expertise can contribute to your projects or team. Open to collaboration and always eager to learn! Aside from my work, I've also contributed to open-source projects, like adding a feature for Focalboard Mattermost.