You should have installed the dotenv package for managing environment variables.
npm
yarn
pnpm
bun
Setup Neon and Drizzle ORM
Create a new Neon project
Log in to the Neon Console and navigate to the Projects section. Select a project or click the New Project button to create a new one.
Your Neon projects come with a ready-to-use Postgres database named neondb. We’ll use it in this tutorial.
Setup connection string variable
Navigate to the Connection Details section in the project console to find your database connection string. It should look similar to this:
Add the DATABASE_URL environment variable to your .env or .env.local file, which you’ll use to connect to the Neon database.
Connect Drizzle ORM to your database
Create a db.ts file and set up your database configuration:
Create tables
Create a schema.ts file 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 db.ts, schema definitions in schema.ts, and a migration script in migrate.ts file which is responsible for applying migrations that stored in the migrations directory.
Query examples
For instance, we create src/queries folder and separate files for each operation: insert, select, update, delete.