Skip to content
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

update tutorial on using Prisma with Wokers #595

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 59 additions & 39 deletions examples/prisma.md
Original file line number Diff line number Diff line change
@@ -1,68 +1,66 @@
# Using Prisma on Cloudflare Workers

There are two ways to use Prisma with Cloudflare Workers: using Prisma Accelerate or using the Driver Adapter.
[Prisma ORM](https://www.prisma.io/docs) provides a modern, robust toolkit for interacting with databases. When paired with Hono and Cloudflare Workers, it enables you to deploy high-performance, serverless applications at the edge.

## Using Prisma Accelerate
In this guide, we’ll cover two distinct approaches for using Prisma ORM in Hono:

### Install Prisma
- [**Prisma Postgres**](#using-prisma-postgres):
A managed, serverless PostgreSQL database integration with Prisma. This approach is good for a production-ready setup as Prisma Postgres has built-in connection pooling with zero-cold starts that mitigates [scaling issues in serverless and edge environments]
(https://www.prisma.io/docs/orm/prisma-client/setup-and-configuration/databases-connections#the-serverless-challenge).

Install Prisma on your Hono Cloudflare Workers. Here, I am using neon.tech free tier as my PostgreSQL database, but you can use whichever database suits your project.
- [**Driver adapters**](#using-prisma-driver-adapters):
An alternative that uses Prisma's flexible driver adapters, allowing you to connect to any database supported by Prisma ORM.

Go to [neon.tech](https://neon.tech/) and create a free PostgreSQL database.
Both approaches have their own advantages, allowing you to choose the one that best fits your project's needs.

```bash
npm i prisma --save-dev
npx prisma init
```

### Setup Prisma Accelerate

To setup Accelerate, go to [Prisma Accelerate](https://www.prisma.io/data-platform/accelerate?via=start&gad_source=1&gclid=CjwKCAjwvIWzBhAlEiwAHHWgvX8l8e7xQtqurVYanQ6LmbNheNvCB-4FL0G6BFEfPrUdGyH3qSllqxoCXDoQAvD_BwE) and log in or register for free.

After logging in, you will be taken to a page where you can create a new Accelerate project.

![Accelerate Page](/images/prismaAcceleratePage.png)
## Using Prisma Postgres

Create a new project by clicking the `New project` button, and name your project.
[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.

![Accelerate Page](/images/accelerateCreateProject.png)
### 1. Install Prisma and required dependencies

You will then be taken to a page like the one below:
Install Prisma in your Hono project:

![Accelerate Edit Page](/images/accelerateProjectPage.png)

Click the `Enable Accelerate` button, and you will be taken to the following page:

![Enable Page](/images/EnableAccelerate.png)

Paste your neon.tech database connection string into the `database connection string` field, choose your region, and click the `Enable Accelerate` button.
```bash
npm i prisma --save-dev
```

You will see something like this:
Install the [Prisma client extension](https://www.npmjs.com/package/@prisma/extension-accelerate) that's required for Prisma Postgres:

![API Key](/images/generateApiKey.png)
```sh
npm i @prisma/extension-accelerate
```

Click `Generate API Key` and you will receive a new API key similar to the one below:
Initialize Prisma with an instance of Prisma Postgres:

```bash
DATABASE_URL="prisma://accelerate...."
npx prisma@latest init --db
```

Copy this `DATABASE_URL` and store it in `.dev.vars` and `.env` so that prisma cli can access it later on.
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.

### Set Up Prisma in Your Project
Once logged in (or if you were already logged in), the CLI will prompt you to select a project name and a database region.

The neon.tech URL you received can also be used as an alternative and provide Prisma with more options, so store it for later use:
Once the command has terminated, it has created:

- 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>`.

Create a `.dev.vars` file and store the `DATABASE_URL` in it:
::: code-group

```bash [.dev.vars]
DATABASE_URL="your_prisma_accelerate_url"
DIRECT_URL="your_neon_tech_url
DATABASE_URL="your_prisma_postgres_url"
```

:::

Now, go to your `schema.prisma` file and set the URLs like this:
Keep the `.env` file so that Prisma CLI can access it later on to perform migrations, generate [Prisma Client](https://www.prisma.io/docs/orm/prisma-client) or to open [Prisma Studio](https://www.prisma.io/docs/orm/tools/prisma-studio).

### 2. Set up Prisma in your project

Now, open your `schema.prisma` file and define the models for your database schema. For example, you might add an `User` model:

::: code-group

Expand All @@ -74,12 +72,23 @@ generator client {
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
directUrl = env("DIRECT_URL")
}

model User {
id Int @id @default(autoincrement())
email String
name String
}
```

:::

Use [Prisma Migrate](https://www.prisma.io/docs/orm/prisma-migrate) to apply changes to the database:

```bash
npx prisma migrate dev
```

Create a function like this, which you can use in your project later:

::: code-group
Expand Down Expand Up @@ -126,7 +135,9 @@ app.post('/', async (c) => {

:::

## Using Prisma Driver Adapter
If you want to **use your own database with Prisma ORM** and benefit from connection pooling and edge caching, you can enable Prisma Accelerate. Learn more about setting up [Prisma Accelerate](https://www.prisma.io/docs/accelerate/getting-started) for your project.

## Using Prisma Driver Adapters

Prisma can be used with the D1 Database via `driverAdapters`. The prerequisites are to install Prisma and integrate Wrangler to bind with your Hono project. This is an example project since all documentation for Hono, Prisma, and D1 Cloudflare is separated and doesn't have exact, precise step-by-step instructions.

Expand Down Expand Up @@ -286,3 +297,12 @@ export default app
:::

This will return all users in the `/` route, using Postman or Thunder Client to see the result.

## Resources

You can use the following resources 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).

You can follow the [end-to-end guide from Prisma](https://www.prisma.io/docs/guides/prisma-postgres-realtime-on-cloudflare) to learn how to build a real-time application with Hono and Prisma Postgres, and deploy it to Cloudflare Workers.
Binary file removed public/images/EnableAccelerate.png
Binary file not shown.
Binary file removed public/images/accelerateCreateProject.png
Binary file not shown.
Binary file removed public/images/accelerateProjectPage.png
Binary file not shown.
Binary file removed public/images/generateApiKey.png
Binary file not shown.
Binary file removed public/images/prismaAcceleratePage.png
Binary file not shown.