Build full-stack apps without CRUD boilerplate using Neon + Data API + Better Auth. See a real-world example
/ORMs/Drizzle

Connect from Drizzle to Neon

Learn how to connect to Neon from Drizzle

Pre-built prompt for connecting Node/TypeScript applications to Neon using Drizzle ORM.

What you will learn:

  • How to connect from Drizzle using different drivers

  • How to configure Drizzle Kit for migrations

Drizzle is a modern ORM for TypeScript that provides a simple and type-safe way to interact with your database. This guide demonstrates how to connect your application to a Neon Postgres database using Drizzle ORM.

AI Rules available

Working with AI coding assistants? Check out our AI rules for Drizzle ORM with Neon to help your AI assistant generate better code when using Drizzle with your Neon database.

To connect a TypeScript/Node.js project to Neon using Drizzle ORM, follow these steps:

  1. Create a TypeScript/Node.js project

    Create a new directory for your project and navigate into it:

    mkdir my-drizzle-neon-project cd my-drizzle-neon-project

    Initialize a new Node.js project with a package.json file:

    npm init -y
  2. Create a Neon project

    If you do not have one already, create a Neon project.

    1. Navigate to the Projects page in the Neon Console.
    2. Click New Project.
    3. Specify your project settings and click Create Project.
  3. Get your connection string

    Find your database connection string by clicking the Connect button on your Project Dashboard to open the Connect to your database modal. Select a branch, a user, and the database you want to connect to. A connection string is constructed for you. Connection details modal The connection string includes the user name, password, hostname, and database name.

    Create a .env file in your project's root directory and add the connection string to it. Your .env file should look like this:

    DATABASE_URL="postgresql://[user]:[password]@[neon_hostname]/[dbname]?sslmode=require&channel_binding=require"
  4. Install Drizzle and a driver

    Install Drizzle ORM, Drizzle Kit for migrations, and your preferred database driver. Choose one of the following drivers based on your application's needs:

    Use the Neon serverless HTTP driver for serverless environments (e.g., Vercel, Netlify).

    npm install drizzle-orm @neondatabase/serverless dotenv npm install -D drizzle-kit
  5. Configure Drizzle Kit

    Drizzle Kit uses a configuration file to manage schema and migrations. Create a drizzle.config.ts file in your project root and add the following content. This configuration tells Drizzle where to find your schema and where to output migration files.

    import 'dotenv/config'; import { defineConfig } from 'drizzle-kit';  if (!process.env.DATABASE_URL) {  throw new Error('DATABASE_URL is not set in the .env file'); }  export default defineConfig({  schema: './src/schema.ts', // Your schema file path  out: './drizzle', // Your migrations folder  dialect: 'postgresql',  dbCredentials: {  url: process.env.DATABASE_URL,  }, });
  6. Initialize the Drizzle client

    Create a file: src/db.ts, to initialize and export your Drizzle client. The setup varies depending on the driver you installed.

    import 'dotenv/config'; import { drizzle } from 'drizzle-orm/neon-http'; import { neon } from '@neondatabase/serverless';  const sql = neon(process.env.DATABASE_URL!); export const db = drizzle(sql);
  7. Create a schema

    Drizzle uses a schema-first approach, allowing you to define your database schema using TypeScript. This schema will be used to generate migrations and ensure type safety throughout your application.

    The following example defines a schema for a simple demo_users table. Create a src/schema.ts file and add the following content:

    import { pgTable, serial, text } from 'drizzle-orm/pg-core';  export const demoUsers = pgTable('demo_users', {  id: serial('id').primaryKey(),  name: text('name'), });
  8. Generate migrations

    After defining your schema, you can generate migration files with Drizzle Kit. This will create the necessary SQL files to set up your database schema in Neon.

    npx drizzle-kit generate

    You should see output similar to the following, indicating that migration files have been created:

    $ npx drizzle-kit generate No config path provided, using default 'drizzle.config.ts' Reading config file '/home/user/drizzle/drizzle.config.ts' 1 tables demo_users 2 columns 0 indexes 0 fks  [✓] Your SQL migration file ➜ drizzle/0000_clever_purple_man.sql 🚀

    You can find the generated SQL migration files in the drizzle directory specified in your drizzle.config.ts.

  9. Apply migrations

    Apply the generated migrations (SQL files) to your Neon database using Drizzle Kit. This command will use the drizzle.config.ts file for database connection details and apply the migrations to your Neon database.

    npx drizzle-kit migrate

    You should see output similar to the following, indicating that the migrations have been applied successfully:

    $ npx drizzle-kit migrate No config path provided, using default 'drizzle.config.ts' Reading config file '/home/user/drizzle/drizzle.config.ts' Using 'pg' driver for database querying

    You can verify that the demo_users table has been created in your Neon database by checking the Tables section in the Neon Console.

  10. Query the database

    Create a file: src/index.ts, to interact with your database using the Drizzle client. Here's an example of inserting a new user and querying all users from the demo_users table:

    import { db } from './db'; import { demoUsers } from './schema';  async function main() {  try {  await db.insert(demoUsers).values({ name: 'John Doe' });  const result = await db.select().from(demoUsers);  console.log('Successfully queried the database:', result);  } catch (error) {  console.error('Error querying the database:', error);  } }  main();

    Run the script using tsx:

    npx tsx src/index.ts

    You should see output similar to the following, indicating that the user was inserted and queried successfully:

    Successfully queried the database: [ { id: 1, name: 'John Doe' } ]

Resources

Need help?

Join our Discord Server to ask questions or see what others are doing with Neon. For paid plan support options, see Support.

Last updated on

Was this page helpful?