Deploy to Cloudflare Workers
Today you'll be deploying a Cloudflare Worker that uses Prisma ORM to save every request to a PostgreSQL database and fetches 20 of the most recent logs.
This guide covers Prisma ORM, TypeScript, PostgreSQL, Prisma Accelerate, and Cloudflare Workers.
Prerequisites
- A PostgreSQL database that is publicly accessible
- Cloudflare Workers account
- Prisma Data Platform account
- Node.js & npm installed
- Git installed
1. Set up your application
Wrangler is the official Cloudflare Worker CLI. You will use it to develop and deploy to Cloudflare Workers. This guide uses Wrangler v3.
Open your terminal and navigate to a location of your choice. First, initialize your project using the create-cloudflare-cli. To do this, run the following command in your terminal:
npm create cloudflare@latest
This will ask you a few questions.
In which directory do you want to create your application?
Enter the name of your project, for example: prisma-cloudflare-accelerate
What type of application do you want to create?
Select the "Hello World" Worker option.
Would you like to use TypeScript? (y/n)
We also want to use TypeScript, so answer yes.
Would you like to use git to manage this Worker? (y/n)
We want to use Git, so answer yes.
The command this will create a new project with a minimal preset configuration. Once create-cloudflare-cli is done, navigate to the project and open it on your editor of choice.
Next, authenticate the Wrangler CLI with your Cloudflare Workers account. To do this, run the following command in your terminal:
npx wrangler login
You can now verify that you're logged in by running npx wrangler whoami.
npx wrangler whoami
2. Set up Prisma ORM
Now you're ready to add Prisma ORM to the project.
Install prisma as a development dependency:
npm install --save-dev prisma
Next, initialize Prisma ORM in your project with the following command:
npx prisma init
This creates a Prisma schema in prisma/schema.prisma.
Note:
prisma init also creates an .env file. The .env file will contain a placeholder DATABASE_URL variable that will be used to update your database schema using Prisma Migrate. Update this value with your database's connection string.
Update your Prisma schema with the following data model:
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model Log {
id Int @id @default(autoincrement())
level Level
message String
meta Json
}
enum Level {
Info
Warn
Error
}
The above data model will be used to persist and retrieve logs from your Cloudflare Worker
3. Update your database schema
To map your data model to the database schema, you need to use the prisma migrate dev CLI command:
npx prisma migrate dev --name init
The command does two things:
- It creates a new SQL migration file for this migration
- It runs the SQL migration file against the database
4. Enable Accelerate in the Prisma Data Platform
Prisma ORM currently does not work on Cloudflare Workers yet. However, you can use Prisma ORM on Cloudflare Workers through Prisma Accelerate.
To get started with Prisma Accelerate:
- Sign up for a free Prisma Data Platform account
- Create a project
- Navigate to the project you created
- Enable Accelerate
- Generate an Accelerate connection string and copy it to your clipboard
5. Configure the Accelerate connection string in your project
-
Rename the existing
DATABASE_URLenvironment variable toDIRECT_URL. TheDIRECT_URLvariable will be used perform migrations and introspections. -
Add the Prisma Accelerate connection string to your
.envfile.-DATABASE_URL="postgres://..."
+DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=__API_KEY__"
+DIRECT_URL="postgres://..."Add
directUrlproperty indatasourceblock in theschema.prismafile.datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}The
directUrlfield is not required for Prisma Accelerate. It allows you to introspect and perform schema migrations. -
In
wrangler.tomlfile, add a[vars]key and your connection string.name = "prisma-cloudflare-accelerate"
main = "src/main.ts"
compatibility_date = "2022-11-07"
+ [vars]
+ DATABASE_URL = "prisma://accelerate.prisma-data.net/?api_key=__API_KEY__"noteCloudflare Workers does not support
.envfiles. To set environment variables, you can either adding the[vars]key in yourwrangler.tomlfile or saving your environment variables in a.dev.varsfile. Refer to Cloudflare's documentation to learn more. -
Install the Prisma Accelerate extension
npm install @prisma/extension-accelerate
You are now ready to generate a Prisma Client.
6. Generate a Prisma Client
Next, generate Prisma Client that connects to your database through Prisma Accelerate over HTTP.
npx prisma generate --no-engine
The --no-engine flag is available from Prisma ORM 5.2.0 and later. If you're using an earlier version of Prisma ORM, use the --accelerate flag.
npx prisma generate --accelerate
The generated Client has a smaller bundle size and is optimized for edge environments like Cloudflare Workers.
The smaller bundle size is due to the fact that the interfaces talking to the database (the Prisma ORM engines) are no longer bundled with Prisma Client as this logic is now handled by Prisma Accelerate.
7. Develop the Cloudflare Worker function
You're now ready to create a Cloudflare Worker. Create a src/index.ts file with the following code:
import { PrismaClient } from '@prisma/client/edge'
import { withAccelerate } from '@prisma/extension-accelerate'
export interface Env {
DATABASE_URL: string
}
export default {
async fetch(
request: Request,
env: Env,
ctx: ExecutionContext
): Promise<Response> {
const prisma = new PrismaClient({
datasourceUrl: env.DATABASE_URL,
}).$extends(withAccelerate())
await prisma.log.create({
data: {
level: 'Info',
message: `${request.method} ${request.url}`,
meta: {
headers: JSON.stringify(request.headers),
},
},
})
const { data, info } = await prisma.log
.findMany({
take: 20,
orderBy: {
id: 'desc',
},
})
.withAccelerateInfo()
console.log(JSON.stringify(info))
return new Response(`request method: ${request.method}!`)
},
}
The
infoobject has additional information which can be useful for debugging. Accelerate can also be used to cache your query results. You can find more information on caching with Prisma Accelerate in here.
Run npm run dev to see your worker in development:
👂 Listening on http://127.0.0.1:8787
Go ahead and open http://127.0.0.1:8787. If all goes well, you should see:
request method: GET!
Refresh the page a couple times to verify that it's working.
8. Publish to Cloudflare Workers
You're now ready to deploy to Cloudflare Workers. Run the following command:
npm run deploy
This will package and upload to Cloudflare. With a bit of luck, you'll see the following:
✨ Built successfully, built project size is 94 KiB.
✨ Successfully published your script to
https://prisma-cloudflare-accelerate.ankman.workers.dev
Visit your deployment URL and you'll again see:
request method: GET!
You're all set! You've successfully deployed a Cloudflare Worker written in TypeScript that uses Prisma ORM to talk to your PostgreSQL database.