-
Notifications
You must be signed in to change notification settings - Fork 10.3k
[Workers]: Add tutorial to use Prisma Postgres #19963
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from 24 commits
Commits
Show all changes
31 commits
Select commit
Hold shift + click to select a range
cfb36a9
feat: add blog on using prisma postgres with workers
ankur-arch 0eba281
chore: change the title
ankur-arch f63d044
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch c8a1fe7
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 7bdbbd6
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 4353aed
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch b3a88cc
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch e5d0ddb
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 9c5d4d7
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 208ef7b
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 742072d
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 955c130
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 4e100e2
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch f110199
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 2856c7d
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 6c66bbb
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch cd2ec5c
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 7730c59
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch b7e6305
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 55822d1
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch e5abe97
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch d0fcb32
chore: add secrets adding output
ankur-arch 5ad0159
Merge pull request #1 from ankur-arch/ppg-tutorial
ankur-arch f8b4e4f
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 6e020d4
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 3f7dc93
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch edca933
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 25e15eb
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
ankur-arch 2cdddab
chore: add more clarity
ankur-arch 541a206
Apply suggestions from code review
Oxyjun 3f52c2f
Update src/content/docs/workers/tutorials/using-prisma-postgres-with-…
Oxyjun File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
232 changes: 232 additions & 0 deletions
232
src/content/docs/workers/tutorials/using-prisma-postgres-with-workers/index.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,232 @@ | ||
| --- | ||
| updated: 2025-02-12 | ||
| difficulty: Beginner | ||
| content_type: 📝 Tutorial | ||
| pcx_content_type: tutorial | ||
| title: Set up and use a Prisma Postgres database | ||
| languages: | ||
| - TypeScript | ||
| - SQL | ||
| - Prisma ORM | ||
| - PostgreSQL | ||
| --- | ||
|
|
||
| [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. | ||
|
|
||
| In this tutorial, you will learn how to: | ||
|
|
||
| - Set up a Cloudflare Workers project with [Prisma ORM](https://www.prisma.io/docs). | ||
| - Create a Prisma Postgres instance from the Prisma CLI. | ||
| - Model data and run migrations with Prisma Postgres. | ||
| - Query the database from Workers. | ||
| - Deploy the Worker to Cloudflare. | ||
|
|
||
| ## Prerequisites | ||
|
|
||
| To follow this guide, ensure you have the following: | ||
|
|
||
| - Node.js `v18.18` or higher installed. | ||
| - An active [Cloudflare account](https://dash.cloudflare.com/). | ||
| - A basic familiarity with installing and using command-line interface (CLI) applications. | ||
|
|
||
| ## 1. Create a new Worker project | ||
|
|
||
| Begin by using [C3](/pages/get-started/c3/) to create a Worker project in the command line: | ||
|
|
||
| ```sh | ||
| npm create cloudflare@latest prisma-postgres-worker -- --type=hello-world --ts=true --git=true --deploy=false | ||
| ``` | ||
|
|
||
| Then navigate into your project: | ||
|
|
||
| ```sh | ||
| cd ./prisma-postgres-worker | ||
| ``` | ||
|
|
||
| Your initial `src/index.ts` file currently contains a simple request handler: | ||
|
|
||
| ```ts title="src/index.ts" | ||
| export default { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
| return new Response("Hello World!"); | ||
| }, | ||
| } satisfies ExportedHandler<Env>; | ||
| ``` | ||
|
|
||
| ## 2. Setup Prisma in your project | ||
|
|
||
| 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. | ||
ankur-arch marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### 2.1. Install required dependencies | ||
|
|
||
| Install Prisma CLI as a dev dependency: | ||
|
|
||
| ```sh | ||
| npm install prisma --save-dev | ||
| ``` | ||
|
|
||
| Install the [Prisma Accelerate client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) as that's required for Prisma Postgres: | ||
ankur-arch marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```sh | ||
| npm install @prisma/extension-accelerate | ||
| ``` | ||
|
|
||
| Install the [`dotenv-cli` package](https://www.npmjs.com/package/dotenv-cli) to load environment variables from `.dev.vars`: | ||
|
|
||
| ```sh | ||
| npm install dotenv-cli --save-dev | ||
| ``` | ||
|
|
||
| ### 2.2. Create a Prisma Postgres database and initialize Prisma | ||
|
|
||
| Initialize Prisma in your application: | ||
|
|
||
| ```sh | ||
| npx prisma@latest init --db | ||
| ``` | ||
|
|
||
| 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. | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region. | ||
|
|
||
| Once the command has terminated, it has created: | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| - A project in your [Platform Console](https://console.prisma.io/) containing a Prisma Postgres database instance. | ||
| - A `prisma` folder containing `schema.prisma`, where you will define your database schema. | ||
| - An `.env` file in the project root, which will contain the Prisma Postgres database url `DATABASE_URL=<your-prisma-postgres-database-url>`. | ||
|
|
||
| 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. | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ### 2.3. Prepare environment variables | ||
|
|
||
| Rename the `.env` file in the root of your application to `.dev.vars` file: | ||
|
|
||
| ```sh | ||
| mv .env .dev.vars | ||
| ``` | ||
|
|
||
| ### 2.4. Apply database schema changes | ||
|
|
||
| Open the `schema.prisma` file in the `prisma` folder and add the following `User` model to your database: | ||
|
|
||
| ```prisma title="prisma/schema.prisma" | ||
| generator client { | ||
| provider = "prisma-client-js" | ||
| } | ||
|
|
||
| datasource db { | ||
| provider = "postgresql" | ||
| url = env("DATABASE_URL") | ||
| } | ||
|
|
||
| model User { | ||
| id Int @id @default(autoincrement()) | ||
| email String | ||
| name String | ||
| } | ||
| ``` | ||
|
|
||
| Next, add the following helper scripts to the `scripts` section of your `package.json`: | ||
|
|
||
| ```json title="package.json" | ||
| "scripts": { | ||
| "migrate": "dotenv -e .dev.vars -- npx prisma migrate dev", | ||
| "generate": "dotenv -e .dev.vars -- npx prisma generate --no-engine", | ||
| "studio": "dotenv -e .dev.vars -- npx prisma studio", | ||
| // Additional worker scripts... | ||
| } | ||
| ``` | ||
|
|
||
| Run the migration script to apply changes to the database: | ||
|
|
||
| ```sh | ||
| npm run migrate | ||
| ``` | ||
|
|
||
| When prompted, provide a name for the migration (e.g., `init`). | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| After these steps are complete, Prisma ORM is fully set up and connected to your Prisma Postgres database. | ||
|
|
||
| ## 3. Develop the application | ||
|
|
||
| Modify the `src/index.ts` file and replace its contents with the following code: | ||
|
|
||
| ```ts title="src/index.ts" | ||
| import { PrismaClient } from "@prisma/client/edge"; | ||
| import { withAccelerate } from "@prisma/extension-accelerate"; | ||
|
|
||
| export interface Env { | ||
| DATABASE_URL: string; | ||
| } | ||
|
|
||
| export default { | ||
| async fetch(request, env, ctx): Promise<Response> { | ||
| const prisma = new PrismaClient({ | ||
| datasourceUrl: env.DATABASE_URL, | ||
| }).$extends(withAccelerate()); | ||
ankur-arch marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
|
||
| const user = await prisma.user.create({ | ||
| data: { | ||
| email: `Jon${Math.ceil(Math.random() * 1000)}@gmail.com`, | ||
| name: "Jon Doe", | ||
| }, | ||
| }); | ||
|
|
||
| const userCount = await prisma.user.count(); | ||
|
|
||
| return new Response(`\ | ||
| Created new user: ${user.name} (${user.email}). | ||
| Number of users in the database: ${userCount}. | ||
| `); | ||
| }, | ||
| } satisfies ExportedHandler<Env>; | ||
| ``` | ||
|
|
||
| Run the development server: | ||
|
|
||
| ```sh | ||
| npm run dev | ||
| ``` | ||
|
|
||
| Visit [`https://localhost:8787`](https://localhost:8787) to see your app in action. | ||
ankur-arch marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ## 4. Deploy the application to Cloudflare | ||
|
|
||
| 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: | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```sh | ||
| npx wrangler secret put DATABASE_URL | ||
| ``` | ||
|
|
||
| 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": | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| ```sh | ||
| ✔ 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 | ||
| ``` | ||
|
|
||
| Then execute the following command to deploy your project to Cloudflare Workers: | ||
|
|
||
| ```sh | ||
| npm run deploy | ||
| ``` | ||
|
|
||
| The `wrangler` CLI will bundle and upload your application. | ||
|
|
||
| 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/). | ||
Oxyjun marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
|
|
||
| :::note | ||
| If you belong to multiple accounts, select the account where you want to deploy the project. | ||
| ::: | ||
|
|
||
| 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. | ||
|
|
||
| ## Next steps | ||
|
|
||
| Congratulations on building and deploying a simple application with Prisma Postgres and Cloudflare Workers! | ||
|
|
||
| To enhance your application further: | ||
|
|
||
| - Add [caching](https://www.prisma.io/docs/postgres/caching) to your queries. | ||
| - Explore the [Prisma Postgres documentation](https://www.prisma.io/docs/postgres/getting-started). | ||
|
|
||
| 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. | ||
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.