Skip to content

Connecting to DB

Course: Serverless Backends - chapter 12

💡 https://www.prisma.io/docs/orm/prisma-client/deployment/edge/deploy-to-cloudflare-workers

Serverless environments have one big problem when dealing with databases.

  1. There can be many connections open to the DB since there can be multiple workers open in various regions

  1. Prisma the library has dependencies that the cloudflare runtime doesn’t understand.

Connection pooling in prisma for serverless env

Section titled “Connection pooling in prisma for serverless env”

💡 https://www.prisma.io/docs/accelerate https://www.prisma.io/docs/orm/prisma-client/deployment/edge/deploy-to-cloudflare-workers

npm install --save-dev prisma
npx prisma init
generator client {
provider = "prisma-client-js"
}
datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}
model User {
id Int @id @default(autoincrement())
name String
email String
password String
}
npx prisma migrate dev --name init
https://console.prisma.io/login

Enable accelerate

Generate an API key

Replace it in .env

DATABASE_URL="prisma://accelerate.prisma-data.net/?api_key=your_key"
npm install @prisma/extension-accelerate
npx prisma generate --no-engine
import { Hono, Next } from 'hono'
import { PrismaClient } from '@prisma/client/edge'
import { withAccelerate } from '@prisma/extension-accelerate'
import { env } from 'hono/adapter'
const app = new Hono()
app.post('/', async (c) => {
// Todo add zod validation here
const body: {
name: string;
email: string;
password: string
} = await c.req.json()
const { DATABASE_URL } = env<{ DATABASE_URL: string }>(c)
const prisma = new PrismaClient({
datasourceUrl: DATABASE_URL,
}).$extends(withAccelerate())
console.log(body)
await prisma.user.create({
data: {
name: body.name,
email: body.email,
password: body.password
}
})
return c.json({msg: "as"})
})
export default app