
Building APIs with Drizzle ORM
A comprehensive guide to using Drizzle ORM for type-safe database operations in your Nuxt applications.
Building APIs with Drizzle ORM
Drizzle ORM is a modern, type-safe ORM for TypeScript that makes working with databases a breeze. Let's explore how to integrate it with Nuxt 4.
Why Drizzle ORM?
Drizzle ORM offers several advantages:
- Type Safety: Full TypeScript support with compile-time type checking
- Performance: Minimal overhead and optimized queries
- Developer Experience: Intuitive API and great error messages
- Flexibility: Works with multiple database drivers
Installation
First, install Drizzle ORM and your database driver:
npm install drizzle-orm @libsql/client
npm install -D drizzle-kit
Defining Your Schema
Create your database schema with Drizzle:
import { sqliteTable, text, integer } from "drizzle-orm/sqlite-core"
import { sql } from "drizzle-orm"
export const blogs = sqliteTable("blogs", {
id: integer("id").primaryKey({ autoIncrement: true }),
title: text("title", { length: 255 }).notNull(),
slug: text("slug", { length: 255 }).notNull(),
content: text("content"),
createdAt: text("createdAt").default(sql`CURRENT_TIMESTAMP`),
})
export type Blog = typeof blogs.$inferSelect
export type NewBlog = typeof blogs.$inferInsert
Creating API Endpoints
Create API endpoints in your server/api directory:
// server/api/blogs/index.get.ts
import { db } from "~/server/db"
import { blogs } from "~/server/db/schema"
export default defineEventHandler(async (event) => {
const allBlogs = await db.select().from(blogs)
return allBlogs
})
Querying Data
Drizzle makes querying intuitive:
// Get all blogs
const allBlogs = await db.select().from(blogs)
// Filter with where
const techBlogs = await db.select().from(blogs).where(eq(blogs.category, "tech"))
// Limit and offset
const recentBlogs = await db.select().from(blogs).orderBy(desc(blogs.createdAt)).limit(10)
Inserting Data
Adding new records is type-safe:
await db.insert(blogs).values({
title: "My New Post",
slug: "my-new-post",
content: "This is the content...",
})
Updating Records
Update existing data easily:
await db.update(blogs).set({ title: "Updated Title" }).where(eq(blogs.id, 1))
Migrations
Use Drizzle Kit to manage migrations:
# Generate migrations
npm run db:generate
# Push schema to database
npm run db:push
# Open Drizzle Studio
npm run db:studio
Best Practices
- Use Transactions: For complex operations
- Validate Input: Always validate data before inserting
- Handle Errors: Wrap database calls in try-catch blocks
- Use Prepared Statements: For repeated queries
Conclusion
Drizzle ORM provides a modern, type-safe way to work with databases in your Nuxt applications. Its intuitive API and excellent TypeScript support make it a joy to use.
Try it out in your next project!