This page documents the modules and methods you can use to interact with Netlify Database from your application code.
@netlify/database
Section titled “@netlify/database”The recommended way to get started with Netlify Database is to install the @netlify/database module in your project:
npm install @netlify/databaseThis module offers a set of methods that let you seamlessly interact with your database, providing a database driver that is automatically configured and optimized for where your code is running.
getConnectionString
Section titled “getConnectionString”Returns the database connection string for the current environment, automatically pointing to the correct database branch (e.g. the production database for production deploys, or an isolated branch for deploy previews).
This is useful if you want to use your own database driver or ORM.
import { getConnectionString } from "@netlify/database";
const connectionString = getConnectionString();Return value
Section titled “Return value”A string containing the Postgres connection URL for the current environment.
Example
Section titled “Example”This example shows how you might use getConnectionString to initialize a third-party Postgres client, such as pg, with the connection string for the current environment.
import { getConnectionString } from "@netlify/database";import pg from "pg";
const pool = new pg.Pool({ connectionString: getConnectionString() });const { rows: users } = await pool.query("SELECT * FROM users");getDatabase
Section titled “getDatabase”Returns a database client that you can use to run queries using the sql and pool methods. The client is intelligently configured to use the best connection type for your environment — for example, it uses a different underlying connector when running queries from builds or a long-running server compared to when running them in Netlify Functions or Edge Functions.
import { getDatabase } from "@netlify/database";
const db = getDatabase();Parameters
Section titled “Parameters”options(optional): an object with the following properties:connectionString: a Postgres connection string to use instead of the automatically-provisioned onedebug: a boolean to enable debug logging
Return value
Section titled “Return value”A database driver object that you can use to query the database using the sql or pool methods.
A tagged template literal function for executing SQL queries safely, based on the Waddler open-source module.
Values interpolated into the template are automatically parameterized to prevent SQL injection.
const db = getDatabase();
const userId = 42;const users = await db.sql`SELECT * FROM users WHERE id = ${userId}`;Parameters
Section titled “Parameters”The sql function accepts a template literal string with interpolated values. Any JavaScript value interpolated into the template is treated as a parameterized value, not raw SQL.
You can optionally specify a generic type parameter to type the returned rows:
interface User { id: number; name: string; email: string;}
const users = await db.sql<User>`SELECT * FROM users`;Return value
Section titled “Return value”A thenable SQLTemplate object that resolves to an array of row objects.
This object also supports the following methods:
execute(): executes the query and returns aPromise<T[]>of row objectsstream(): returns anAsyncGenerator<T>that yields rows one at a timechunked(chunkSize?): returns anAsyncGenerator<T[]>that yields rows in chunks of the specified sizetoSQL(): returns the raw SQL string and parameters without executing the query
Example
Section titled “Example”This example shows common CRUD operations using the sql tagged template, including selecting, inserting, updating, and deleting rows, as well as streaming results for large datasets.
import { getDatabase } from "@netlify/database";
const db = getDatabase();
// Select with a conditionconst activeUsers = await db.sql`SELECT * FROM users WHERE active = ${true}`;
// Insert a rowawait db.sql`INSERT INTO users (name, email) VALUES (${"Ada"}, ${"ada@example.com"})`;
// Update a rowawait db.sql`UPDATE users SET name = ${"Ada Lovelace"} WHERE id = ${1}`;
// Delete a rowawait db.sql`DELETE FROM users WHERE id = ${1}`;
// Stream rows one at a timefor await (const row of db.sql`SELECT * FROM users`.stream()) { console.log(row);}
// Stream rows in chunksfor await (const chunk of db.sql`SELECT * FROM users`.chunked(100)) { console.log(`Processing ${chunk.length} rows`);}The sql function also exposes the following helpers:
-
sql.identifier(value): creates a safe SQL identifier for dynamically referencing table or column names. Accepts a string, an array of strings, or an object withschema,table,column, andasproperties.const table = db.sql.identifier({ table: "users" });const rows = await db.sql`SELECT * FROM ${table}`; -
sql.values(value): creates a values list for bulk inserts. Accepts a two-dimensional array where each inner array represents a row.const data = db.sql.values([["Ada", "ada@example.com"],["Bob", "bob@example.com"],]);await db.sql`INSERT INTO users (name, email) VALUES ${data}`; -
sql.raw(value): injects a raw, unparameterized value into a query. Accepts a string, number, boolean, or bigint. Use with caution — this bypasses SQL injection protection.const order = db.sql.raw("DESC");const users = await db.sql`SELECT * FROM users ORDER BY name ${order}`; -
sql.unsafe(query, params?, options?): executes a raw SQL query string. Accepts a query string, an optional array of parameter values, and an optional options object with arowModeproperty ("array"or"object").const results = await db.sql.unsafe("SELECT * FROM users WHERE id = $1", [42]); -
sql.default: a constant representing the SQLDEFAULTkeyword, for use when inserting rows that should use the column’s default value.await db.sql`INSERT INTO users (name, created_at) VALUES (${"Ada"}, ${db.sql.default})`;
A pg.Pool connection pool instance. Use this when you need direct control over the connection lifecycle — most commonly for transactions, where BEGIN, your queries, and COMMIT/ROLLBACK must all run on the same connection.
Example
Section titled “Example”This example shows how you might use the connection pool to run a transaction that inserts a user and their first post atomically — if either insert fails, both are rolled back.
import { getDatabase } from "@netlify/database";
const db = getDatabase();
const client = await db.pool.connect();try { await client.query("BEGIN"); await client.query( "INSERT INTO users (name, email) VALUES ($1, $2)", ["Ada", "ada@example.com"] ); await client.query( "INSERT INTO posts (author_id, title) VALUES ($1, $2)", [1, "First post"] ); await client.query("COMMIT");} catch (e) { await client.query("ROLLBACK"); throw e;} finally { client.release();}REST API
Section titled “REST API”The Netlify REST API exposes endpoints for managing databases, branches, and snapshots programmatically. All endpoints are scoped to a site, are rooted at https://api.netlify.com/api/v1, and authenticate via OAuth 2 — see the full Netlify API reference for authentication details and shared response shapes.
POST /sites/{site_id}/database
Section titled “POST /sites/{site_id}/database”Creates a new database for the specified site. If a database already exists, returns the existing connection string. The database region defaults to the site’s functions region if not specified.
Request body
region(string, optional): the region where the database should be created
Response — 201 Created, or 200 OK if a database already exists
connection_string(string): the connection string for the database
GET /sites/{site_id}/database
Section titled “GET /sites/{site_id}/database”Returns the database connection string for the specified site.
Response — 200 OK
connection_string(string): the connection string for the database
POST /sites/{site_id}/database/branch
Section titled “POST /sites/{site_id}/database/branch”Creates a new database branch for a deploy. If a branch already exists for the specified deploy ID, returns the existing connection string.
Request body
deploy_id(string, required): the deploy ID to associate with this branchparent_branch_id(string, optional): the ID of the parent branch to fork from; defaults to the production branch
Response — 201 Created, or 200 OK if a branch already exists for this deploy
connection_string(string): the connection string for the database branch
GET /sites/{site_id}/database/branch/{deploy_id}
Section titled “GET /sites/{site_id}/database/branch/{deploy_id}”Returns the database branch connection string for a specific deploy. Returns 404 if no branch exists for the deploy.
Response — 200 OK
connection_string(string): the connection string for the database branch
DELETE /sites/{site_id}/database/branch/{deploy_id}
Section titled “DELETE /sites/{site_id}/database/branch/{deploy_id}”Deletes the database branch associated with a deploy.
Response — 204 No Content
POST /sites/{site_id}/database/snapshot
Section titled “POST /sites/{site_id}/database/snapshot”Creates a point-in-time snapshot of a database branch. Defaults to the production branch if no branch name is specified.
Request body
branch_name(string, optional): the name of the branch to snapshot; defaults toproductionname(string, optional): an optional name for the snapshot
Response — 201 Created
id(string): the unique identifier of the snapshottimestamp(string, ISO 8601): the timestamp when the snapshot was createdsource_branch_id(string): the ID of the branch that was snapshotted
GET /sites/{site_id}/database/snapshots
Section titled “GET /sites/{site_id}/database/snapshots”Returns all snapshots for the site’s database.
Response — 200 OK
snapshots(array): list of snapshot objects withid,timestamp, andsource_branch_idfields
DELETE /sites/{site_id}/database/snapshot/{snapshot_id}
Section titled “DELETE /sites/{site_id}/database/snapshot/{snapshot_id}”Deletes a database snapshot.
Response — 204 No Content
POST /sites/{site_id}/database/snapshot/{snapshot_id}/restore
Section titled “POST /sites/{site_id}/database/snapshot/{snapshot_id}/restore”Restores a snapshot to a database branch. Defaults to the production branch if no branch name is specified.
Request body
branch_name(string, optional): the name of the branch to restore the snapshot to; defaults toproduction
Response — 200 OK
Did you find this doc useful?
Your feedback helps us improve our docs.