/netlify-skills:netlify-databasefrom netlify-skills
Sets up and manages Postgres databases on Netlify, including provisioning, Drizzle ORM wiring, migrations, local dev databases, deploy-preview branches, and migration from Neon, Supabase, or RDS.
Ships in netlify-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
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.
// ✅ 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.
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.
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>:
[a-z0-9_-].// 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.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:
npx drizzle-kit generate.netlify/database/migrations/.@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.sqldb.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.
db.pooldb.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();
}
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.
netlify database migrations apply.⚠️ 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?
netlify/database/migrations.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:
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.
| 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. |
references/operational-footguns.mdreferences/migrations.mdreferences/local-dev.mdreferences/migration-from-extension.md@netlify/neon code: references/legacy-extension.mdThese are org conventions, not docs facts — merged into the rendered skill by ctx-gen and never generated. Owned by the skills maintainer.
netlify api scraping, no reading tokens from local CLI config files.references/operational-footguns.md,
references/migrations.md, references/local-dev.md,
references/cli-commands.md, references/migration-from-extension.md,
references/legacy-extension.md.drizzle-kit push in any form against a
Netlify-hosted database, never run drizzle-kit migrate against
NETLIFY_DB_URL, and never apply DDL via netlify database connect or
any direct connection.netlify command 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.401 Access Denied on createSiteDatabase: 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, run netlify api createSiteDatabase, or pull tokens
from local CLI config to work around it.drizzle-orm and drizzle-kit must be installed from @beta —
latest lacks the drizzle-orm/netlify-db adapter and will fail. The
body may not soften this to a recommendation.references/cli-commands.md (opens in a new tab)references/legacy-extension.md (opens in a new tab)references/local-dev.md (opens in a new tab)references/migration-from-extension.md (opens in a new tab)references/migrations.md (opens in a new tab)references/operational-footguns.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
netlify-database, postgres, drizzle-orm, migrations, edge-functions
16 skills in this plugin
/netlify-access-controlPicks the right Netlify site-protection layer and disambiguates the three unrelated "auth" concepts users conflate — app-user login (Netlify Identity), site-load gating (Password Protection / project visibility), and dashboard SAML SSO. Use it when asked to password-protect a site or Deploy Preview, make a project private/public, restrict a site to your team, require SSO to view a site, set up company-wide or internal-app SSO, invite users to a private project, or know which team member made a request to a private site. Also use it for SSO-session symptoms on protected sites: "logged out mid-session", 401s after about an hour, or token expiry/refresh questions. Not for wiring auth code — route app-login setup to netlify-identity./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 their site, get a second opinion from another model, or delegate development tasks to run remotely against their repo./netlify-ai-gatewayUse Netlify AI Gateway to call OpenAI, Anthropic Claude, Google Gemini, Meta, TypeSafe (Jev), or OpenRouter-hosted models (xAI/DeepSeek/Mistral/Qwen) from Netlify Functions or Edge Functions without managing provider accounts or API keys. Reach for this when adding an AI feature to a Netlify app — a chatbot, text summarizer, image generator, joke/content generator, form-submission routing or analysis, or any LLM call — or when wiring the OpenAI/Anthropic/Gemini/TypeSafe/OpenRouter SDK into a Netlify Function, choosing which env vars to use, streaming long generations, or debugging why gateway calls fail at build time or return 401./netlify-blobsStore and retrieve unstructured objects, files, and cache-like state on Netlify with the @netlify/blobs module. Use when persisting user file uploads (images/documents), caching computed output from functions or Background Functions, serving downloadable assets, storing JSON blobs keyed by ID, or seeding deploy-specific data. Reach for this for key/value or object storage from Functions, Edge Functions, or Build Plugins — not for per-user, transactional, or relational data (use Netlify DB for that). Triggers include "save an uploaded file", "cache API results", "store generated site map", "key/value store for a function", or "file uploads without a database"./netlify-cachingCache dynamic and static responses on Netlify's CDN from Functions, Edge Functions, Netlify Server, and proxies. Use when you add caching or cache-control headers to a function or server response, tune cache TTL or stale-while-revalidate, set up the durable cache, vary a cache key by query/header/cookie/country/language, purge or invalidate the cache by site or cache tag, use the programmatic Cache API (caches.open/match/put) or @netlify/cache helpers (fetchWithCache/cacheHeaders/getCacheStatus/purgeCache), speed up an expensive API call, add ISR or on-demand revalidation, or debug why a response is or isn't cached via the Cache-Status header./netlify-configConfigure Netlify builds and routing via netlify.toml, _redirects, and _headers. Use when setting a build command or publish directory, validating netlify.toml against its JSON schema, adding redirects/rewrites/proxies or an SPA fallback rewrite, or setting custom response headers or basic auth. Also use when managing environment variables and secrets, scoping vars per deploy context, marking a var as secret or disabling secret scanning, handling sensitive vars in fork Deploy Previews, configuring functions bundling or the Netlify Server region/size, ignoring builds, or wiring up a monorepo or JavaScript SPA on Netlify.Other plugins' skills for the same job
npx claudepluginhub netlify/context-and-tools --plugin netlify-skills