Subchapter 3.9
references/features-database.mdMarkdown3 KBView on GitHub
.data/db.sqliteimport { defineConfig } from "nitro";
export default defineConfig({
experimental: { database: true },
});useDatabase() (auto-imported when the flag is on, or import from nitro/database) returns a connection. Optional connection name defaults to "default".
import { defineHandler } from "nitro";
import { useDatabase } from "nitro/database";
export default defineHandler(async () => {
const db = useDatabase();
await db.sql`CREATE TABLE IF NOT EXISTS users (
"id" TEXT PRIMARY KEY, "firstName" TEXT, "lastName" TEXT, "email" TEXT
)`;
const id = String(Math.round(Math.random() * 10_000));
await db.sql`INSERT INTO users VALUES (${id}, 'John', 'Doe', '')`;
const { rows } = await db.sql`SELECT * FROM users WHERE id = ${id}`;
return { rows };
});Connections are created lazily and cached per name.
// Tagged template with safe parameter binding
const { rows } = await db.sql`SELECT * FROM users WHERE id = ${id}`;
const res = await db.sql`INSERT INTO posts (title) VALUES (${"Hello"})`;
// res.rows, res.changes, res.lastInsertRowid
// Raw string execution
await db.exec("CREATE TABLE IF NOT EXISTS t (id TEXT)");
// Prepared statement
const stmt = db.prepare("SELECT * FROM users WHERE id = ?");
const result = await stmt.bind("1001").all();Always use
db.sqltagged templates (orprepare().bind()) for user input — they parameterize and prevent SQL injection.
import { defineConfig } from "nitro";
export default defineConfig({
experimental: { database: true },
database: {
default: { connector: "sqlite", options: { name: "db" } },
users: {
connector: "postgresql",
options: { url: "postgresql://user:pass@host:5432/db" },
},
},
// Use a local SQLite db in development while prod uses Postgres
devDatabase: {
default: { connector: "sqlite", options: { name: "dev-db" } },
},
});Use a named connection with useDatabase("users").
All db0 connectors (opens in a new tab) are supported, including: sqlite / node-sqlite, better-sqlite3, bun-sqlite, libsql (+ libsql-http/libsql-web), postgresql, mysql2, pglite, planetscale, cloudflare-d1, and Cloudflare Hyperdrive variants.
experimental.database: true; defaults to a zero-config SQLite connection.useDatabase() from nitro/database (auto-imported when enabled); names default to "default".db.sql tagged templates for safe, parameterized queries.devDatabase to run a different (local) database in development.