Neon raises $30M in Series A-1Read More

Run a Node.js app

Introduction

In this section, you will learn how to add a Postgres client to your NodeJS project and connect to your database.

Create a NodeJS project and add dependencies

Create a NodeJS project and change to the newly created directory.

mkdir neon-nodejs-example
cd neon-nodejs-example
npm init -y

Add project dependecies using the following command:

npm install postgres dotenv

Store Neon credentials

Store your Neon credentials in the .env file. Note that for security purposes, you should not expose your Neon credentials to the browser.

PGHOST='<project_name>.cloud.neon.tech:<port>'
PGDATABASE='<database>'
PGUSER='<username>'
PGPASSWORD='<password>'
PROJECT_NAME='<project_name>'

Connect to database using Postgres client and Neon credentials

To connect to the database using the Postgres client and your Neon credentials, add the following code to the app.js file:

const postgres = require('postgres');
require('dotenv').config();

const { PGHOST, PGDATABASE, PGUSER, PGPASSWORD, PROJECT_NAME } = process.env;
const URL = `postgres://${PGUSER}:${PGPASSWORD}@${PGHOST}/${PGDATABASE}?options=project%3D${PROJECT_NAME}`;

const sql = postgres(URL, { ssl: 'require' });

async function getPostgresVersion() {
  const result = await sql`select version()`;
  console.log(result);
}

getPostgresVersion();

You can now run node app.js to view the result.

Result(1) [
  {
    version: 'PostgreSQL 14.5 on x86_64-pc-linux-gnu, compiled by gcc (Debian 10.2.1-6) 10.2.1 20210110, 64-bit'
  }
]

The same configuration can be used in Express or Next.js applications.