0
0
NextjsHow-ToBeginner · 4 min read

How to Use Drizzle with Next.js: Setup and Example

To use drizzle with Next.js, install the drizzle-orm package and set up your database connection in a server component or API route. Then, define your schema and use Drizzle's query functions inside Next.js server-side code to interact with your database efficiently.
📐

Syntax

Here is the basic syntax to set up Drizzle ORM with Next.js:

  • import Drizzle and your database client.
  • Define your database schema using Drizzle's schema helpers.
  • Create a Drizzle instance with your database connection.
  • Use Drizzle's query methods inside server components or API routes.
typescript
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import { pgTable, serial, text } from 'drizzle-orm/pg-core';

// Define schema
const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name'),
});

// Create a PostgreSQL pool
const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// Initialize Drizzle
const db = drizzle(pool);

// Example query
async function getUsers() {
  return await db.select().from(users);
}
💻

Example

This example shows a Next.js API route using Drizzle to fetch users from a PostgreSQL database.

typescript
import { NextApiRequest, NextApiResponse } from 'next';
import { drizzle } from 'drizzle-orm/node-postgres';
import { Pool } from 'pg';
import { pgTable, serial, text } from 'drizzle-orm/pg-core';

const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name'),
});

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

const db = drizzle(pool);

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
  try {
    const allUsers = await db.select().from(users);
    res.status(200).json(allUsers);
  } catch (error) {
    res.status(500).json({ error: 'Failed to fetch users' });
  }
}
Output
[{"id":1,"name":"Alice"},{"id":2,"name":"Bob"}]
⚠️

Common Pitfalls

Common mistakes when using Drizzle with Next.js include:

  • Trying to use Drizzle client-side instead of server-side; Drizzle must run on the server.
  • Not properly configuring the database connection string in process.env.DATABASE_URL.
  • Forgetting to await asynchronous Drizzle queries, causing unexpected results.
  • Using Drizzle queries inside React client components instead of server components or API routes.
typescript
/* Wrong: Using Drizzle in a client component (not supported) */

'use client';
import { drizzle } from 'drizzle-orm/node-postgres';

// This will fail because Drizzle needs server environment

/* Right: Use Drizzle in server component or API route */

// See example section for correct usage
📊

Quick Reference

Tips for using Drizzle with Next.js:

  • Always run Drizzle code on the server side (API routes or server components).
  • Use environment variables for database connection strings.
  • Define your schema clearly with Drizzle's schema helpers.
  • Use async/await to handle queries properly.
  • Close database connections if needed to avoid leaks.

Key Takeaways

Use Drizzle ORM only in Next.js server components or API routes, never in client components.
Define your database schema with Drizzle's schema helpers for type-safe queries.
Configure your database connection string securely using environment variables.
Always await Drizzle's async query methods to get correct results.
Handle errors gracefully in API routes to avoid exposing sensitive info.