Home

Connecting to your database

Supabase provides several options for programmatically connecting to your Postgres database:

  1. Direct connections using Postgres' standard connection system
  2. Connection pooling using PgBouncer
  3. Programmatic access using the Serverless APIs

Serverless APIs#

Supabase provides auto-updating APIs. This is the easiest way to get started if you are managing data (fetching, inserting, updating). We provide several types of API to suit your preferences:

  • REST: interact with your database through a REST interface.
  • GraphQL: interact with your database through a GraphQL interface.
  • Realtime: listen to database changes over websockets.

Direct connections#

Every Supabase project provides a full Postgres database. You can connect to the database using any tool which supports Postgres. You can find the connection string in the Database settings inside the dashboard:

  1. Go to the Settings section.
  2. Click Database.
  3. Find your Connection Info and Connection String. Direct connections are on port 5432.

Connection Pooler#

Every Supabase project comes with PgBouncer for connection pooling. A connection pooler is useful for managing a large number of temporary connections. For example, if you are using Prisma, Drizzle, Kysely, or anything deployed to a Serverless environment (AWS Lambdas or Edge Functions). You can find the connection pool config in the Database settings inside the dashboard:

  1. Go to the Settings section.
  2. Click Database.
  3. Find your Connection Info and Connection String. Connection pooling is on port 6543.

Supavisor#

note

PgBouncer is being deprecated in favor of Supavisor. Supavisor is available on all new and existing projects.

On 15th January 2024 PgBouncer will be disabled. Additionally, your Supabase database domain (db.projectref.supabase.co) will start resolving to an IPv6 address. No changes are required if your network supports communicating via IPv6. Otherwise, update your applications to use Supavisor which will continue to support IPv4 connections.

Full details here.

Supavisor is a new connection pooler by Supabase. It can provide a more scalable connection pool than PgBouncer, and runs on a high-availability cluster segregated from your database.

This can free up some CPU cycles for your database to use for queries. It also makes connecting to Postgres in a serverless environment much easier.

We're building compatibility with PgBouncer, and application changes will not be required to switch from PgBouncer to Supavisor. When a project is switched from PgBouncer to Supavisor, the appropriate connection string will be made available under the Connection Pooling section on Database settings. Note that while PgBouncer remains accessible for use, it will no longer be available for configuration from the dashboard. The PgBouncer connection string will also be similarly inaccessible from the dashboard.

Supavisor is open source and compatible with any Postgres deployment. Check out the Github repository.

Choosing a connection method#

  • The Serverless APIs provide programmatic access and have built-in connection pooling. You can use these for all browser and application interactions. We recommend using these wherever possible.
  • A "direct connection" is Postgres' native connection system. You should use this for tools which are always alive - usually installed on a long-running server, like Node.js, Ruby, Python, etc.
  • A "connection pooler" is a tool which keeps connections "alive". You should use this for serverless functions and tools which disconnect from the database frequently, like Prisma, Drizzle, Kysely, etc.

Why would you use a connection pool? Primarily because the way that Postgres handles connections isn't very scalable for a large number of temporary connections. You can use these simple questions to determine which connection method to use:

  • Are you connecting to a database and maintaining a connection? If yes, use a direct connection.
  • Are you connecting to your database and then disconnecting immediately (e.g. a serverless environment)? If yes, use a connection pool.

Connecting with SSL#

You should connect to your database using SSL wherever possible, to prevent snooping and man-in-the-middle attacks.

You can obtain your connection info and Server root certificate from your application's dashboard:

Connection Info and Certificate.

How connection pooling works#

A "connection pool" is a system (external to Postgres) which manages connections, rather than PostgreSQL's native system. Supabase uses PgBouncer for connection pooling.

When a client makes a request, PgBouncer "allocates" an available connection to the client. When the client transaction or session is completed the connection is returned to the pool and is free to be used by another client.

Connection pooling

Pgbounce provides several Pool Modes, each handling connections differently:

Session#

When a new client connects, a connection is assigned to the client until it disconnects. Afterward, the connection is returned back to the pool.

All PostgreSQL features can be used with this option.

Transaction#

This is the suggested option for serverless functions. A connection is only assigned to the client for the duration of a transaction. Two consecutive transactions from the same client could be executed over two different connections.

Some session-based PostgreSQL features such as prepared statements are not available with this option. A comprehensive list of incompatible features can be found here.

Statement#

This is the most granular option. Connections are returned to the pool after every statement. Transactions with multiple statements are not allowed. This is best used when AUTOCOMMIT is in use.

Integrations#

Connecting with Drizzle#

Drizzle ORM is a TypeScript ORM for SQL databases designed with maximum type safety in mind. You can use their ORM to connect to your database.

1

Install

Install Drizzle and related dependencies.


_10
npm i drizzle-orm postgres
_10
npm i -D drizzle-kit

2

Create your models

Create a schema.ts file and define your models.


_10
import { pgTable, serial, text, varchar } from "drizzle-orm/pg-core";
_10
_10
export const users = pgTable('users', {
_10
id: serial('id').primaryKey(),
_10
fullName: text('full_name'),
_10
phone: varchar('phone', { length: 256 }),
_10
});

3

Connect

Connect to your database using the Connection Pooler for serverless environments, and the Direct Connection for long-running servers.


_11
import { drizzle } from 'drizzle-orm/postgres-js'
_11
import postgres from 'postgres'
_11
import { users } from './schema'
_11
_11
const connectionString = process.env.DATABASE_URL
_11
_11
// Disable prefetch as it is not supported for "Transaction" pool mode
_11
const client = postgres(connectionString, { prepare: false })
_11
const db = drizzle(client);
_11
_11
const allUsers = await db.select().from(users);

Connecting with pgAdmin#

pgAdmin is a GUI tool for managing Postgres databases. You can use it to connect to your database via SSL:

1

Register

Register a new Postgres server.

Register a new postgres server.

2

Name

Name your server.

Name Postgres Server.

3

Connect

Add the connection info. You can use the "Direct connection" config, which you can find in your Supabase dashboard.

Add Connection Info.

4

SSL

Navigate to the Parameters tab and select connection parameter as Root Certificate. Next navigate to the Root certificate input, it will open up a file-picker modal. Select the certificate you downloaded from your Supabase dashboard and save the server details. PgAdmin should now be able to connect to your Postgres via SSL.

Add Connection Info.

Connecting with psql#

psql is a command-line tool that comes with Postgres.

Assuming you've downloaded your SSL certificate to $HOME/Downloads/prod-supabase.cer, and your host address is db.ref.supabase.co you connect to your database via SSL:


_10
psql "sslmode=verify-full sslrootcert=$HOME/Downloads/prod-supabase.cer host=db.ref.supabase.co dbname=postgres user=postgres"

Connecting with Postgres.js#

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

1

Install

Install Postgres.js and related dependencies.


_10
npm i postgres

2

Connect

Create a db.js file with the connection details. Use the Connection Pooler for serverless environments, and the Direct Connection for long-running servers.


_10
// db.js
_10
import postgres from 'postgres'
_10
_10
const connectionString = process.env.DATABASE_URL
_10
const sql = postgres(connectionString)
_10
_10
export default sql

3

Execute commands

Use the connection to execute commands.


_11
import sql from './db.js'
_11
_11
async function getUsersOver(age) {
_11
const users = await sql`
_11
select name, age
_11
from users
_11
where age > ${ age }
_11
`
_11
// users = Result [{ name: "Walter", age: 80 }, { name: 'Murray', age: 68 }, ...]
_11
return users
_11
}