Type-Safe Queries, Wrapped in a Plugin
Prisma With Fastify
Prisma gives you a fully typed query client generated from a schema. Wrap one PrismaClient in a Fastify plugin and disconnect on shutdown.
What you'll learn
- Install prisma and @prisma/client
- Build a Prisma plugin that decorates the app
- Use generated methods like db.user.findMany in handlers
Prisma is a code-generated ORM: you define models in schema.prisma, run prisma generate, and get a fully typed client. Wrapping it in a Fastify plugin takes about ten lines.
Install & Generate
npm install prisma @prisma/client
npx prisma init
# edit prisma/schema.prisma, then
npx prisma migrate dev --name init
npx prisma generate The Plugin
import fp from 'fastify-plugin'
import { PrismaClient } from '@prisma/client'
declare module 'fastify' {
interface FastifyInstance {
db: PrismaClient
}
}
export default fp(async (app) => {
const prisma = new PrismaClient({ log: ['warn', 'error'] })
await prisma.$connect()
app.decorate('db', prisma)
app.addHook('onClose', async () => {
await prisma.$disconnect()
})
}) Only one PrismaClient per process — instantiating multiple opens redundant pools.
Using the Typed Client
app.get('/users', async () => {
return app.db.user.findMany({
where: { active: true },
select: { id: true, email: true },
})
})
app.post('/users', async (req) => {
const body = req.body as { email: string }
return app.db.user.create({ data: { email: body.email } })
}) The return types are inferred from your schema — rename a column, and the compiler tells you every call that needs updating.
Drizzle With Fastify →