Database

Postgres.js


Connecting with Postgres.js

Postgres.js is a full-featured Postgres client for Node.js and Deno.

1

Install

Install Postgres.js and related dependencies.

1
npm i postgres
2

Connect

Create a db.js file with the connection details.

To get your connection details, go to the Connect panel. Choose Transaction pooler if you're on a platform with transient connections, such as a serverless function, and Session pooler if you have a long-lived connection. Copy the URI and save it as the environment variable DATABASE_URL.

1
// db.js
2
import postgres from 'postgres'
3
4
const connectionString = process.env.DATABASE_URL
5
const sql = postgres(connectionString)
6
7
export default sql
3

Execute commands

Use the connection to execute commands.

1
import sql from './db.js'
2
3
async function getUsersOver(age) {
4
const users = await sql`
5
select name, age
6
from users
7
where age > ${ age }
8
`
9
// users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]
10
return users
11
}