Prisma Postgres ↗︎ is a managed PostgreSQL database with built-in connection pooling. In this tutorial, you query it from a Worker with Prisma ORM ↗︎, which runs inside the Worker with the nodejs_compat compatibility flag.
In this tutorial, you will learn how to:
- Set up a Cloudflare Workers project with Prisma ORM.
- Create a Prisma Postgres database from the command line.
- Define a data model and create its tables in the database.
- Query the database from Workers.
- Deploy the Worker to Cloudflare.
To follow this guide, ensure you have the following:
- Node.js
v22.18or higher installed. - An active Cloudflare account ↗︎.
- A basic familiarity with installing and using command-line interface (CLI) applications.
Begin by using C3 to create a Worker project in the command line:
npm create cloudflare@latest prisma-postgres-worker -- --type=hello-world --lang=ts --git=true --deploy=false --agents=falseThen navigate into your project:
cd ./prisma-postgres-workerYour initial src/index.ts file currently contains a simple request handler:
export default {
async fetch(request, env, ctx): Promise<Response> {
return new Response("Hello World!");
},
} satisfies ExportedHandler<Env>;In this step, you will add Prisma ORM to the project, create a Prisma Postgres database, and create the tables for your data model.
Run the Prisma CLI in the project directory:
npx prisma@latest orm init --yes --target postgres --authoring pslyarn dlx prisma@latest orm init --yes --target postgres --authoring pslpnpx prisma@latest orm init --yes --target postgres --authoring pslThe command installs @prisma/orm-postgres and the Prisma CLI, and creates:
src/prisma/contract.prisma: the file where you define your data model. It starts with aUserand aPostmodel.src/prisma/contract.jsonandsrc/prisma/contract.d.ts: emitted from the contract. The Worker imports both, so there is no separateprisma generatestep.prisma.config.ts: tells the Prisma CLI where the contract is and reads theDATABASE_URLenvironment variable from.env.
Prisma ORM connects to PostgreSQL through the pg driver, which needs the node:net and node:tls modules. Add the nodejs_compat flag to your Wrangler configuration file:
{
"compatibility_flags": ["nodejs_compat"],
}compatibility_flags = [ "nodejs_compat" ]Create a database and write its connection string to .env:
npx create-db@latest --env .envyarn dlx create-db@latest --env .envpnpx create-db@latest --env .envThe command creates a temporary Prisma Postgres database and prints a claim URL. The database is deleted after 24 hours unless you open the claim URL and claim it with a free Prisma account. If you already have a Prisma Postgres database, put its connection string in .env instead:
DATABASE_URL="postgres://USERNAME:PASSWORD@HOST:5432/postgres?sslmode=require"Both the Prisma CLI (through prisma.config.ts) and wrangler dev read this file, so the Worker receives the value as env.DATABASE_URL during local development.
Replace the contents of src/prisma/contract.prisma with the following User model:
// use prisma-8
model User {
id Int @id @default(autoincrement())
email String
name String
}Emit the contract files from the model, then create the table in the database:
npx prisma contract emit
npx prisma db initdb init creates the User table and records the contract version in the database. When you change the model later, run npx prisma contract emit again, followed by npx prisma db update to apply the change during development.
After these steps are complete, Prisma ORM is fully set up and connected to your Prisma Postgres database.
Modify the src/index.ts file and replace its contents with the following code:
import postgres from "@prisma/orm-postgres/runtime";
import { contractFromJson } from "@prisma/orm-postgres/static";
import type { Contract } from "./prisma/contract.d";
import contractJson from "./prisma/contract.json" with { type: "json" };
const contract = contractFromJson<Contract>(contractJson);
export default {
async fetch(request, env, ctx): Promise<Response> {
const path = new URL(request.url).pathname;
if (path === "/favicon.ico")
return new Response("Resource not found", {
status: 404,
headers: {
"Content-Type": "text/plain",
},
});
const db = postgres({ contract, url: env.DATABASE_URL });
try {
const user = await db.orm.public.User.create({
email: `Jon${Math.ceil(Math.random() * 1000)}@gmail.com`,
name: "Jon Doe",
});
const { userCount } = await db.orm.public.User.aggregate((a) => ({
userCount: a.count(),
}));
return new Response(`\
Created new user: ${user.name} (${user.email}).
Number of users in the database: ${userCount}.
`);
} finally {
ctx.waitUntil(db.close());
}
},
} satisfies ExportedHandler<Env>;A few things to note about this handler:
- The database client is created inside
fetchand closed after the response withctx.waitUntil(db.close()). Workers do not allow a socket opened during one request to be reused by another, so do not share a module-level client across requests. contract.jsonis imported withwith { type: "json" }and converted once withcontractFromJson. Wrangler bundles it into the Worker.- On PostgreSQL, you reach a model through its schema:
db.orm.public.User.
Generate the Worker types so that Env includes the DATABASE_URL variable from .env:
npx wrangler typesRun the development server:
npm run devVisit http://localhost:8787 ↗︎ to see your app display the following output:
Created new user: Jon Doe (Jon453@gmail.com).
Number of users in the database: 1.Every time you refresh the page, a new user is created. The number displayed will increment by 1 with each refresh as it returns the total number of users in your database.
When the application is deployed to Cloudflare, it needs access to the DATABASE_URL environment variable that is defined locally in .env. You can use the npx wrangler secret put command to upload the DATABASE_URL to the deployment environment:
npx wrangler secret put DATABASE_URLWhen prompted, paste the DATABASE_URL value (from .env). If you are logged in via the Wrangler CLI, you will see a prompt asking if you'd like to create a new Worker. Confirm by choosing "yes":
✔ There doesn't seem to be a Worker called "prisma-postgres-worker". Do you want to create a new Worker with that name and add secrets to it? … yesThen execute the following command to deploy your project to Cloudflare Workers:
npm run deployThe wrangler CLI will bundle and upload your application.
If you are not already logged in, the wrangler CLI will open a browser window prompting you to log in to the Cloudflare dashboard.
Once the deployment completes, verify the deployment by visiting the live URL provided in the deployment output, such as https://{PROJECT_NAME}.workers.dev. If you encounter any issues, ensure the secrets were added correctly and check the deployment logs for errors.
Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers!
To enhance your application further:
- Learn how to filter, sort, and paginate ↗︎ with Prisma ORM.
- Explore the Prisma Postgres documentation ↗︎.
- Connect to your database through Hyperdrive to pool connections closer to your Worker.