Skip to content

Commit 3920f35

Browse files
ankur-archnikolasburkhyperlint-ai[bot]thomasgauvinmikenomitch
authored
[Workers]: Add tutorial to use Prisma Postgres (#19963)
* feat: add blog on using prisma postgres with workers * chore: change the title * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Nikolas <[email protected]> * chore: add secrets adding output * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: hyperlint-ai[bot] <154288675+hyperlint-ai[bot]@users.noreply.github.com> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Thomas Gauvin <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Thomas Gauvin <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Mike Nomitch <[email protected]> * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx Co-authored-by: Mike Nomitch <[email protected]> * chore: add more clarity * Apply suggestions from code review * Update src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx --------- Co-authored-by: Nikolas <[email protected]> Co-authored-by: hyperlint-ai[bot] <154288675+hyperlint-ai[bot]@users.noreply.github.com> Co-authored-by: Thomas Gauvin <[email protected]> Co-authored-by: Mike Nomitch <[email protected]> Co-authored-by: Jun Lee <[email protected]>
1 parent c929635 commit 3920f35

File tree

1 file changed

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

1 file changed

+247
-0
lines changed
Lines changed: 247 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,247 @@
1+
---
2+
updated: 2025-02-12
3+
difficulty: Beginner
4+
content_type: 📝 Tutorial
5+
pcx_content_type: tutorial
6+
title: Set up and use a Prisma Postgres database
7+
languages:
8+
- TypeScript
9+
- SQL
10+
- Prisma ORM
11+
- PostgreSQL
12+
---
13+
14+
[Prisma Postgres](https://www.prisma.io/postgres) is a managed, serverless PostgreSQL database. It supports features like 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 Prisma CLI.
20+
- Model data and run migrations with Prisma Postgres.
21+
- Query the database from Workers.
22+
- Deploy the Worker to Cloudflare.
23+
24+
## Prerequisites
25+
26+
To follow this guide, ensure you have the following:
27+
28+
- Node.js `v18.18` or higher installed.
29+
- An active [Cloudflare account](https://dash.cloudflare.com/).
30+
- A basic familiarity with installing and using command-line interface (CLI) applications.
31+
32+
## 1. Create a new Worker project
33+
34+
Begin by using [C3](/pages/get-started/c3/) to create a Worker project in the command line:
35+
36+
```sh
37+
npm create cloudflare@latest prisma-postgres-worker -- --type=hello-world --ts=true --git=true --deploy=false
38+
```
39+
40+
Then navigate into your project:
41+
42+
```sh
43+
cd ./prisma-postgres-worker
44+
```
45+
46+
Your initial `src/index.ts` file currently contains a simple request handler:
47+
48+
```ts title="src/index.ts"
49+
export default {
50+
async fetch(request, env, ctx): Promise<Response> {
51+
return new Response("Hello World!");
52+
},
53+
} satisfies ExportedHandler<Env>;
54+
```
55+
56+
## 2. Setup Prisma in your project
57+
58+
In this step, you will set up Prisma ORM with a Prisma Postgres database using the CLI. Then you will create and execute helper scripts to create tables in the database and generate a Prisma client to query it.
59+
60+
### 2.1. Install required dependencies
61+
62+
Install Prisma CLI as a dev dependency:
63+
64+
```sh
65+
npm install prisma --save-dev
66+
```
67+
68+
Install the [Prisma Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) as it is required for Prisma Postgres:
69+
70+
```sh
71+
npm install @prisma/extension-accelerate
72+
```
73+
74+
Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`:
75+
76+
```sh
77+
npm install dotenv-cli --save-dev
78+
```
79+
80+
### 2.2. Create a Prisma Postgres database and initialize Prisma
81+
82+
Initialize Prisma in your application:
83+
84+
```sh
85+
npx prisma@latest init --db
86+
```
87+
88+
If you do not have a [Prisma Data Platform](https://console.prisma.io/) 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.
89+
90+
Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region.
91+
92+
Once the command has terminated, it will have created:
93+
94+
- A project in your [Platform Console](https://console.prisma.io/) containing a Prisma Postgres database instance.
95+
- A `prisma` folder containing `schema.prisma`, where you will define your database schema.
96+
- An `.env` file in the project root, which will contain the Prisma Postgres database url `DATABASE_URL=<your-prisma-postgres-database-url>`.
97+
98+
Note that Cloudflare Workers do not support `.env` files. You will use a file called `.dev.vars` instead of the `.env` file that was just created.
99+
100+
### 2.3. Prepare environment variables
101+
102+
Rename the `.env` file in the root of your application to `.dev.vars` file:
103+
104+
```sh
105+
mv .env .dev.vars
106+
```
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 (for example, `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 and replace its contents 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 path = new URL(request.url).pathname;
165+
if (path === "/favicon.ico")
166+
return new Response("Resource not found", {
167+
status: 404,
168+
headers: {
169+
"Content-Type": "text/plain",
170+
},
171+
});
172+
173+
const prisma = new PrismaClient({
174+
datasourceUrl: env.DATABASE_URL,
175+
}).$extends(withAccelerate());
176+
177+
const user = await prisma.user.create({
178+
data: {
179+
email: `Jon${Math.ceil(Math.random() * 1000)}@gmail.com`,
180+
name: "Jon Doe",
181+
},
182+
});
183+
184+
const userCount = await prisma.user.count();
185+
186+
return new Response(`\
187+
Created new user: ${user.name} (${user.email}).
188+
Number of users in the database: ${userCount}.
189+
`);
190+
},
191+
} satisfies ExportedHandler<Env>;
192+
```
193+
194+
Run the development server:
195+
196+
```sh
197+
npm run dev
198+
```
199+
200+
Visit [`https://localhost:8787`](https://localhost:8787) to see your app display the following output:
201+
202+
```sh
203+
Number of users in the database: 1
204+
```
205+
206+
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.
207+
208+
## 4. Deploy the application to Cloudflare
209+
210+
When the application is deployed to Cloudflare, it needs access to the `DATABASE_URL` environment variable that is defined locally in `.dev.vars`. You can use the [`npx wrangler secret put`](/workers/configuration/secrets/#adding-secrets-to-your-project) command to upload the `DATABASE_URL` to the deployment environment:
211+
212+
```sh
213+
npx wrangler secret put DATABASE_URL
214+
```
215+
216+
When prompted, paste the `DATABASE_URL` value (from `.dev.vars`). 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":
217+
218+
```sh
219+
✔ 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? … yes
220+
```
221+
222+
Then execute the following command to deploy your project to Cloudflare Workers:
223+
224+
```sh
225+
npm run deploy
226+
```
227+
228+
The `wrangler` CLI will bundle and upload your application.
229+
230+
If you are 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/).
231+
232+
:::note
233+
If you belong to multiple accounts, select the account where you want to deploy the project.
234+
:::
235+
236+
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.
237+
238+
## Next steps
239+
240+
Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers!
241+
242+
To enhance your application further:
243+
244+
- Add [caching](https://www.prisma.io/docs/postgres/caching) to your queries.
245+
- Explore the [Prisma Postgres documentation](https://www.prisma.io/docs/postgres/getting-started).
246+
247+
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)