Database
Configure and use PostgreSQL or SQLite with Drizzle ORM.
NextSaas supports PostgreSQL and SQLite out of the box. Simply set two environment variables and you're ready to go — no code changes needed to switch between databases.
Setup
PostgreSQL (default)
-
Provision a PostgreSQL database from any provider (Neon, Supabase, or local Docker).
-
Configure your
.env:DATABASE_ADAPTER="pg" DATABASE_URL="postgresql://user:password@host:5432/dbname?sslmode=require"
SQLite
-
Configure your
.env:DATABASE_ADAPTER="sqlite" DATABASE_URL="file:data/local.db"You can also use an in-memory database for development:
DATABASE_URL=":memory:"
Usage
All database access goes through getDb():
import { getDb } from "@/db";
export default async function Page() {
const db = await getDb();
const user = await db.users.findById(userId);
const orders = await db.orders.findByUserId(userId);
await db.orders.create({ id, userId, amount, ... });
}You can also import types for use in your components:
import { getDb, type Order, type User } from "@/db";Modifying Schema
To add a new field (e.g., phone on users):
-
Edit the schema file for each database you support:
// PostgreSQL schema export const usersTable = pgTable("users", { // ...existing fields phone: text("phone"), });// SQLite schema export const usersTable = sqliteTable("users", { // ...existing fields phone: text("phone"), }); -
Generate and apply the migration:
bun run db:generate bun run db:migrate
Migrations
After any schema change, run these two commands:
-
Generate migration — creates a SQL migration file:
bun run db:generate -
Apply migration — executes against your database:
bun run db:migrate
Drizzle Studio
Browse and manage your database data with Drizzle Studio:
bunx drizzle-kit studioAdding a New Database Adapter
NextSaas is designed to make it easy to add support for other databases. Here's how to add a new adapter, using MySQL as an example:
-
Create a schema file at
<src>/db/drivers/mysql/schema.ts, defining the same tables using Drizzle's MySQL column types. You can reference the existing PostgreSQL or SQLite schema as a guide. -
Create an adapter file at
<src>/db/drivers/mysql/adapter.tsthat implements all the database query methods. Reference an existing adapter for the expected function signatures. -
Register the new driver in the following files:
<src>/db/types.ts— add"mysql"to theDriverTypeunion<src>/db/factory.ts— add acase "mysql"branch in bothcreateAdapter()andcreateAuthDrizzle()<src>/env.ts— add"mysql"to theDATABASE_ADAPTERvalidation
-
Configure your
.env:DATABASE_ADAPTER="mysql" DATABASE_URL="mysql://user:password@host:3306/dbname" -
Generate and apply migrations:
bun run db:generate bun run db:migrate
No changes are needed in any business code — everything works through getDb() automatically.