Create FasterCreate Faster

Prisma

Prisma is a next-generation ORM with an intuitive data model, automated migrations, and powerful type safety.

→ Prisma Documentation

Requires: Database (PostgreSQL or MySQL)

What create-faster adds

Beyond the official setup, we include:

Development Scripts:

  • db:generate - Generate Prisma Client from schema (runs automatically before dev and build)
  • db:migrate - Create and apply migrations (asks for a migration name, so run it from a terminal)
  • db:push - Push schema to database (dev)
  • db:studio - Launch Prisma Studio visual editor
  • db:seed - Populate database with sample data

Files created (Turborepo):

packages/db/
├── prisma/
│   └── schema.prisma       # Database schema with User, Post, auth models
├── src/
│   └── index.ts            # PrismaClient singleton with type helpers
├── generated/              # Auto-generated Prisma Client (gitignored)
│   └── prisma/
├── scripts/
│   └── seed.ts             # Seed script with sample data
├── package.json            # Dependencies and db:* scripts
├── tsconfig.json           # TypeScript config
└── .env.example            # DATABASE_URL template

Files created (Single repo):

src/lib/db/
└── index.ts                # PrismaClient singleton

prisma/
└── schema.prisma           # Database schema

scripts/
└── seed.ts                 # Seed script

.env.example                # DATABASE_URL template

schema.prisma

Database schema with User and Post models. Shown here with PostgreSQL:

prisma/schema.prisma
generator client {
  provider = "prisma-client"
  output   = "../generated/prisma"
}

datasource db {
  provider = "postgresql" // or "mysql" based on database selection
}

model User {
  id            String   @id @default(uuid())
  name          String
  email         String   @unique
  emailVerified Boolean  @default(false) @map("email_verified")
  avatarUrl     String?  @map("avatar_url") @db.Text

  phone         String?
  firstName     String?  @map("first_name")
  lastName      String?  @map("last_name")
  createdAt     DateTime @default(now()) @map("created_at")
  updatedAt     DateTime @updatedAt @map("updated_at")

  posts         Post[]

  @@map("users")
}

model Post {
  id        String   @id @default(uuid())
  title     String
  content   String   @db.Text
  published Boolean  @default(false)
  authorId  String   @map("author_id")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  author    User     @relation(fields: [authorId], references: [id], onDelete: Cascade)

  @@map("posts")
}

With Better Auth, the schema adds Session, Account, and Verification models:

prisma/schema.prisma (Better Auth additions)
model User {
  // ... base fields
  accounts      Account[]
  sessions      Session[]
  posts         Post[]
}

model Session {
  id        String   @id
  userId    String   @map("user_id")
  token     String   @unique
  expiresAt DateTime @map("expires_at")
  ipAddress String?  @map("ip_address")
  userAgent String?  @map("user_agent")
  createdAt DateTime @default(now()) @map("created_at")
  updatedAt DateTime @updatedAt @map("updated_at")

  user      User     @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("sessions")
}

model Account {
  id                      String    @id
  userId                  String    @map("user_id")
  accountId               String    @map("account_id")
  providerId              String    @map("provider_id")
  accessToken             String?   @map("access_token") @db.Text
  refreshToken            String?   @map("refresh_token") @db.Text
  accessTokenExpiresAt    DateTime? @map("access_token_expires_at")
  refreshTokenExpiresAt   DateTime? @map("refresh_token_expires_at")
  scope                   String?
  idToken                 String?   @map("id_token") @db.Text
  password                String?
  createdAt               DateTime  @default(now()) @map("created_at")
  updatedAt               DateTime  @updatedAt @map("updated_at")

  user                    User      @relation(fields: [userId], references: [id], onDelete: Cascade)

  @@map("accounts")
}

model Verification {
  id         String   @id
  identifier String
  value      String
  expiresAt  DateTime @map("expires_at")
  createdAt  DateTime @default(now()) @map("created_at")
  updatedAt  DateTime @updatedAt @map("updated_at")

  @@map("verifications")
}

index.ts

PrismaClient singleton with global caching to prevent hot-reload issues. The client always runs through a driver adapter: PrismaPg for PostgreSQL, PrismaMariaDb for MySQL. Shown here with PostgreSQL:

src/lib/db/index.ts
import { PrismaPg } from '@prisma/adapter-pg';
import { parse as parseConnectionString } from 'pg-connection-string';
import { PrismaClient } from '../../../generated/prisma/client'; // '../generated/prisma/client' in a turborepo

// warnIfProductionTlsDisabled() is generated here too: it logs a warning in production when DATABASE_URL turns TLS off
warnIfProductionTlsDisabled(process.env.DATABASE_URL);
// TLS in production unless DATABASE_URL sets sslmode: pg applies the parsed URL over these options.
const adapter = new PrismaPg({
  connectionString: process.env.DATABASE_URL!,
  ssl: process.env.NODE_ENV === 'production',
});

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

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

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

type Client = typeof prisma;

export * from '../../../generated/prisma/client';

// Type helpers
export type User = Awaited<ReturnType<Client['user']['findUnique']>>;
export type Post = Awaited<ReturnType<Client['post']['findUnique']>>;

With PostgreSQL, TLS follows sslmode in DATABASE_URL and defaults to on in production (see PostgreSQL). With MySQL, the adapter gets DATABASE_URL with ssl=true appended in production when the URL has no ssl parameter, so the connector negotiates TLS and verifies the server certificate (see MySQL). The local Docker MySQL URL ends with ?ssl=false and connects in plain text.

src/lib/db/index.ts (MySQL)
import { PrismaMariaDb } from '@prisma/adapter-mariadb';

// withProductionTls() is generated here too: it appends ssl=true in production and warns when DATABASE_URL sets ssl=false for a remote host
const adapter = new PrismaMariaDb(withProductionTls(process.env.DATABASE_URL ?? 'mysql://localhost:3306/db'));

With Better Auth, additional type helpers are exported:

src/lib/db/index.ts (Better Auth additions)
export type Session = Awaited<ReturnType<Client['session']['findUnique']>>;
export type Account = Awaited<ReturnType<Client['account']['findUnique']>>;
export type Verification = Awaited<ReturnType<Client['verification']['findUnique']>>;

seed.ts

Seed script with sample data using .create() and .createMany():

scripts/seed.ts
import { prisma } from '@repo/db'; // or '../src/lib/db' in single repo

async function seed() {
  console.log('🌱 Seeding database...');

  // Clear existing data
  await prisma.post.deleteMany();
  await prisma.user.deleteMany();

  // Create users
  const alice = await prisma.user.create({
    data: {
      name: 'alice',
      email: 'alice@example.com',
    },
  });

  const bob = await prisma.user.create({
    data: {
      name: 'bob',
      email: 'bob@example.com',
    },
  });

  console.log(`✅ Created 2 users`);

  // Create posts
  await prisma.post.createMany({
    data: [
      {
        title: 'Getting Started with Prisma',
        content: 'Prisma is a next-generation ORM that provides excellent type safety...',
        published: true,
        authorId: alice.id,
      },
      {
        title: 'Building Modern APIs',
        content: 'Modern API development requires careful consideration of many factors...',
        published: true,
        authorId: alice.id,
      },
      {
        title: 'Draft: Upcoming Features',
        content: 'This is a draft post about upcoming features...',
        published: false,
        authorId: bob.id,
      },
    ],
  });

  console.log(`✅ Created ${3} posts`);
  console.log('🎉 Seeding completed!');
}

seed()
  .catch((error) => {
    console.error('❌ Seeding failed:', error);
    process.exit(1);
  })
  .finally(async () => {
    await prisma.$disconnect();
    process.exit(0);
  });

On Cloudflare Workers

With --deployment cloudflare, PostgreSQL and MySQL are reached through a Hyperdrive binding, and the Worker cannot hold a client across requests. The db module exports a per-request createDb(hyperdrive) factory instead of the prisma singleton:

src/lib/db/index.ts (Cloudflare, PostgreSQL)
import { PrismaPg } from '@prisma/adapter-pg';
import { PrismaClient } from '../../../generated/prisma/client';

export function createDb(hyperdrive: Hyperdrive) {
  const adapter = new PrismaPg({ connectionString: hyperdrive.connectionString });
  return new PrismaClient({ adapter });
}
export type Database = ReturnType<typeof createDb>;
type Client = Database;

export * from '../../../generated/prisma/client';

export type User = Awaited<ReturnType<Client['user']['findUnique']>>;
export type Post = Awaited<ReturnType<Client['post']['findUnique']>>;

With MySQL the adapter is new PrismaMariaDb({ host, port, user, password, database }), with each field read from the binding (hyperdrive.host, hyperdrive.port, and so on).

Call it inside each request handler (const db = await createDb(env.HYPERDRIVE)), never at module level.

The Worker bundle needs a client generated for the workerd runtime, which loads the query compiler as a WebAssembly module and cannot run on Bun. schema.prisma therefore declares two generators:

prisma/schema.prisma (Cloudflare)
generator client {
  provider = "prisma-client"
  runtime  = "workerd"
  output   = "../generated/prisma"
}

generator nodeClient {
  provider = "prisma-client"
  output   = "../generated/prisma-node"
}

scripts/seed.ts imports the second client instead of prisma and builds it on DATABASE_URL with the same adapter as the Node client above, because the seed runs on Bun. Migrations (db:migrate, db:push) also run on Node against DATABASE_URL and are unchanged.

On this page