Database
Set up and use the database system using Drizzle ORM with PostgreSQL in The Boring Template.
This template uses Drizzle ORM with PostgreSQL. For more information, visit the Drizzle ORM docs.
Setup
Prerequisites
PostgreSQL
🐘 Database using Neon.tech (or any other PostgreSQL provider)
Node.js
.env.local
Installation
Install the required packages:
Environment Configuration
Add your database URL to your .env.local
file:
Configuration Files
Drizzle Config
Create a drizzle.config.ts
file to configure your database:
Database Client
Set up your database client:
HTTP vs Serverless
The template provides two database clients: one for HTTP and one for
serverless environments. Use db
for regular HTTP operations and dbClient
for server actions with transactions.
Schema Organization
Organize your schemas in the server/drizzle/schema/
directory and export them:
Database Operations
Server Actions
Example of a server action with proper error handling and validation:
Always use transactions when performing multiple related database operations to ensure data consistency.
Frontend Integration
Use React Query mutations for database operations:
Database Schema Example
Here's an example of a database schema definition:
Best Practices
Error Handling
- Wrap database operations in try-catch blocks
- Use proper error types
- Implement proper validation
- Handle edge cases
Security
- Implement rate limiting
- Use transactions for related operations
- Validate all inputs
- Check permissions
Type Safety
- Leverage TypeScript
- Use Drizzle's type inference
- Define proper schemas
- Use Zod validation
Migrations
Drizzle provides tools for creating and running database migrations through the drizzle-kit package.
Generate Migrations
To generate migrations based on your schema changes:
Run Migrations
To apply pending migrations to your database:
Push Schema
For development, you can directly push schema changes:
Use migrations for production environments and db:push only for development.