thelastapi
Get started free

Use Postgres from Next.js with Drizzle or Prisma

Connect Next.js to Postgres with Drizzle or Prisma using DATABASE_URL from thelastapi, complete with isolated dev branches for safe migrations.

On this page 7 sections

You connect Next.js to Postgres using Drizzle or Prisma by pointing your ORM client to the DATABASE_URL environment variable generated for your project. Running vibiz dev provisions an isolated development database branch containing your production table schema with zero user data, writes the connection string to .env.development.local, and preserves migration ledgers so migration tools run cleanly without touching live data.

Whether your Next.js application runs on thelastapi hosting or on another server, your ORM connects over standard Postgres. You do not need a custom driver, an adapter proxy, or specialized query engines.

How Next.js gets its DATABASE_URL

When you create a project with the database resource, thelastapi provisions a serverless Postgres database for you. Every project includes two environments: production and development.

To start a new project or add a database to an existing Next.js directory, run the CLI:

Terminal
vibiz init my-nextjs-app --resources database

To fetch the connection string for your local computer or an AI agent, use vibiz dev:

Terminal
vibiz dev

This single command branches the Postgres database, creates your development environment, and writes DATABASE_URL directly into .env.development.local. Next.js automatically loads .env.development.local during local development (next dev).

The development database gives you an exact copy of production's schemas, tables, indexes, views, and functions, but every table is completely empty. The migration ledgers for tools like Drizzle and Prisma are preserved inside the branch. That means local schema tests and migrations never risk overwriting, leaking, or wiping customer data. For more on single-command setup, read our guide on how to get a Postgres DATABASE_URL in one command.

Setting up Drizzle ORM in Next.js

Drizzle works with standard Postgres clients like postgres. Because thelastapi provides plain Postgres over the internet, you can use standard open-source tools without special adapters.

First, install Drizzle ORM, the postgres driver, and Drizzle Kit:

Terminal
npm install drizzle-orm postgres
npm install -D drizzle-kit

1. Define the connection

Create a database client file, such as src/db/index.ts. It reads the DATABASE_URL provided by vibiz dev:

TypeScript
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';
import * as schema from './schema';

const connectionString = process.env.DATABASE_URL;

if (!connectionString) {
  throw new Error('DATABASE_URL is not set');
}

const client = postgres(connectionString);
export const db = drizzle(client, { schema });

2. Define a schema

Create your schema in src/db/schema.ts:

TypeScript
import { pgTable, text, timestamp, uuid } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: uuid('id').defaultRandom().primaryKey(),
  email: text('email').notNull().unique(),
  createdAt: timestamp('created_at').defaultNow().notNull(),
});

3. Configure Drizzle Kit

Create a drizzle.config.ts in your root directory:

TypeScript
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  schema: './src/db/schema.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

To push schema changes or run migrations against your local branch, run:

Terminal
npx drizzle-kit push

Or apply tracked migration files:

Terminal
npx drizzle-kit migrate

Because Drizzle's migration history tables are preserved during database branching, migrations run predictably on your local branch just as they will in production.

Setting up Prisma ORM in Next.js

Prisma connects directly to the same Postgres connection string.

Install the Prisma CLI and the client:

Terminal
npm install @prisma/client
npm install -D prisma

Initialize your Prisma setup:

Terminal
npx prisma init

1. Configure the datasource

Inside prisma/schema.prisma, ensure the provider is set to postgresql and references DATABASE_URL:

prisma
datasource db {
  provider = "postgresql"
  url      = env("DATABASE_URL")
}

generator client {
  provider = "prisma-client-js"
}

model User {
  id        String   @id @default(uuid())
  email     String   @unique
  createdAt DateTime @default(now())
}

2. Initialize the Prisma Client

Instantiate the Prisma Client in src/lib/prisma.ts:

TypeScript
import { PrismaClient } from '@prisma/client';

const globalForPrisma = globalThis as unknown as { prisma: PrismaClient };

export const prisma = globalForPrisma.prisma || new PrismaClient();

if (process.env.NODE_ENV !== 'production') {
  globalForPrisma.prisma = prisma;
}

3. Run migrations

Apply your schema migrations using Prisma's migration CLI:

Terminal
npx prisma migrate dev --name init

Prisma writes migration entries into its _prisma_migrations ledger. Because the development branch created by vibiz dev preserves migration ledgers while clearing user data, Prisma recognizes which migrations have already been executed and applies only new schema changes.

Running migrations safely with isolated development branches

A common failure mode when building web apps is running migrations against a database containing live customer rows, or sharing a messy staging database across team members and AI coding assistants.

thelastapi eliminates this by splitting every project into two environments:

FeatureDevelopment BranchProduction Database
DataEmpty tables (zero production rows)Real live customer data
SchemasMirrored from productionCanonical schema
Migration LedgersKept intactKept intact
AccessFull-access and Limited keysFull-access owners only
Commandvibiz devDeployment or vibiz env

If you make an experimental schema modification or load messy test data, you can reset the development branch back to a clean state at any time:

Terminal
vibiz dev --reset

This throws away the local copy. The next time you run vibiz dev, thelastapi creates a fresh branch from the current production schema with all rows wiped clean. Read more about this architecture in our article on serverless Postgres for side projects: one database per project.

Inspecting and querying the database without extra tools

You can inspect tables or run quick queries without opening an external database GUI or writing a dedicated script. thelastapi provides a read-only query interface via CLI and HTTP.

To inspect the schemas, tables, and row estimates of your development database:

Terminal
curl "https://thelastapi.dev/v1/projects/$PROJECT/database?env=development" \
  -H "Authorization: Bearer $VIBIZ_API_KEY"

To run a single read-only SQL query against the development database:

Terminal
curl https://thelastapi.dev/v1/projects/$PROJECT/database/query \
  -H "Authorization: Bearer $VIBIZ_API_KEY" \
  -H 'content-type: application/json' \
  -d '{"sql":"select table_name from information_schema.tables where table_schema = '\''public'\''","env":"development"}'

The read view enforces strict safety bounds:

  • Accepts only SELECT, WITH, TABLE, VALUES, EXPLAIN, or SHOW statements.
  • Max statement length of 20,000 characters.
  • Query timeout of 5 seconds.
  • Returns up to 500 rows (truncated: true past that limit).

Any statement that attempts to write via the query endpoint returns 400 invalid_request. To write or seed rows, use your ORM client or a database script against the DATABASE_URL provided by vibiz dev. Details can be found in the Database documentation.

Loading the production database URL on any host

When deploying Next.js, you have two options depending on where your application is hosted.

1. thelastapi hosting

If you deploy your app on thelastapi, your production environment variables are synchronized automatically. You do not need to copy or paste credentials. Learn more in our walk-through on how to deploy a Next.js app with a database and sign-in in one command.

2. Hosting outside thelastapi

You can run your Next.js application on any server or cloud host while using thelastapi managed Postgres database. You do not need thelastapi hosting to use the database; every resource can be used independently as explained in the Use one service guide.

Instead of pasting raw database credentials into your hosting dashboard, provide a single secret: VIBIZ_APP_KEY. At server boot, load your variables dynamically:

Terminal
npm install --save-exact @vibiz/app@0.3.15

In your Next.js server initialization or instrumentation hook:

TypeScript
import { vibiz } from '@vibiz/app';

await vibiz.loadEnv();

await vibiz.loadEnv() pulls the project's production variables, including DATABASE_URL, directly into process.env. If database credentials rotate, your app picks up the new credentials on the next boot without manual intervention. Alternatively, if your build process requires static variables, pull them during CI:

Terminal
npx @vibiz/cli env pull --format dotenv -o .env.production

Or read the production environment variables using a full-access key:

Terminal
vibiz env --write .env.production

For more details on key permissions, review the Keys and environments reference.

Run vibiz dev in your Next.js project to branch your database, set up your Drizzle or Prisma configuration with process.env.DATABASE_URL, and apply your first migration.

Frequently asked questions

Does the development database branch contain any live production data?

No. Every development branch generated by `vibiz dev` copies your production schemas and table structures, but all rows from both your application tables and sign-in sessions are wiped clean before access is granted.

How much does a managed Postgres database cost on thelastapi?

Each ready database is recorded in usage at an estimated $0.02 a day of cost, billed with the default margin (+20% today, shown as `billed_usd` in usage) while final pricing is being determined.

Can an AI agent or Limited key access production database rows?

No. Limited keys and AI agents only receive access to the development environment and will receive a `403 owner_only` error if they attempt to query production rows.

How do I export my database if I decide to migrate away?

Run `vibiz export --db` to download a complete SQL snapshot file (`.sql.gz`) that you can restore into any standard Postgres instance using `psql`, or view the [Export documentation](/docs/export) for full details.