Use this skill whenever a Netlify project needs a Postgres database. It covers Netlify Database setup, queries from Functions or Edge Functions, schema changes through migrations in netlify/database/migrations, Drizzle ORM wiring, local dev databases and tests, deploy-preview database branches, and moving off Neon, Supabase, RDS or the legacy @netlify/neon extension. Activate it when someone asks to add a database, store users or posts or orders, save form submissions, create or alter a table, add a column, write a migration, set up Drizzle, fix a failing migration deploy, seed or test against a local database, or switch an existing Postgres app onto Netlify. Use it even if the request never says Netlify Database explicitly.
Capabilities
Use this, not that
Netlify Database reads NETLIFY_DB_URL
File layout
Drizzle
Transactions require db.pool
Getting started
Full instructionsExample command
Install
npm install @netlify/database # required: its presence triggers provisioningInstructions: SKILL.mdv1.0.40
Netlify Database
Managed Postgres built into Netlify. Netlify provisions the database, applies migrations on deploy, and creates a database branch for every deploy preview and agent run.
Use this, not that
// ✅ Modern: auto-configured, branch-aware
import { getDatabase } from "@netlify/database";
const db = getDatabase();
const users = await db.sql`SELECT * FROM users WHERE id = ${id}`;
// ✅ Drizzle: native adapter, connection configured automatically
import { drizzle } from "drizzle-orm/netlify-db";
export const db = drizzle({ schema });
// ❌ Legacy Neon extension: do not write new code with it
import { neon } from "@netlify/neon"; // reads NETLIFY_DATABASE_URL
Netlify Database reads NETLIFY_DB_URL. It does not read NETLIFY_DATABASE_URL.
Install
npm install @netlify/database # required: its presence triggers provisioning
npm install drizzle-orm@beta && npm install -D drizzle-kit@beta # Drizzle: @beta is mandatory
npm install -g netlify-cli # CLI 26.0.0+, Node 20.12.2+
Or run netlify database init --yes. It is non-interactive: it installs packages, scaffolds a starter migration, and verifies connectivity.
⚠️ No
@netlify/databaseinstalled means no database. Automatic provisioning only happens when the package is in the project. Without it, nothing is provisioned on deploy.
⚠️ Costs credits. Netlify Database is available on Credit-based plans only. An active database consumes credits for compute and bandwidth. Storage is currently free. Every active deploy preview uses one branch toward the plan's branch limit.
File layout
netlify/database/migrations/ # auto-applied on deploy; do not move
├── 20260301143000_create_users.sql # SQL-file format
└── 20260318091500_add_posts/migration.sql # subdirectory format
netlify/functions/*.ts # query from here or from edge functions
drizzle.config.ts # if using Drizzle
db/schema.ts, db/index.ts # Drizzle schema and client
Migration name format is <number>_<slug>:
- The slug may contain only
[a-z0-9_-]. - Migrations are sorted lexicographically. Use timestamp prefixes.
- A migration's name is its filename minus the extension.
Function example
// netlify/functions/users.ts
import type { Config } from "@netlify/functions";
import { getDatabase } from "@netlify/database";
const db = getDatabase();
export default async (req: Request) => {
if (req.method === "GET") {
return Response.json(await db.sql`SELECT * FROM users ORDER BY id DESC`);
}
if (req.method === "POST") {
const { name, email } = await req.json();
const [user] = await db.sql`INSERT INTO users (name, email) VALUES (${name}, ${email}) RETURNING *`;
return Response.json(user, { status: 201 });
}
return new Response("Method not allowed", { status: 405 });
};
export const config: Config = { path: "/api/users" };
-- netlify/database/migrations/20260301143000_create_users.sql
CREATE TABLE users (
id SERIAL PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
created_at TIMESTAMP DEFAULT NOW()
);
Drizzle
// drizzle.config.ts
import { defineConfig } from "drizzle-kit";
export default defineConfig({
dialect: "postgresql",
schema: "./db/schema.ts",
out: "netlify/database/migrations", // REQUIRED: the default "drizzle" dir is never applied
});
// db/schema.ts
import { pgTable, serial, text, timestamp } from "drizzle-orm/pg-core";
export const users = pgTable("users", {
id: serial().primaryKey(),
name: text().notNull(),
email: text().notNull().unique(),
createdAt: timestamp().defaultNow(),
});
// db/index.ts
import { drizzle } from "drizzle-orm/netlify-db";
import * as schema from "./schema";
export const db = drizzle({ schema });
After changing the schema:
- Run
npx drizzle-kit generate. - Commit the generated files under
netlify/database/migrations/. - Deploy.
API: @netlify/database
| Call | Returns |
|---|---|
getDatabase(options?) |
Client with sql and pool. Options: connectionString, debug. Picks the right connector per runtime. |
getConnectionString() |
Postgres URL for the current branch (production or preview), for your own driver. |
process.env.NETLIFY_DB_URL |
Same URL, available in builds, functions, edge functions, and agent runners. |
db.sql
db.sql is a tagged template (Waddler). Every ${} value is a bound parameter. The result is awaitable and resolves to T[].
const rows = await db.sql<User>`SELECT * FROM users`;
for await (const row of db.sql`SELECT * FROM users`.stream()) {}
for await (const chunk of db.sql`SELECT * FROM users`.chunked(100)) {}
db.sql`...`.toSQL(); // SQL + params, not executed
db.sql.identifier({ table: "users" }); // dynamic table/column names
const data = db.sql.values([["Ada", "[email protected]"], ["Bob", "[email protected]"]]);
await db.sql`INSERT INTO users (name, email) VALUES ${data}`;
db.sql.default; // SQL DEFAULT keyword
db.sql.raw("DESC"); // ⚠️ unparameterized
await db.sql.unsafe("SELECT * FROM users WHERE id = $1", [42], { rowMode: "object" }); // ⚠️ raw string
⚠️
sql.rawandsql.unsafebypass injection protection. Never pass user input to them.
Transactions require db.pool
db.pool is a pg.Pool. BEGIN, COMMIT, and ROLLBACK must all run on the same client, so a transaction cannot be done with db.sql.
const client = await db.pool.connect();
try {
await client.query("BEGIN");
await client.query("INSERT INTO users (name, email) VALUES ($1, $2)", ["Ada", "[email protected]"]);
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();
}
Other drivers
import pg from "pg";
const pool = new pg.Pool({ connectionString: getConnectionString() });
import postgres from "postgres";
const sql = postgres(process.env.NETLIFY_DB_URL);
⚠️ Lambda compatibility mode functions get no auto-configured connection. The same applies outside Netlify and to an outdated CLI. In those cases you must call
getDatabase({ connectionString }). The symptom is the errorThe environment has not been configured to use Netlify Database. Connection strings contain credentials: keep them in env vars or a secret manager, never in commits.
Migrations: how they ship
- Deploy preview: migrations apply on each new deploy, before the deploy becomes available. A failed migration fails the deploy.
- Production: migrations apply immediately before publish, and a failure blocks publishing. With auto-publish off, migrations apply when you manually publish.
- Local: migrations are never automatic. Run
netlify database migrations apply. - Data changes (backfills, fixes, seeds for production) also ship as migration files containing DML.
⚠️ Never edit, rename, or delete an applied migration. Checksums are tracked, and the next deploy fails with
has been modified after being appliedorhas been removed after being applied. To fix:
- Restore the original file with
git checkoutornetlify database migrations pull.- Write a new corrective migration instead.
⚠️ Out-of-order prefixes fail. A new migration must sort after every applied one. Generate names with
netlify database migrations new -d "<purpose>", which creates<prefix>_<slug>/migration.sql.
⚠️ Renames and drops break live traffic. Old code briefly runs against the new schema during a deploy. Use expand → migrate → contract:
- Add the new column and write to both columns.
- Backfill the new column.
- Drop the old column in a later migration.
New tables and new nullable columns are safe in one migration.
Own migration tool?
- Keep its files outside
netlify/database/migrations. - You must apply migrations to preview branches yourself, for example in the build command.
- There is no publish hook. Production schema changes must be backwards-compatible and applied out of band before publishing.
Branches and previews
- Only production deploys reach the production database.
- Each deploy preview, and each agent run, gets its own branch. A preview branch is forked from production data, so it may contain real user data and PII.
- The production branch cannot be reset.
- Production rollback means reverting the deploy. Restoring a snapshot overwrites data and is not a routine rollback.
- Locally there are no branches: there is one local database.
Local dev and tests
netlify dev # starts a local Postgres with the dev server
netlify database migrations apply [--to <name>]
netlify database status [--json]
netlify database connect --query "SELECT * FROM users LIMIT 10" --json
netlify database reset # wipes the LOCAL db only
netlify database migrations reset # deletes local migration files not yet applied
psql "$(netlify database connect --json | jq -r .connection_string)"
For Vite, add netlify() from @netlify/vite-plugin to plugins. It runs the same engine as netlify dev and shares the same data.
// Vitest: DB only
import { NetlifyDB } from "@netlify/database-dev";
const db = new NetlifyDB(); // in-memory, random port
const url = await db.start();
await db.applyMigrations("./netlify/database/migrations");
await db.stop();
// Full environment: sets NETLIFY_DB_URL
import { NetlifyDev } from "@netlify/dev";
const nd = new NetlifyDev({ projectRoot: "./fixtures/my-project" });
await nd.start(); /* tests */ await nd.stop();
Local limitations:
- The local database is a single process, so don't use it for load testing.
- Auto-scale and sleep settings don't apply locally.
CLI quick reference
netlify database:
| Command | Purpose |
|---|---|
init [-y] |
Set up the database in a project |
status [-b <branch>] [--show-credentials] [--json] |
Enabled state, package presence, connection string, applied/pending migrations |
migrations new -d <desc> [-s sequential|timestamp] |
Create a correctly named migration |
migrations apply [--to <name>] |
Apply pending migrations to the local database |
migrations pull [-b [branch]] [--force] |
⚠️ Overwrites local migration files with a remote branch's |
migrations reset [-b <branch>] |
Delete unapplied local migration files |
connect [-q <sql>] [--json] |
Query the local database |
reset |
Wipe the local database |
Full flag details are in references/cli-commands.md.
Common errors
| Error | Fix |
|---|---|
database not found |
Install @netlify/database and deploy, or run netlify database init. |
added out of order |
Rename with a higher prefix. If it was never applied anywhere, migrations reset. |
error running migrations: … |
Read the DB error in the deploy log. Reproduce locally with migrations apply, and fix on a preview before merging. |
branch limit reached |
Too many active previews. Close stale PRs or upgrade the plan. |
database feature not available for this account |
The account needs a Credit-based plan. |
compute customization requires a Pro or higher plan |
Free/Personal plans use default compute. |
Access Denied |
Permission issue: only Team Owners delete databases, and only Owners and Developers view connection strings. |
Deeper guides
- Footgun catalog:
references/operational-footguns.md - Migration patterns:
references/migrations.md - Local setup and testing:
references/local-dev.md - Moving from the Neon extension:
references/migration-from-extension.md - Reading old
@netlify/neoncode:references/legacy-extension.md - Product docs: https://docs.netlify.com/build/data-and-storage/netlify-database/
Netlify house rules (database)
These are org conventions, not docs facts — merged into the rendered skill by
ctx-gen and never generated. Owned by the skills maintainer.
- Production data changes are expressed as DML migrations — agents never
edit rows directly (UI row editing exists for humans; it is not an agent
surface). - Preview branches can contain production data, including PII — and preview
deploy links are public. Warn before sharing. - Use only documented surfaces: no raw psql against internal endpoints, no
netlify apiscraping, no reading tokens from local CLI config files. - Deep guides live in this skill:
references/operational-footguns.md,
references/migrations.md,references/local-dev.md,
references/cli-commands.md,references/migration-from-extension.md,
references/legacy-extension.md. - Schema changes reach hosted databases only as committed migration files
applied by the deploy. Never rundrizzle-kit pushin any form against a
Netlify-hosted database, never rundrizzle-kit migrateagainst
NETLIFY_DB_URL, and never apply DDL vianetlify database connector
any direct connection. - When a
netlifycommand or a deploy fails, surface the exact error, the
deploy log URL, and the affected site/branch to the user and stop — do
not invent recovery commands or escalate to lower-level tools. - First-deploy
401 Access DeniedoncreateSiteDatabase: if it happened
on a--prod-first deploy, retry preview-first (netlify deploy, no
--prod); if a preview also fails, report and stop. Never curl
api.netlify.com, runnetlify api createSiteDatabase, or pull tokens
from local CLI config to work around it. - A request to change existing data is ambiguous between production and the
preview branch — if the prompt didn't say, ask. When acting on someone's
behalf, default to not touching production. - Destructive database operations — REST branch delete, snapshot restore,
any reset — require explicit user confirmation first. The body must not
present snapshot restore as a routine production-rollback lever. - Pin:
drizzle-ormanddrizzle-kitmust be installed from@beta—
latestlacks thedrizzle-orm/netlify-dbadapter and will fail. The
body may not soften this to a recommendation.
Explore more skills
Browse all- Netlify MCP ServersBuild, deploy, and secure Model Context Protocol (MCP) servers on Netlify. Use whenever the task involves creating an…
- Netlify Agent RunnerRun AI agent tasks remotely on Netlify using Claude, Codex, or Gemini. Use when the user wants to run an AI agent on…
- Netlify BlobsStore and retrieve unstructured objects, files, and cache-like state on Netlify with the @netlify/blobs module. Use…
- Netlify FormsUse this skill whenever a developer wants to add a contact form, signup form, file upload form, or any HTML form to a…
- Netlify IdentityAdd user authentication to a Netlify site with @netlify/identity, covering signup/login/logout,…
- Netlify CLI and DeployGuide for using the Netlify CLI and deploying sites. Use when installing the CLI, linking sites, deploying (Git-based…
Security
Reviews (0)
More from Netlify
View source →Frequently asked questions about netlify-database
What does the netlify-database skill do?
Use this skill whenever a Netlify project needs a Postgres database. It covers Netlify Database setup, queries from Functions or Edge Functions, schema changes through migrations in netlify/database/migrations, Drizzle ORM wiring, local dev databases and tests, deploy-preview database branches, and moving off Neon, Supabase, RDS or the legacy @netlify/neon extension. Activate it when someone asks to add a database, store users or posts or orders, save form submissions, create or alter a table, add a column, write a migration, set up Drizzle, fix a failing migration deploy, seed or test against a local database, or switch an existing Postgres app onto Netlify. Use it even if the request never says Netlify Database explicitly. It's a reusable SKILL.md instruction set that loads into your AI coding assistant on demand, no prompt engineering, no copy-pasting every session.
How do I install the netlify-database skill?
Run `npx @skills-hub-ai/cli install netlify-database` from your terminal. The CLI writes the SKILL.md to the correct location for your AI tool (e.g. ~/.claude/skills/netlify-database/ for Claude Code or ~/.cursor/skills/ for Cursor with --target cursor) and adds it to your project's .skills.json lockfile.
Which AI tools does netlify-database work with?
netlify-database runs in Claude Code. It follows the open Agent Skills standard (SKILL.md), so the same skill works in every supported tool without modification.
Is the netlify-database skill free?
Yes. Every skill on skills-hub.ai is free and open-source. There are no premium tiers, paywalls, or usage limits. You only pay for whatever AI assistant you're already using.
How do I use netlify-database after installing it?
In Claude Code, type `/netlify-database` (or whatever slash command the skill registers) and the AI follows the skill's instructions immediately. You can also reference it by name in natural language, your AI loads the skill into context when relevant.
Can I share the netlify-database skill with my team?
Yes. Commit your project's .skills.json lockfile and teammates run `npx @skills-hub-ai/cli install` (no args) to install every skill at the exact version you pinned. Organization-scoped installs work via skills-hub.ai organizations.
Badge for your README
Show that this skill is on Skills Hub. The badge links back to this page and shows the live install count.
[](https://skills-hub.ai/skills/netlify-database)<a href="https://skills-hub.ai/skills/netlify-database"><img src="https://skills-hub.ai/api/badges/skill/netlify-database" alt="Install on Skills Hub"></a>More options in the badge docs.