Guide

SQL Database

Nitro provides a built-in and lightweight SQL database layer.


The default database connection is preconfigured with SQLite and works out of the box for development mode and any Node.js compatible production deployments. By default, data will be stored in .data/db.sqlite3.

You can change default connection or define more connections to any of the supported databases.
You can integrate database instance to any of the supported ORMs.
Read more in DB0 Documentation.

Opt-in to the experimental feature

Database support is currently experimental. Refer to the db0 issues for status and bug report.

In order to enable database layer you need to enable experimental feature flag.

export default defineNitroConfig({
  experimental: {
    database: true
  }
})

Also install better-sqlite3 dependency:

npm i -D better-sqlite3

Usage

index.ts
export default defineEventHandler(async () => {
  const db = useDatabase();

  // Create users table
  await db.sql`DROP TABLE IF EXISTS users`;
  await db.sql`CREATE TABLE IF NOT EXISTS users ("id" TEXT PRIMARY KEY, "firstName" TEXT, "lastName" TEXT, "email" TEXT)`;

  // Add a new user
  const userId = String(Math.round(Math.random() * 10_000));
  await db.sql`INSERT INTO users VALUES (${userId}, 'John', 'Doe', '')`;

  // Query for users
  const { rows } = await db.sql`SELECT * FROM users WHERE id = ${userId}`;

  return {
    rows,
  };
});

Configuration

You can configure database connections using database config:

export default defineNitroConfig({
  database: {
    default: {
      connector: 'sqlite',
      options: { name: 'db' }
    },
    users: {
      connector: 'postgresql',
      url: 'postgresql://username:password@hostname:port/database_name'
    }
  }
})
You can use the devDatabase config to overwrite the database configuration only for development mode.