Drizzle With Fastify

Lighter, Edge-Friendly, SQL-Like

Drizzle With Fastify

Drizzle is a TypeScript-first query builder that compiles to minimal SQL. Its tiny runtime makes it a natural fit for serverless and edge deployments.

4 min read Level 2/5 #fastify#drizzle#orm
What you'll learn
  • Install drizzle-orm and a driver such as postgres-js
  • Build a Drizzle plugin that decorates the app
  • Use the fluent select, insert, and update API

Drizzle is a thin, typed query builder. Unlike Prisma, there is no separate engine binary — just functions that build SQL. That makes it ideal for serverless cold starts and edge runtimes.

Install

npm install drizzle-orm postgres
npm install -D drizzle-kit

Schema & Client

// db/schema.ts
import { pgTable, serial, text, boolean } from 'drizzle-orm/pg-core'

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  email: text('email').notNull().unique(),
  active: boolean('active').default(true),
})
// db/plugin.ts
import fp from 'fastify-plugin'
import { drizzle, type PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import postgres from 'postgres'
import * as schema from './schema.js'

declare module 'fastify' {
  interface FastifyInstance {
    db: PostgresJsDatabase<typeof schema>
  }
}

export default fp(async (app) => {
  const client = postgres(app.config.DATABASE_URL)
  app.decorate('db', drizzle(client, { schema }))
  app.addHook('onClose', async () => {
    await client.end()
  })
})

Fluent Queries

import { eq } from 'drizzle-orm'
import { users } from './db/schema.js'

app.get('/users/:id', async (req) => {
  const { id } = req.params as { id: string }
  const rows = await app.db
    .select()
    .from(users)
    .where(eq(users.id, Number(id)))
  return rows[0] ?? null
})

Drizzle Kit handles migrations: drizzle-kit generate from your schema, then run the SQL.

@fastify/mongodb →