Lesson 19 / 32
Database Integration
Connect databases through plugins, decorate the instance with a client and close it on shutdown.
Database as a plugin
Initialize the database connection in a plugin and decorate the Fastify instance for use in routes.
Database plugin example
A plugin that sets up a Prisma client and makes it available in routes.
import { PrismaClient } from '@prisma/client';
export default async function dbPlugin(fastify, opts) {
const prisma = new PrismaClient();
fastify.addHook('onClose', async () => {
await prisma.$disconnect();
});
fastify.decorate('db', prisma);
}
// In a route:
fastify.get('/users', async () => {
return await fastify.db.user.findMany();
});Handle connection gracefully
Use the onClose hook to disconnect the database when Fastify shuts down.