This tutorial demonstrates how to use Drizzle ORM with Vercel Postgres. Vercel Postgres is a serverless SQL database designed to integrate with Vercel Functions and your frontend framework.
This guide assumes familiarity with:
You should have installed Drizzle ORM and Drizzle kit. You can do this by running the following command:
npm
yarn
pnpm
bun
You should have installed dotenv package for managing environment variables. Read more about this package here
npm
yarn
pnpm
bun
You should have installed @vercel/postgres package. Read more about this package here
npm
yarn
pnpm
bun
Check Vercel documentation to learn how to connect to the database with Drizzle ORM.
Setup Vercel Postgres and Drizzle ORM
Create a new Vercel Postgres database
You can create new Vercel Postgres database in the dashboard.
Read Vercel Postgres documentation to learn how to create a new database.
Setup connection string variable
Navigate to your Vercel Postgres database and copy POSTGRES_URL from .env.local section.
Add POSTGRES_URL to your .env.local or .env file.
Connect Drizzle ORM to your database
Create a index.ts file in the src/db directory and set up your database configuration:
Create tables
Create a schema.ts file in the src/db directory and declare your tables:
Setup Drizzle config file
Drizzle config - a configuration file that is used by Drizzle Kit and contains all the information about your database connection, migration folder and schema files.
Create a drizzle.config.ts file in the root of your project and add the following content:
Applying changes to the database
You can generate migrations using drizzle-kit generate command and then run them using the drizzle-kit migrate command.
Generate migrations:
These migrations are stored in the drizzle/migrations directory, as specified in your drizzle.config.ts. This directory will contain the SQL files necessary to update your database schema and a meta folder for storing snapshots of the schema at different migration stages.
Push command is good for situations where you need to quickly test new schema designs or changes in a local development environment, allowing for fast iterations without the overhead of managing migration files.
Basic file structure
This is the basic file structure of the project. In the src/db directory, we have database-related files including connection in index.ts and schema definitions in schema.ts.
Query examples
For instance, we create src/db/queries folder and separate files for each operation: insert, select, update, delete.