Skip to content
Cloudflare Docs

Prisma ORM

Prisma ORM is a Node.js and TypeScript ORM with a focus on type safety and developer experience. This example demonstrates how to use Prisma ORM with PostgreSQL via Cloudflare Hyperdrive in a Workers application.

Prerequisites

1. Install Prisma ORM

Install Prisma CLI as a dev dependency:

Terminal window
npm i -D prisma

Install the dotenv-cli package to load environment variables from .dev.vars:

Terminal window
npm i -D dotenv-cli

Install the pg driver for use with Hyperdrive:

Terminal window
npm i pg@>8.13.0

If using TypeScript, install the types package:

Terminal window
npm i -D @types/pg

Add the required Node.js compatibility flags and Hyperdrive binding to your wrangler.toml file:

{
"compatibility_flags": [
"nodejs_compat"
],
"compatibility_date": "2024-09-23",
"hyperdrive": [
{
"binding": "HYPERDRIVE",
"id": "<your-hyperdrive-id-here>"
}
]
}

2. Configure Prisma ORM

2.1. Initialize Prisma

Initialize Prisma in your application:

Terminal window
npx prisma init

This creates a prisma folder with a schema.prisma file and an .env file.

2.2. Define a schema

Define your database schema in the prisma/schema.prisma file:

prisma/schema.prisma
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String @unique
createdAt DateTime @default(now())
}

2.3. Set up environment variables

Rename the .env file to .dev.vars (since Workers doesn't support .env files):

Terminal window
mv .env .dev.vars

Add your database connection string to .dev.vars:

.dev.vars
DATABASE_URL="postgres://user:password@host:port/database"

Add helper scripts to your package.json:

package.json
"scripts": {
"migrate": "dotenv -e .dev.vars -- npx prisma migrate dev",
"generate": "dotenv -e .dev.vars -- npx prisma generate --no-engine",
"studio": "dotenv -e .dev.vars -- npx prisma studio"
}

2.4. Run migrations

Generate and apply the database schema:

Terminal window
npm run migrate

When prompted, provide a name for the migration (for example, init).

3. Connect Prisma ORM to Hyperdrive

Use your Hyperdrive configuration when using Prisma ORM. Update your src/index.ts file:

src/index.ts
import { PrismaClient } from "@prisma/client/edge";
export interface Env {
HYPERDRIVE: Hyperdrive;
}
export default {
async fetch(request, env, ctx): Promise<Response> {
// Create Prisma client using Hyperdrive connection string
const prisma = new PrismaClient({
datasourceUrl: env.HYPERDRIVE.connectionString,
});
// Sample query to create and fetch users
const user = await prisma.user.create({
data: {
name: "John Doe",
email: `john.doe.${Date.now()}@example.com`,
},
});
const allUsers = await prisma.user.findMany();
return Response.json({
newUser: user,
allUsers: allUsers,
});
},
} satisfies ExportedHandler<Env>;

4. Deploy your Worker

Deploy your Worker:

Terminal window
npx wrangler deploy

Next steps