|
| 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 built on unikernels. It supports features like connection pooling, caching, real-time subscriptions, and query optimization recommendations. A generous free tier is available for initial development, testing and hobby projects. |
| 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, 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. |
| 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 that's 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 don't 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 has 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 don't 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 (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 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 prisma = new PrismaClient({ |
| 165 | + datasourceUrl: env.DATABASE_URL, |
| 166 | + }).$extends(withAccelerate()); |
| 167 | + |
| 168 | + const user = 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(`\ |
| 178 | +Created new user: ${user.name} (${user.email}). |
| 179 | +Number of users in the database: ${userCount}. |
| 180 | + `); |
| 181 | + }, |
| 182 | +} satisfies ExportedHandler<Env>; |
| 183 | +``` |
| 184 | + |
| 185 | +Run the development server: |
| 186 | + |
| 187 | +```sh |
| 188 | +npm run dev |
| 189 | +``` |
| 190 | + |
| 191 | +Visit [`https://localhost:8787`](https://localhost:8787) to see your app in action. |
| 192 | + |
| 193 | +## 4. Deploy the application to Cloudflare |
| 194 | + |
| 195 | +When the application is deployed to Cloudflare, it needs access to the `DATABASE_URL` environment variable that's 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: |
| 196 | + |
| 197 | +```sh |
| 198 | +npx wrangler secret put DATABASE_URL |
| 199 | +``` |
| 200 | + |
| 201 | +When prompted, paste the `DATABASE_URL` value (from `.dev.vars`). If you're logged in via the Wrangler CLI, you'll see a prompt asking if you'd like to create a new Worker. Confirm by choosing "yes": |
| 202 | + |
| 203 | +```sh |
| 204 | +✔ 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 |
| 205 | +``` |
| 206 | +
|
| 207 | +Then execute the following command to deploy your project to Cloudflare Workers: |
| 208 | +
|
| 209 | +```sh |
| 210 | +npm run deploy |
| 211 | +``` |
| 212 | +
|
| 213 | +The `wrangler` CLI will bundle and upload your application. |
| 214 | +
|
| 215 | +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/). |
| 216 | +
|
| 217 | +:::note |
| 218 | +If you belong to multiple accounts, select the account where you want to deploy the project. |
| 219 | +::: |
| 220 | +
|
| 221 | +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. |
| 222 | +
|
| 223 | +## Next steps |
| 224 | +
|
| 225 | +Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers! |
| 226 | +
|
| 227 | +To enhance your application further: |
| 228 | +
|
| 229 | +- Add [caching](https://www.prisma.io/docs/postgres/caching) to your queries. |
| 230 | +- Explore the [Prisma Postgres documentation](https://www.prisma.io/docs/postgres/getting-started). |
| 231 | +
|
| 232 | +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