Skip to main content
Drizzle ORM is a TypeScript-first ORM that provides type-safe database access with a SQL-like query builder. You can use Drizzle with Xata using either the standard PostgreSQL driver or the serverless driver for edge environments.

Prerequisites

  • Xata account with a project and branch
  • Node.js project with TypeScript

Installation

Install Drizzle ORM and the PostgreSQL driver:
npm install drizzle-orm postgres
npm install -D drizzle-kit

Get your connection string

xata branch url
Set it as an environment variable:
DATABASE_URL=postgresql://user:password@host:port/database

Connect to Xata

Use this for traditional servers and long-running applications:
import { drizzle } from 'drizzle-orm/postgres-js';
import postgres from 'postgres';

const client = postgres(process.env.DATABASE_URL!);
export const db = drizzle(client);

Define your schema

Create a schema.ts file:
import { pgTable, serial, text, timestamp } from 'drizzle-orm/pg-core';

export const users = pgTable('users', {
  id: serial('id').primaryKey(),
  name: text('name').notNull(),
  email: text('email').notNull().unique(),
  createdAt: timestamp('created_at').defaultNow(),
});

Query your database

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

// Insert a user
await db.insert(users).values({
  name: 'Alice',
  email: 'alice@example.com',
});

// Select all users
const allUsers = await db.select().from(users);

// Select with filter
const user = await db
  .select()
  .from(users)
  .where(eq(users.email, 'alice@example.com'));

Configure Drizzle Kit

Create a drizzle.config.ts file for migrations:
import { defineConfig } from 'drizzle-kit';

export default defineConfig({
  schema: './schema.ts',
  out: './drizzle',
  dialect: 'postgresql',
  dbCredentials: {
    url: process.env.DATABASE_URL!,
  },
});

Run migrations

Generate and apply migrations:
# Generate migration files
npx drizzle-kit generate

# Apply migrations
npx drizzle-kit migrate
For serverless environments, consider using the Serverless Proxy to connect over HTTP or WebSocket instead of TCP.