
TypeScript-first database collections with static type inference and automatic migrations. Built on top of Postgres.js and Zod.
Introduction
import { connect, z } from 'zodgres';
// Connect to database
const db = connect('postgres://user:password@localhost:5432/mydb');
// Define a collection with Zod schema
const users = db.collection('users', {
id: z.number().optional(), // auto-incrementing
name: z.string().max(100),
age: z.number().min(0).max(100).optional(),
});
// Open the connection and run collection migrations
await db.open();
// Create records
const user = await users.create({ name: 'John Doe', age: 30 });
// Result: { id: 1, name: 'John Doe', age: 30 }
// Query records
const allUsers = await users.select(); // or users.select`*`
const adults = await users.select`* WHERE age >= ${18}`;
// Close connection
await db.close();
Features
- 🔒 Type-safe - Full TypeScript support with Zod schema validation
- 🚀 Simple API - Collection-based interface for common database operations
- 📦 Flexible - Works with Postgres or in-memory PGLite for testing
- ⚡ SQL Templates - Use template literals for complex queries
- 🔄 Auto-migration - Automatic table creation from Zod schemas
Installation
npm install zodgres
yarn add zodgres
pnpm add zodgres
bun add zodgres
Database Connection
Connect to a PostgreSQL database using a connection string:
// Local database
const db = connect('postgres://postgres:password@localhost:5432/myapp');
// Remote database with options
const db = connect('postgres://user:pass@host:5432/db', {
max: 10, // Maximum connections
ssl: 'prefer', // SSL mode
});