Skip to content

Commit cfb36a9

Browse files
committed
feat: add blog on using prisma postgres with workers
1 parent 61cf89e commit cfb36a9

File tree

1 file changed

+224
-0
lines changed
  • src/content/docs/workers/tutorials/using-prisma-postgres-with-workers

1 file changed

+224
-0
lines changed
Lines changed: 224 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,224 @@
1+
---
2+
updated: 2025-02-12
3+
difficulty: Beginner
4+
content_type: 📝 Tutorial
5+
pcx_content_type: tutorial
6+
title: Setup Prisma Postgres database using Workers
7+
languages:
8+
- TypeScript
9+
- SQL
10+
- Prisma ORM
11+
- PostgreSQL
12+
---
13+
14+
[Prisma Postgres](https://www.prisma.io/postgres) is a managed-PostgreSQL database that has built-in connection pooling, caching, real-time subscriptions, and query optimization recommendations.
15+
16+
In this tutorial, you will learn how to:
17+
18+
- Set up a Cloudflare workers project with [Prisma ORM](https://www.prisma.io/docs).
19+
- Create a Prisma Postgres instance from the CLI.
20+
- Query the database from Workers.
21+
- Deploy the worker to Cloudflare.
22+
23+
## Prerequisites
24+
25+
To follow this guide, ensure you have the following:
26+
27+
- Node.js `v18.18` or higher installed.
28+
- An active [Cloudflare account](https://dash.cloudflare.com/).
29+
- A basic familiarity with installing and using command-line interface (CLI) applications.
30+
31+
## 1. Create a new Worker project
32+
33+
Begin by using [C3](/pages/get-started/c3/) to create a Worker project in the command line:
34+
35+
```sh
36+
npm create cloudflare@latest prisma-postgres-worker -- --type=hello-world --ts=true --git=true --deploy=false
37+
```
38+
39+
Then navigate into your project:
40+
41+
```sh
42+
cd ./prisma-postgres-worker
43+
```
44+
45+
Your initial `src/index.ts` file contains a simple request handler:
46+
47+
```ts title="src/index.ts"
48+
export default {
49+
async fetch(request, env, ctx): Promise<Response> {
50+
return new Response("Hello World!");
51+
},
52+
} satisfies ExportedHandler<Env>;
53+
```
54+
55+
## 2. Setup Prisma in your project
56+
57+
In this step, we set up Prisma ORM with a Prisma Postgres database using the CLI. Then we'll create and execute helper scripts to create tables in our database and generate a Prisma client to query it.
58+
59+
### 2.1. Install required dependencies
60+
61+
Install Prisma CLI as a dev dependency:
62+
63+
```sh
64+
npm install prisma --save-dev
65+
```
66+
67+
Install the [Prisma Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) as that's required for Prisma Postgres:
68+
69+
```sh
70+
npm i @prisma/extension-accelerate
71+
```
72+
73+
Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`:
74+
75+
```sh
76+
npm i -D dotenv-cli
77+
```
78+
79+
### 2.2. Create a Prisma Postgres database and initialize Prisma
80+
81+
Initialize Prisma in your application:
82+
83+
```sh
84+
npx prisma@latest init --db
85+
```
86+
87+
If you don't have an account yet, or if you are not logged in, the command will prompt you to log in using one of the available authentication providers. A browser window will open so you can log in or create an account. Return to the CLI after you have completed this step.
88+
89+
Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region.
90+
91+
After the command runs successfully, it will create:
92+
93+
- A `prisma` folder containing `schema.prisma`, where you will define your database schema.
94+
- An `.env` file in the project root, which will contain the Prisma Postgres database url `DATABASE_URL=<your-prisma-postgres-database-url>`.
95+
96+
You will use a `.dev.vars` file instead of the created `.env` file.
97+
98+
### 2.3. Prepare environment variables
99+
100+
Create a `.dev.vars` file in the root of your application and copy the `DATABASE_URL` from the `.env` file. You can also do this via the CLI:
101+
102+
```sh
103+
cp .env .dev.vars
104+
```
105+
106+
Then, you can remove the `.env` file.
107+
108+
### 2.4. Apply database schema changes
109+
110+
Open the `schema.prisma` file in the `prisma` folder and add the following `User` model to your database:
111+
112+
```prisma title="prisma/schema.prisma"
113+
generator client {
114+
provider = "prisma-client-js"
115+
}
116+
117+
datasource db {
118+
provider = "postgresql"
119+
url = env("DATABASE_URL")
120+
}
121+
122+
model User {
123+
id Int @id @default(autoincrement())
124+
email String
125+
name String
126+
}
127+
```
128+
129+
Next, add the following helper scripts to the `scripts` section of your `package.json`:
130+
131+
```json title="package.json"
132+
"scripts": {
133+
"migrate": "dotenv -e .dev.vars -- npx prisma migrate dev",
134+
"generate": "dotenv -e .dev.vars -- npx prisma generate --no-engine",
135+
"studio": "dotenv -e .dev.vars -- npx prisma studio",
136+
// Additional worker scripts...
137+
}
138+
```
139+
140+
Run the migration script to apply changes to the database:
141+
142+
```sh
143+
npm run migrate
144+
```
145+
146+
When prompted, provide a name for the migration (e.g., `init`).
147+
148+
After these steps are complete, Prisma ORM is fully set up and connected to your Prisma Postgres database.
149+
150+
## 3. Develop the application
151+
152+
Modify the `src/index.ts` file with the following code:
153+
154+
```ts title="src/index.ts"
155+
import { PrismaClient } from "@prisma/client/edge";
156+
import { withAccelerate } from "@prisma/extension-accelerate";
157+
158+
export interface Env {
159+
DATABASE_URL: string;
160+
}
161+
162+
export default {
163+
async fetch(request, env, ctx): Promise<Response> {
164+
const prisma = new PrismaClient({
165+
datasourceUrl: env.DATABASE_URL,
166+
}).$extends(withAccelerate());
167+
168+
await prisma.user.create({
169+
data: {
170+
email: `Jon${Math.ceil(Math.random() * 1000)}@gmail.com`,
171+
name: "Jon Doe",
172+
},
173+
});
174+
175+
const userCount = await prisma.user.count();
176+
177+
return new Response(`Number of users in the database: ${userCount}`);
178+
},
179+
} satisfies ExportedHandler<Env>;
180+
```
181+
182+
Run the development server:
183+
184+
```sh
185+
npm run dev
186+
```
187+
188+
Visit `https://localhost:8787` to see your app in action.
189+
190+
## 4. Deploy the application to Cloudflare
191+
192+
Use the [`npx wrangler secret put` command](/workers/configuration/secrets/#adding-secrets-to-your-project) to upload the `DATABASE_URL`:
193+
194+
```sh
195+
npx wrangler secret put DATABASE_URL
196+
```
197+
198+
When prompted, paste the `DATABASE_URL` value.
199+
200+
Then execute the following command to deploy your project to Cloudflare Workers:
201+
202+
```sh
203+
npm run deploy
204+
```
205+
206+
The `wrangler` CLI will bundle and upload your application.
207+
208+
If you’re not already logged in, the `wrangler` CLI will open a browser window prompting you to log in to the [Cloudflare dashboard](https://dash.cloudflare.com/).
209+
:::note
210+
If you belong to multiple accounts, select the account where you want to deploy the project.
211+
:::
212+
213+
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.
214+
215+
## Next steps
216+
217+
Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers!
218+
219+
To enhance your application further:
220+
221+
- Add [caching](https://www.prisma.io/docs/postgres/caching) to your queries.
222+
- Explore the [Prisma Postgres documentation](https://www.prisma.io/docs/postgres/getting-started).
223+
224+
To see how to build a real-time application with Cloudflare workers and Prisma Postgres, read [this](https://www.prisma.io/docs/guides/prisma-postgres-realtime-on-cloudflare) guide.

0 commit comments

Comments
 (0)